qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
3,070,274 | I'm looking for a way to do something like this:
```
// style.css
@def borderSize '2px';
.style {
width: borderSize + 2;
height: borderSize + 2;
}
```
where the width and height attributes would end up having values of 4px. | 2010/06/18 | [
"https://Stackoverflow.com/questions/3070274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317404/"
] | Mozilla kind-of-sort-of-not-really supports this with it's CSS `calc()` function.
This example shamelessly stolen (with attribution!) from [Ajaxian](http://ajaxian.com/archives/css-calc-in-the-house)
```
/*
* Two divs aligned, split up by a 1em margin
*/
#a {
width:75%;
margin-right: 1em;
}
#b {
width: -moz-calc(25% - 1em);
}
```
It's not cross-browser, and it's probably only barely supported by even bleeding-edge versions of Firefox, but there's at least being progress made in that direction. | You could also calculate in your provider method, if you put a parameter in the function:
```
@eval baseFontSize com.myexample.CssSettingsProvider.getBaseFontSize(0)+"pt";
@eval baseFontSize_plus_1 com.myexample.CssSettingsProvider.getBaseFontSize(1)+"pt";
```
`com.myexample.CssSettingsProvider` would look like this:
```
public static int getBaseFontSize(int sizeToAdd) {
if (true) {
return 9 + sizeToAdd;
}
return baseFontSize;
}
``` |
3,070,274 | I'm looking for a way to do something like this:
```
// style.css
@def borderSize '2px';
.style {
width: borderSize + 2;
height: borderSize + 2;
}
```
where the width and height attributes would end up having values of 4px. | 2010/06/18 | [
"https://Stackoverflow.com/questions/3070274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317404/"
] | Sometimes I use the following:
```
@eval BORDER_SIZE_PLUS_2 2+2+"px"; /* GWT evaluates this at compile time! */
```
Oddly, this only works, if you don't put any spaces between the `+` operator and the operands. Also, in @eval you can't use constants that were previously defined by @def. You can however use constants that are defined as static fields in one of your Java classes:
```
@eval BORDER_SIZE_PLUS_2 com.example.MyCssConstants.BORDER_SIZE+2+"px";
```
Or you could let the calculation be performed completely by Java:
```
@eval WIDTH com.example.MyCssCalculations.width(); /* static function,
no parameters! */
@eval HEIGHT com.example.MyCssCalculations.height();
.style {
width: WIDTH;
height: HEIGHT;
}
```
But what I would actually like to do is very similar to your suggestion:
```
@def BORDER_SIZE 2;
.style {
width: value(BORDER_SIZE + 2, 'px'); /* not possible */
height: value(BORDER_SIZE + 3, 'px');
}
```
I don't think that's possible in GWT 2.0. Maybe you find a better solution - here's the [Dev Guide](http://code.google.com/webtoolkit/doc/latest/DevGuideClientBundle.html#CssResource) page on this topic. | You could also calculate in your provider method, if you put a parameter in the function:
```
@eval baseFontSize com.myexample.CssSettingsProvider.getBaseFontSize(0)+"pt";
@eval baseFontSize_plus_1 com.myexample.CssSettingsProvider.getBaseFontSize(1)+"pt";
```
`com.myexample.CssSettingsProvider` would look like this:
```
public static int getBaseFontSize(int sizeToAdd) {
if (true) {
return 9 + sizeToAdd;
}
return baseFontSize;
}
``` |
49,470,764 | Suppose you have 14 bits. How do you determine how many integers can be represented in binary from those 14 bits?
Is it simply just 2^n? So 2^14 = 16384?
Please note this part of the question: "how many INTEGERS can be represented in BINARY...". That's where my confusion lies in what otherwise seems like a fairly straightforward question. If the question was just asking how many different values or numbers can be represented from 14 bits, than yes, I'm certain it's just 2^n. | 2018/03/24 | [
"https://Stackoverflow.com/questions/49470764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8716929/"
] | The answer depends on whether you need signed or unsigned integers.
If you need unsigned integers then using `2^n` you can represent integers from 0 to 2^n exclusive. e.g. n=2; 2^2=4 you can represent the integers from 0 to 4 exclusive (0 to 3 inclusive). Therefore with n bits, you can represent a maximum unsigned integer **value** of `2^n - 1`, but a total count of `2^n` different integers including 0.
If you need signed integers, then half of the values are negative and half of the values are positive and 1 bit is used to indicate whether the integer is positive or negative. You then calculate using using `2^n/2`. e.g. n=2; 2^2/2=2 you can represent the integers from -2 to 2 exclusive (-2 to +1 inclusive). 0 is considered postive, so you get 2 negative values (-2, -1) and 2 positive values (0 and +1). Therefore with n bits, you can represent signed integers **values** between `(-) 2^n/2` and `(+) 2^n/n - 1`, but you still have a total count of `2^n` different integers as you did with the unsigned integers. | Yes, it's that easy as `2^n`.
A bit can have 2 distinct values: 0 and 1.
If you have 2 bits, than you have 4 distinct values: 00, 01, 10, 11. The list goes on.
Combinatorics has the simple counting formula
```
N = n_1 ⋅ n_2 ⋅ ... ⋅ n_k
```
Since `n_1 = n_2 = n_k = 2` you can reduce the formula to
```
N = 2 ^ k
``` |
186,718 | The Bearer: Background
----------------------
---
On Alternate Earth, studies and cases have shown that a *small percentage of the population (10%) is responsible for 90% of the bad luck*.
**These people are targeted by bad luck**, almost by cosmic forces: they are struck by lightning out of a sunny day, hit by cars whose brakes give out, and slip on banana peels in a no-eating zone.
Perhaps the luck is equalized somehow, because these people generally survive or are compensated for the situation.
The general populace once labelled these people as 'clumsy airheads', but following some high profile cases, they have since come to be known as **'Bearers'**, generally ranked class-F through class-A, each about 10x rarer and with worse luck than the next.
**Most of the time, disasters from Bearers do little harm to others**, and class-F through class-B have relatively tame bad luck, ranging respectively from the frequent stubbing of toes and slipping on bananas, to occasional injury and minor destruction of property.
Class-A bearers have a grade of bad luck involving weekly escapes from death, ranging from car crashes, apartment fires, and lightning strikes.
However, at a level 100x rarer and deadlier than class A, Class S Bearers are very rare, sitting at 1/100,000,000 people **but are disproportionately represented in history**: The Explosion of Black Tom Island (1875), the gunpowder explosion of Abbeville (1773), multiple unstoppable wildfires, the 1987 Stock Market Crash, and a [failed rocket launch that killed a cow in Cuba](http://www.digitaljournal.com/tech-and-science/science/herd-shot-around-the-world-the-last-east-coast-polar-launch/article/567614) (1986), to name a few.
Eventually, the world came to know about the potential disasters that could be wreaked by a single bearer in recent times, in Robert's Case (Misc section). After being hit by multiple tsunamis, hurricanes, and other natural disasters caused by one Bearer, the governments decided to change their stance on bearers, to prevent similar tragedies.
Summary: Bearer Information
---------------------------
---
[](https://i.stack.imgur.com/J1vD2.jpg)
* A Bearer's bad luck is related to the recently discovered *Tetroid Waves*
* **The Bad Luck rating can be measured from Tetroid waves**
* E is 10x more bad luck (Tetroids) than F, D is 10x stronger than E, and so on.
* The Tetroid rating from F to S can be equated to local earthquakes (diagram above)
* All humans emit tetroids, Bearers are simply humans with more Tetroids
* It is easy to track Bearers, especially B to S-class, but Tetroid waves can be blocked by some common metals
* Blocking Tetroid waves does not prevent disasters, but does impact interference (see below)\*
* The strength of Tetroid waves emitted prior correspond to the bad luck event that will ensue
* Luck seems to follow laws of conservation; an event of bad luck is equalized by almost equal good luck eventually
* A Bearer can emit Tetroids above their class when in distress, and generally the event triggered aims to solve the Bearer's problems
* Tetroid wave interference happens when two or more Bearers are nearby
* **Paradoxically, destructive interference (cancellation of bad luck) happens when multiple Bearers share similar harmonious emotional states**
* Conversely, constructive interference (amplification of bad luck) happens when multiple Bearers are emotionally chaotic
Question
--------
---
How should the World interact with Bearers, knowing that their numbers are steadily increasing, to best mitigate global and local disasters?
The best answer would also be *humane, properly integrate modern society with the Bearers, and prevent unwarranted discrimination where possible*.
Also, out of interest, who is responsible for the compensation, in the even of an accident? Will insurance rates for Bearers be disproportionately high, or will a common fund exist to support them?
Note: This happens on Alternate Earth, in reality we unfortunately cannot blame stubbed toes on Tetroid waves.
Misc: Robert's Case
-------------------
---
The following case is for background and humor, does not provide too much for question details:
>
> Up until a certain historically significant case, Bearers were not well-quantified or tracked. Domestic Class-S Bearers were not well-monitored or mitigated, and many remained unknown.
>
>
>
> This all changed after a case dealing with Robert 'Bob' Murphy, a seemingly ordinary, if not bad, conductor, who, unknown at the time, was also an S-class Bearer. After a failed concert, the depressed Bob was further implicated by an issue with pyrotechnics, which resulted in multiple casualties and many injuries. Following which Bob was framed by a Syndicate organization, and, charged with multiple murders, sentenced to the electric chair.
>
>
>
> As it turns out, Bob was certainly a bad orchestra conductor, but a good conductor in general; on the hour of his scheduled execution, a critical lightning storm erupted and struck the facility and multiple backup power plants, during which Bob escaped electrocution at the chair for electrocution from the sky. Seizing the chaos, Bob escaped the facility.
>
>
>
> All following attempts to capture Bob were primarily successful, but no results at containment or execution worked: prison vehicles carrying Bob would get flat tires or get into uncanny accidents. Eventually the government gave up and decided to just exile Bob into the ocean with some supplies and a fishing boat, hoping he'd maybe drift onto the shores of their rival country. **This was their worst idea yet.**
>
>
>
> Bob had the bad luck to end up in several tsunamis and hurricanes across the world, causing immense damage to multiple countries, before the United Nations, after an intense investigation, unanimously agreed to compensate him and exonerate him of the crimes he did not commit. To this day, Robert Murphy lives somewhere on an undisclosed island in the Bermuda Triangle.
>
>
>
> Since then, governments around the world have changed their stance and system on the treatment of Bearers, hoping to prevent a similar tragedy.
>
>
> | 2020/10/03 | [
"https://worldbuilding.stackexchange.com/questions/186718",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/68848/"
] | ***Two Roads:***
There are two directions your society can take with regards to bearers, and it somewhat depends on how the actual "ability" functions. The tetroid wave situation is complex, and I think only you fully understand it. Both of these solutions can be applied, or can be exclusive. It's up to you.
1. **Exile**: If the ability doesn't effect disasters outside the bearers, find a geologically stable place isolated from the bulk of humanity and offer a sliding scale of requirements and incentives to these folks to go there. S-scale people might be required to go there but offered vast sums of money in compensation for their troubles, in the same way a typhoid carrier might be required to isolate from those who are at risk. Those with the mildest cases will have no requirement, but will be offered lucrative jobs and compensations to go there. This will be a shifting solution, as asteroids crash there, aliens show up, and hurricanes materialize out of no where to lash (for example) the Aleutian Islands or Siberia. Concentrating these folks may magnify the effect (additive), or bad luck/good luck might cancel itself out and these folks will balance. If there is a hereditary element to this, there is a risk in concentrating this much potential into one breeding population.
2. **Control**: If there is a net total of good and bad luck in the world, and these people just concentrate it, then use them as a guide for these forces. Hurricanes will track towards them, so shift weather patterns to end droughts or avoid direct impacts on major cities. In a real crisis, an S-class talent can probably avert a nuclear attack because the bomb will fizzle out. Nations can pay into an international fund and buy, sell, and trade bad luck in the form of residence for these folks. Cuba gets hit with hurricanes all the time, so why not get paid to sponsor people, then make your nation hurricane-proof? | What about The Fortunate?
=========================
The fortunate would be the opposite end of the spectrum-the people for whom bad luck simply doesn't happen. They are the ones who could build a rocket out of a tin can and successfully circumnavigate the moon down to your simply lucky people who play a good stock market game or enjoy perfect health. They can be paired with the Bearers in areas or missions, so that the catastrophes that are waiting to happen will have generally fortunate results. So your car crash will unite two old lovers, or the hurricane will lead to policy changes desperately needed for decades, or a dropping of scientific papers will lead to the discovery of an unrealized theory. People who specialize in the measurement and classification of bearers would become popular (as mentioned in Enthus3d's comment in the thread) as they could generally mitigate the worst of the bearers. In this way, the bearers would create the chaos to make changes, and the fortunate would be used to change that negative chaos into a positive force for change. |
186,718 | The Bearer: Background
----------------------
---
On Alternate Earth, studies and cases have shown that a *small percentage of the population (10%) is responsible for 90% of the bad luck*.
**These people are targeted by bad luck**, almost by cosmic forces: they are struck by lightning out of a sunny day, hit by cars whose brakes give out, and slip on banana peels in a no-eating zone.
Perhaps the luck is equalized somehow, because these people generally survive or are compensated for the situation.
The general populace once labelled these people as 'clumsy airheads', but following some high profile cases, they have since come to be known as **'Bearers'**, generally ranked class-F through class-A, each about 10x rarer and with worse luck than the next.
**Most of the time, disasters from Bearers do little harm to others**, and class-F through class-B have relatively tame bad luck, ranging respectively from the frequent stubbing of toes and slipping on bananas, to occasional injury and minor destruction of property.
Class-A bearers have a grade of bad luck involving weekly escapes from death, ranging from car crashes, apartment fires, and lightning strikes.
However, at a level 100x rarer and deadlier than class A, Class S Bearers are very rare, sitting at 1/100,000,000 people **but are disproportionately represented in history**: The Explosion of Black Tom Island (1875), the gunpowder explosion of Abbeville (1773), multiple unstoppable wildfires, the 1987 Stock Market Crash, and a [failed rocket launch that killed a cow in Cuba](http://www.digitaljournal.com/tech-and-science/science/herd-shot-around-the-world-the-last-east-coast-polar-launch/article/567614) (1986), to name a few.
Eventually, the world came to know about the potential disasters that could be wreaked by a single bearer in recent times, in Robert's Case (Misc section). After being hit by multiple tsunamis, hurricanes, and other natural disasters caused by one Bearer, the governments decided to change their stance on bearers, to prevent similar tragedies.
Summary: Bearer Information
---------------------------
---
[](https://i.stack.imgur.com/J1vD2.jpg)
* A Bearer's bad luck is related to the recently discovered *Tetroid Waves*
* **The Bad Luck rating can be measured from Tetroid waves**
* E is 10x more bad luck (Tetroids) than F, D is 10x stronger than E, and so on.
* The Tetroid rating from F to S can be equated to local earthquakes (diagram above)
* All humans emit tetroids, Bearers are simply humans with more Tetroids
* It is easy to track Bearers, especially B to S-class, but Tetroid waves can be blocked by some common metals
* Blocking Tetroid waves does not prevent disasters, but does impact interference (see below)\*
* The strength of Tetroid waves emitted prior correspond to the bad luck event that will ensue
* Luck seems to follow laws of conservation; an event of bad luck is equalized by almost equal good luck eventually
* A Bearer can emit Tetroids above their class when in distress, and generally the event triggered aims to solve the Bearer's problems
* Tetroid wave interference happens when two or more Bearers are nearby
* **Paradoxically, destructive interference (cancellation of bad luck) happens when multiple Bearers share similar harmonious emotional states**
* Conversely, constructive interference (amplification of bad luck) happens when multiple Bearers are emotionally chaotic
Question
--------
---
How should the World interact with Bearers, knowing that their numbers are steadily increasing, to best mitigate global and local disasters?
The best answer would also be *humane, properly integrate modern society with the Bearers, and prevent unwarranted discrimination where possible*.
Also, out of interest, who is responsible for the compensation, in the even of an accident? Will insurance rates for Bearers be disproportionately high, or will a common fund exist to support them?
Note: This happens on Alternate Earth, in reality we unfortunately cannot blame stubbed toes on Tetroid waves.
Misc: Robert's Case
-------------------
---
The following case is for background and humor, does not provide too much for question details:
>
> Up until a certain historically significant case, Bearers were not well-quantified or tracked. Domestic Class-S Bearers were not well-monitored or mitigated, and many remained unknown.
>
>
>
> This all changed after a case dealing with Robert 'Bob' Murphy, a seemingly ordinary, if not bad, conductor, who, unknown at the time, was also an S-class Bearer. After a failed concert, the depressed Bob was further implicated by an issue with pyrotechnics, which resulted in multiple casualties and many injuries. Following which Bob was framed by a Syndicate organization, and, charged with multiple murders, sentenced to the electric chair.
>
>
>
> As it turns out, Bob was certainly a bad orchestra conductor, but a good conductor in general; on the hour of his scheduled execution, a critical lightning storm erupted and struck the facility and multiple backup power plants, during which Bob escaped electrocution at the chair for electrocution from the sky. Seizing the chaos, Bob escaped the facility.
>
>
>
> All following attempts to capture Bob were primarily successful, but no results at containment or execution worked: prison vehicles carrying Bob would get flat tires or get into uncanny accidents. Eventually the government gave up and decided to just exile Bob into the ocean with some supplies and a fishing boat, hoping he'd maybe drift onto the shores of their rival country. **This was their worst idea yet.**
>
>
>
> Bob had the bad luck to end up in several tsunamis and hurricanes across the world, causing immense damage to multiple countries, before the United Nations, after an intense investigation, unanimously agreed to compensate him and exonerate him of the crimes he did not commit. To this day, Robert Murphy lives somewhere on an undisclosed island in the Bermuda Triangle.
>
>
>
> Since then, governments around the world have changed their stance and system on the treatment of Bearers, hoping to prevent a similar tragedy.
>
>
> | 2020/10/03 | [
"https://worldbuilding.stackexchange.com/questions/186718",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/68848/"
] | ***Two Roads:***
There are two directions your society can take with regards to bearers, and it somewhat depends on how the actual "ability" functions. The tetroid wave situation is complex, and I think only you fully understand it. Both of these solutions can be applied, or can be exclusive. It's up to you.
1. **Exile**: If the ability doesn't effect disasters outside the bearers, find a geologically stable place isolated from the bulk of humanity and offer a sliding scale of requirements and incentives to these folks to go there. S-scale people might be required to go there but offered vast sums of money in compensation for their troubles, in the same way a typhoid carrier might be required to isolate from those who are at risk. Those with the mildest cases will have no requirement, but will be offered lucrative jobs and compensations to go there. This will be a shifting solution, as asteroids crash there, aliens show up, and hurricanes materialize out of no where to lash (for example) the Aleutian Islands or Siberia. Concentrating these folks may magnify the effect (additive), or bad luck/good luck might cancel itself out and these folks will balance. If there is a hereditary element to this, there is a risk in concentrating this much potential into one breeding population.
2. **Control**: If there is a net total of good and bad luck in the world, and these people just concentrate it, then use them as a guide for these forces. Hurricanes will track towards them, so shift weather patterns to end droughts or avoid direct impacts on major cities. In a real crisis, an S-class talent can probably avert a nuclear attack because the bomb will fizzle out. Nations can pay into an international fund and buy, sell, and trade bad luck in the form of residence for these folks. Cuba gets hit with hurricanes all the time, so why not get paid to sponsor people, then make your nation hurricane-proof? | There is a certain amount of bad luck in the world; we need the Bearers, because otherwise we'd be suffering all that bad luck ourselves
----------------------------------------------------------------------------------------------------------------------------------------
Is it true? Doesn't matter! The most humane route for dealing with Bearers is propaganda on their behalf. These aren't the bad guys, these are the martyrs.
In exactly the same way that a lightning rod protects your house by attracting any lightning away from the more vulnerable parts, Bearers attract the lightning of misfortune away from us regular folk. At least, if they're used correctly. Can we position them to make sure that tsunamis never hit nuclear plants or populated coastal areas? Can they keep the tornadoes away from schools and residential neighborhoods?
Sure, for the protection of regular people, S-Class Bearers cannot be allowed to go wherever they like, whenever they like, but competing institutes for probability research, and other governments and private entities, can try to find ways to make use of these living tetroid generators, be it research or an attempt to focus bad luck. They may find themselves in high demand! (What "luck".)
Don't be surprised, for that matter, if some governments even try to recruit such people into military or espionage roles. Especially if tetroid radiation is difficult to detect, and public spaces cannot easily be made secure against incursion.
Obviously, if Bearers become living weapons, this is going to undermine the Bearer-Martyr propaganda, and you'll end up with a complex effect where many of the general public are unsure what to think. But you can certainly start out with benevolent organizations casting Bearers as the people "taking one for the team", not just being the source of others' misfortune. |
186,718 | The Bearer: Background
----------------------
---
On Alternate Earth, studies and cases have shown that a *small percentage of the population (10%) is responsible for 90% of the bad luck*.
**These people are targeted by bad luck**, almost by cosmic forces: they are struck by lightning out of a sunny day, hit by cars whose brakes give out, and slip on banana peels in a no-eating zone.
Perhaps the luck is equalized somehow, because these people generally survive or are compensated for the situation.
The general populace once labelled these people as 'clumsy airheads', but following some high profile cases, they have since come to be known as **'Bearers'**, generally ranked class-F through class-A, each about 10x rarer and with worse luck than the next.
**Most of the time, disasters from Bearers do little harm to others**, and class-F through class-B have relatively tame bad luck, ranging respectively from the frequent stubbing of toes and slipping on bananas, to occasional injury and minor destruction of property.
Class-A bearers have a grade of bad luck involving weekly escapes from death, ranging from car crashes, apartment fires, and lightning strikes.
However, at a level 100x rarer and deadlier than class A, Class S Bearers are very rare, sitting at 1/100,000,000 people **but are disproportionately represented in history**: The Explosion of Black Tom Island (1875), the gunpowder explosion of Abbeville (1773), multiple unstoppable wildfires, the 1987 Stock Market Crash, and a [failed rocket launch that killed a cow in Cuba](http://www.digitaljournal.com/tech-and-science/science/herd-shot-around-the-world-the-last-east-coast-polar-launch/article/567614) (1986), to name a few.
Eventually, the world came to know about the potential disasters that could be wreaked by a single bearer in recent times, in Robert's Case (Misc section). After being hit by multiple tsunamis, hurricanes, and other natural disasters caused by one Bearer, the governments decided to change their stance on bearers, to prevent similar tragedies.
Summary: Bearer Information
---------------------------
---
[](https://i.stack.imgur.com/J1vD2.jpg)
* A Bearer's bad luck is related to the recently discovered *Tetroid Waves*
* **The Bad Luck rating can be measured from Tetroid waves**
* E is 10x more bad luck (Tetroids) than F, D is 10x stronger than E, and so on.
* The Tetroid rating from F to S can be equated to local earthquakes (diagram above)
* All humans emit tetroids, Bearers are simply humans with more Tetroids
* It is easy to track Bearers, especially B to S-class, but Tetroid waves can be blocked by some common metals
* Blocking Tetroid waves does not prevent disasters, but does impact interference (see below)\*
* The strength of Tetroid waves emitted prior correspond to the bad luck event that will ensue
* Luck seems to follow laws of conservation; an event of bad luck is equalized by almost equal good luck eventually
* A Bearer can emit Tetroids above their class when in distress, and generally the event triggered aims to solve the Bearer's problems
* Tetroid wave interference happens when two or more Bearers are nearby
* **Paradoxically, destructive interference (cancellation of bad luck) happens when multiple Bearers share similar harmonious emotional states**
* Conversely, constructive interference (amplification of bad luck) happens when multiple Bearers are emotionally chaotic
Question
--------
---
How should the World interact with Bearers, knowing that their numbers are steadily increasing, to best mitigate global and local disasters?
The best answer would also be *humane, properly integrate modern society with the Bearers, and prevent unwarranted discrimination where possible*.
Also, out of interest, who is responsible for the compensation, in the even of an accident? Will insurance rates for Bearers be disproportionately high, or will a common fund exist to support them?
Note: This happens on Alternate Earth, in reality we unfortunately cannot blame stubbed toes on Tetroid waves.
Misc: Robert's Case
-------------------
---
The following case is for background and humor, does not provide too much for question details:
>
> Up until a certain historically significant case, Bearers were not well-quantified or tracked. Domestic Class-S Bearers were not well-monitored or mitigated, and many remained unknown.
>
>
>
> This all changed after a case dealing with Robert 'Bob' Murphy, a seemingly ordinary, if not bad, conductor, who, unknown at the time, was also an S-class Bearer. After a failed concert, the depressed Bob was further implicated by an issue with pyrotechnics, which resulted in multiple casualties and many injuries. Following which Bob was framed by a Syndicate organization, and, charged with multiple murders, sentenced to the electric chair.
>
>
>
> As it turns out, Bob was certainly a bad orchestra conductor, but a good conductor in general; on the hour of his scheduled execution, a critical lightning storm erupted and struck the facility and multiple backup power plants, during which Bob escaped electrocution at the chair for electrocution from the sky. Seizing the chaos, Bob escaped the facility.
>
>
>
> All following attempts to capture Bob were primarily successful, but no results at containment or execution worked: prison vehicles carrying Bob would get flat tires or get into uncanny accidents. Eventually the government gave up and decided to just exile Bob into the ocean with some supplies and a fishing boat, hoping he'd maybe drift onto the shores of their rival country. **This was their worst idea yet.**
>
>
>
> Bob had the bad luck to end up in several tsunamis and hurricanes across the world, causing immense damage to multiple countries, before the United Nations, after an intense investigation, unanimously agreed to compensate him and exonerate him of the crimes he did not commit. To this day, Robert Murphy lives somewhere on an undisclosed island in the Bermuda Triangle.
>
>
>
> Since then, governments around the world have changed their stance and system on the treatment of Bearers, hoping to prevent a similar tragedy.
>
>
> | 2020/10/03 | [
"https://worldbuilding.stackexchange.com/questions/186718",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/68848/"
] | ### Vigilantism, Genocide & Eugenics
I'm sorry to basically go full Nazi on the first answer here.
History shows us what happens when we scapegoat a particular group of people as being responsible for all the suffering in the world. Replace ["The Eternal Jew"](https://encyclopedia.ushmm.org/content/en/article/nazi-propaganda)-style propaganda with "Here is this scientific proof that this group of people are making your life worse". You've basically got a "just add water" holocaust ready-to-go, without the need for a propaganda ministry.
They will be:
* The subject of vigilante attacks. If your existence was somehow causing hundreds of deaths, most moderate people would want to exile you to stop the damage, but some nut will want to kill you. That nutcase may have access to weapons and a Thetan (sorry - Tetroid) detector.
* In some countries they will be exiled away from population centres, "Ghettos" but further away.
* Some countries will class them as terrorists as put them to death.
* Eventually this will become some form of democide - either hidden (eg CIA assassination sort of things), or more like "Final Solution" level horrors, as the Ghettos are silently "dealt with".
* Researchers will try to detect what gene influences this condition. Pregnant mothers will have their babies screened for it and termination "requested". | What about The Fortunate?
=========================
The fortunate would be the opposite end of the spectrum-the people for whom bad luck simply doesn't happen. They are the ones who could build a rocket out of a tin can and successfully circumnavigate the moon down to your simply lucky people who play a good stock market game or enjoy perfect health. They can be paired with the Bearers in areas or missions, so that the catastrophes that are waiting to happen will have generally fortunate results. So your car crash will unite two old lovers, or the hurricane will lead to policy changes desperately needed for decades, or a dropping of scientific papers will lead to the discovery of an unrealized theory. People who specialize in the measurement and classification of bearers would become popular (as mentioned in Enthus3d's comment in the thread) as they could generally mitigate the worst of the bearers. In this way, the bearers would create the chaos to make changes, and the fortunate would be used to change that negative chaos into a positive force for change. |
186,718 | The Bearer: Background
----------------------
---
On Alternate Earth, studies and cases have shown that a *small percentage of the population (10%) is responsible for 90% of the bad luck*.
**These people are targeted by bad luck**, almost by cosmic forces: they are struck by lightning out of a sunny day, hit by cars whose brakes give out, and slip on banana peels in a no-eating zone.
Perhaps the luck is equalized somehow, because these people generally survive or are compensated for the situation.
The general populace once labelled these people as 'clumsy airheads', but following some high profile cases, they have since come to be known as **'Bearers'**, generally ranked class-F through class-A, each about 10x rarer and with worse luck than the next.
**Most of the time, disasters from Bearers do little harm to others**, and class-F through class-B have relatively tame bad luck, ranging respectively from the frequent stubbing of toes and slipping on bananas, to occasional injury and minor destruction of property.
Class-A bearers have a grade of bad luck involving weekly escapes from death, ranging from car crashes, apartment fires, and lightning strikes.
However, at a level 100x rarer and deadlier than class A, Class S Bearers are very rare, sitting at 1/100,000,000 people **but are disproportionately represented in history**: The Explosion of Black Tom Island (1875), the gunpowder explosion of Abbeville (1773), multiple unstoppable wildfires, the 1987 Stock Market Crash, and a [failed rocket launch that killed a cow in Cuba](http://www.digitaljournal.com/tech-and-science/science/herd-shot-around-the-world-the-last-east-coast-polar-launch/article/567614) (1986), to name a few.
Eventually, the world came to know about the potential disasters that could be wreaked by a single bearer in recent times, in Robert's Case (Misc section). After being hit by multiple tsunamis, hurricanes, and other natural disasters caused by one Bearer, the governments decided to change their stance on bearers, to prevent similar tragedies.
Summary: Bearer Information
---------------------------
---
[](https://i.stack.imgur.com/J1vD2.jpg)
* A Bearer's bad luck is related to the recently discovered *Tetroid Waves*
* **The Bad Luck rating can be measured from Tetroid waves**
* E is 10x more bad luck (Tetroids) than F, D is 10x stronger than E, and so on.
* The Tetroid rating from F to S can be equated to local earthquakes (diagram above)
* All humans emit tetroids, Bearers are simply humans with more Tetroids
* It is easy to track Bearers, especially B to S-class, but Tetroid waves can be blocked by some common metals
* Blocking Tetroid waves does not prevent disasters, but does impact interference (see below)\*
* The strength of Tetroid waves emitted prior correspond to the bad luck event that will ensue
* Luck seems to follow laws of conservation; an event of bad luck is equalized by almost equal good luck eventually
* A Bearer can emit Tetroids above their class when in distress, and generally the event triggered aims to solve the Bearer's problems
* Tetroid wave interference happens when two or more Bearers are nearby
* **Paradoxically, destructive interference (cancellation of bad luck) happens when multiple Bearers share similar harmonious emotional states**
* Conversely, constructive interference (amplification of bad luck) happens when multiple Bearers are emotionally chaotic
Question
--------
---
How should the World interact with Bearers, knowing that their numbers are steadily increasing, to best mitigate global and local disasters?
The best answer would also be *humane, properly integrate modern society with the Bearers, and prevent unwarranted discrimination where possible*.
Also, out of interest, who is responsible for the compensation, in the even of an accident? Will insurance rates for Bearers be disproportionately high, or will a common fund exist to support them?
Note: This happens on Alternate Earth, in reality we unfortunately cannot blame stubbed toes on Tetroid waves.
Misc: Robert's Case
-------------------
---
The following case is for background and humor, does not provide too much for question details:
>
> Up until a certain historically significant case, Bearers were not well-quantified or tracked. Domestic Class-S Bearers were not well-monitored or mitigated, and many remained unknown.
>
>
>
> This all changed after a case dealing with Robert 'Bob' Murphy, a seemingly ordinary, if not bad, conductor, who, unknown at the time, was also an S-class Bearer. After a failed concert, the depressed Bob was further implicated by an issue with pyrotechnics, which resulted in multiple casualties and many injuries. Following which Bob was framed by a Syndicate organization, and, charged with multiple murders, sentenced to the electric chair.
>
>
>
> As it turns out, Bob was certainly a bad orchestra conductor, but a good conductor in general; on the hour of his scheduled execution, a critical lightning storm erupted and struck the facility and multiple backup power plants, during which Bob escaped electrocution at the chair for electrocution from the sky. Seizing the chaos, Bob escaped the facility.
>
>
>
> All following attempts to capture Bob were primarily successful, but no results at containment or execution worked: prison vehicles carrying Bob would get flat tires or get into uncanny accidents. Eventually the government gave up and decided to just exile Bob into the ocean with some supplies and a fishing boat, hoping he'd maybe drift onto the shores of their rival country. **This was their worst idea yet.**
>
>
>
> Bob had the bad luck to end up in several tsunamis and hurricanes across the world, causing immense damage to multiple countries, before the United Nations, after an intense investigation, unanimously agreed to compensate him and exonerate him of the crimes he did not commit. To this day, Robert Murphy lives somewhere on an undisclosed island in the Bermuda Triangle.
>
>
>
> Since then, governments around the world have changed their stance and system on the treatment of Bearers, hoping to prevent a similar tragedy.
>
>
> | 2020/10/03 | [
"https://worldbuilding.stackexchange.com/questions/186718",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/68848/"
] | ### Vigilantism, Genocide & Eugenics
I'm sorry to basically go full Nazi on the first answer here.
History shows us what happens when we scapegoat a particular group of people as being responsible for all the suffering in the world. Replace ["The Eternal Jew"](https://encyclopedia.ushmm.org/content/en/article/nazi-propaganda)-style propaganda with "Here is this scientific proof that this group of people are making your life worse". You've basically got a "just add water" holocaust ready-to-go, without the need for a propaganda ministry.
They will be:
* The subject of vigilante attacks. If your existence was somehow causing hundreds of deaths, most moderate people would want to exile you to stop the damage, but some nut will want to kill you. That nutcase may have access to weapons and a Thetan (sorry - Tetroid) detector.
* In some countries they will be exiled away from population centres, "Ghettos" but further away.
* Some countries will class them as terrorists as put them to death.
* Eventually this will become some form of democide - either hidden (eg CIA assassination sort of things), or more like "Final Solution" level horrors, as the Ghettos are silently "dealt with".
* Researchers will try to detect what gene influences this condition. Pregnant mothers will have their babies screened for it and termination "requested". | There is a certain amount of bad luck in the world; we need the Bearers, because otherwise we'd be suffering all that bad luck ourselves
----------------------------------------------------------------------------------------------------------------------------------------
Is it true? Doesn't matter! The most humane route for dealing with Bearers is propaganda on their behalf. These aren't the bad guys, these are the martyrs.
In exactly the same way that a lightning rod protects your house by attracting any lightning away from the more vulnerable parts, Bearers attract the lightning of misfortune away from us regular folk. At least, if they're used correctly. Can we position them to make sure that tsunamis never hit nuclear plants or populated coastal areas? Can they keep the tornadoes away from schools and residential neighborhoods?
Sure, for the protection of regular people, S-Class Bearers cannot be allowed to go wherever they like, whenever they like, but competing institutes for probability research, and other governments and private entities, can try to find ways to make use of these living tetroid generators, be it research or an attempt to focus bad luck. They may find themselves in high demand! (What "luck".)
Don't be surprised, for that matter, if some governments even try to recruit such people into military or espionage roles. Especially if tetroid radiation is difficult to detect, and public spaces cannot easily be made secure against incursion.
Obviously, if Bearers become living weapons, this is going to undermine the Bearer-Martyr propaganda, and you'll end up with a complex effect where many of the general public are unsure what to think. But you can certainly start out with benevolent organizations casting Bearers as the people "taking one for the team", not just being the source of others' misfortune. |
128,386 | I have these scripts I made that work absolutely perfectly as I need them to. Is there any improvements that can be done to these scripts and make them more efficient for Mobile Platforms? Or even just combine them into one script?
These 4 scripts are just about identical except that each one controls a different obstacle and I have it that way so I can have more control over each individual obstacle. Does that make sense? (For instance, I want one obstacle to start spawning 10 seconds into the game and another to spawn RIGHT when the game starts).
Obstacle 1:
```
using UnityEngine;
using System.Collections;
[System.Serializable] // Serialize this so it looks neater in the inspector
public class Obstacle1 // Hammer Obstacle
{
public GameObject hammer; // The first obstacle gameobject. This is attached in the inspector.
public Vector3 spawnHPosValues; // Where the first obstacle will be spawned at on the X,Y,Z plane.
public int hCount; // This is the count of the first obstacle in a given wave. //
public float hSpawnWait; // Time in seconds between next wave of obstacle 1.
public float hStartGameWait; // Time in seconds between when the game starts and when the first obstacle start spawning.
public float hWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 1 will spawn.
}
public class SpawnHammers : MonoBehaviour {
public Obstacle1 obstacle1; // Reference to the Obstacle 1 class //
void Start () {
StartCoroutine (SpawnHammer ()); // at the beginning of the game, start to function SpawnHammer() //
}
IEnumerator SpawnHammer () {
yield return new WaitForSeconds(obstacle1.hStartGameWait);
while (true)
{
for (int i = 0; i < obstacle1.hCount; i++) {
Vector3 spawnPosition = new Vector3 (Random.Range(-obstacle1.spawnHPosValues.x, obstacle1.spawnHPosValues.x),
obstacle1.spawnHPosValues.y,
obstacle1.spawnHPosValues.z); // I choose where I spawn the obstacles on the X,Y,Z planes. Only the X
// plane will be random
Quaternion spawnRotation = Quaternion.identity; // Spawn with NO rotation
Instantiate (obstacle1.hammer, spawnPosition, spawnRotation); // Bring the object into the scene
yield return new WaitForSeconds(obstacle1.hSpawnWait); // Spawn a new obstacle
}
yield return new WaitForSeconds (obstacle1.hWaveSpawnWait); // Start the new wave of obstacles
}
}
}
```
Obstacle 2:
```
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Obstacle2 // Road Barrier Obstacle
{
public GameObject roadBarrier; // The second obstacle gameobject. This is attached in the inspector.
public Vector3 spawnRBPosValues; // Where the second obstacle will be spawned at on the X,Y,Z plane.
public int rbCount; // This is the count of the second obstacle in a given wave. //
public float rbSpawnWait; // Time in seconds between next wave of obstacle 2.
public float rbStartGameWait; // Time in seconds between when the game starts and when the second obstacle will start spawning.
public float rbWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 2 will spawn.
}
public class SpawnRoadBarriers : MonoBehaviour {
public Obstacle2 obstacle2;
void Start () {
StartCoroutine (SpawnRoadBarrier ());
}
IEnumerator SpawnRoadBarrier () {
yield return new WaitForSeconds(obstacle2.rbStartGameWait);
while (true)
{
for (int i = 0; i < obstacle2.rbCount; i++) {
Vector3 spawnPosition = new Vector3 (Random.Range(-obstacle2.spawnRBPosValues.x, obstacle2.spawnRBPosValues.x),
obstacle2.spawnRBPosValues.y,
obstacle2.spawnRBPosValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (obstacle2.roadBarrier, spawnPosition, spawnRotation);
yield return new WaitForSeconds(obstacle2.rbSpawnWait);
}
yield return new WaitForSeconds (obstacle2.rbWaveSpawnWait);
}
}
}
```
Obstacle 3:
```
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Obstacle3 // Cone Obstacle
{
public GameObject cone; // The third obstacle gameobject. This is attached in the inspector.
public Vector3 spawnCPosValues; // Where the third obstacle will be spawned at on the X,Y,Z plane.
public int cCount; // This is the count of the third obstacle in a given wave.
public float cSpawnWait; // Time in seconds between next wave of obstacle 3.
public float cStartGameWait; // Time in seconds between when the game starts and when the third obstacle start spawning.
public float cWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 3 will spawn.
}
public class SpawnCones : MonoBehaviour {
public Obstacle3 obstacle3;
void Start () {
StartCoroutine (SpawnCone ());
}
IEnumerator SpawnCone () {
yield return new WaitForSeconds(obstacle3.cStartGameWait);
while (true)
{
for (int i = 0; i < obstacle3.cCount; i++) {
Vector3 spawnPosition = new Vector3 (Random.Range(-obstacle3.spawnCPosValues.x, obstacle3.spawnCPosValues.x),
obstacle3.spawnCPosValues.y,
obstacle3.spawnCPosValues.z);
Quaternion spawnRotation = Quaternion.Euler(0f,0f,90f); // rotate 90 degrees on the Z axis
Instantiate (obstacle3.cone, spawnPosition, spawnRotation);
yield return new WaitForSeconds(obstacle3.cSpawnWait);
}
yield return new WaitForSeconds (obstacle3.cWaveSpawnWait);
}
}
}
```
Obstacle 4:
```
using UnityEngine;
using System.Collections;
[System.Serializable]
public class Obstacle4 // Barrel Obstacle
{
public GameObject barrel; // The fourth obstacle gameobject. This is attached in the inspector.
public Vector3 spawnBPosValues; // Where the fourth obstacle will be spawned at on the X,Y,Z plane.
public int bCount; // This is the count of the fourth obstacle in a given wave.
public float bSpawnWait; // Time in seconds between next wave of obstacle 4.
public float bStartGameWait; // Time in seconds between when the game starts and when the fourth obstacle start spawning.
public float bWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 4 will spawn.
}
public class SpawnBarrels : MonoBehaviour {
public Obstacle4 obstacle4;
void Start () {
StartCoroutine (SpawnBarrel ());
}
IEnumerator SpawnBarrel () {
yield return new WaitForSeconds(obstacle4.bStartGameWait);
while (true)
{
for (int i = 0; i < obstacle4.bCount; i++) {
Vector3 spawnPosition = new Vector3 (Random.Range(-obstacle4.spawnBPosValues.x, obstacle4.spawnBPosValues.x),
obstacle4.spawnBPosValues.y,
obstacle4.spawnBPosValues.z);
Quaternion spawnRotation = Quaternion.Euler(0f,0f,90f); // rotate 90 degrees on the Z axis
Instantiate (obstacle4.barrel, spawnPosition, spawnRotation);
yield return new WaitForSeconds(obstacle4.bSpawnWait);
}
yield return new WaitForSeconds (obstacle4.bWaveSpawnWait);
}
}
}
``` | 2016/05/14 | [
"https://codereview.stackexchange.com/questions/128386",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/103199/"
] | 1. **Bracket alignment**. For some reason, all obstacle classes and `while`-loops are written with vertically aligned bracket, while the `MonoBehaviour`s are egyptians.
>
> [Coding style] create a consistent look to the code, so that readers can focus on content, not layout. - [C# Coding Convention](https://msdn.microsoft.com/en-us/library/ff926074.aspx)
>
>
>
And, the commonly agreed convention for this one is vertically aligned,
2. **Naming**.
1. Do not abbreviate the variable name... Go for the full name, with exception of some **short** lambda functions', event handlers' parameters and `for`-loops' variables.
At first, I thought they were some kind of hungarian notation, and had trouble figuring out what kind of handles are they? It was until I saw the next obstacle class that I realize it was `h` for `Hammer`!
```
public class Obstacle1 // Hammer Obstacle
{
public GameObject hammer; // The first obstacle gameobject. This is attached in the inspector.
public Vector3 spawnHPosValues; // Where the first obstacle will be spawned at on the X,Y,Z plane.
public int hCount; // This is the count of the first obstacle in a given wave. //
public float hSpawnWait; // Time in seconds between next wave of obstacle 1.
public float hStartGameWait; // Time in seconds between when the game starts and when the first obstacle start spawning.
public float hWaveSpawnWait; // Time in seconds between waves when the next wave of obstacle 1 will spawn.
}
```
So, do use the full name, like `spawnHammerPosition`, `hammerCount` and so on... It does irk a bit, but I will refactor this with other `Obstacle`s later.
2. In this bit of code
```
var spawnRotation = Quaternion.identity; // Spawn with NO rotation
Instantiate(hammer.GameObject, spawnPosition, spawnRotation); // Bring the object into the scene
```
Instead of `spawnRotation`, you could have gone with `noRotation` and gotten rid of the comment.
```
var noRotation = Quaternion.identity;
Instantiate(hammer.GameObject, spawnPosition, noRotation); // Bring the object into the scene
```
Or, if you are proficient enough, just inline it.
3. Normally, you should use PascalCase for `public` menbers, and not camelCase. However, Unity3D seems favor the latter. Therefore, it is up to you to decide. (`Quaternion.identity` `*twiches eye*`)
4. When your method name is already `SpawnObstacles`, you don't also have to name the local variable `spawnPosition`, just `position` should suffice.
5. Class name should never be plurial, and never a verb or verb+complement.
>
> This distinguishes type names from methods, which are named with verb phrases. - [Names of Classes, Structs, and Interfaces](https://msdn.microsoft.com/en-us/library/ms229040(v=vs.110).aspx)
>
>
>
`SpawnHammers` -> `HammerSpawner`
3. I don't understand, why you have 4 different classes with the same properties and copy-pasta comments, and, most importantly, shareing the same role of obstacle.
Combine them into a single class, subclass if you had to keep the class name for distinction :
```
[Serializable]
public abstract class Obstacle
{
public GameObject gameObject;
public Vector3 spawnPosition;
public int spawnCount;
public float spawnWait;
public float startGameWait;
public float waveSpawnWait;
}
public class Hammer : Obstacle { }
public class RoadBarrier : Obstacle { }
public class Cone : Obstacle { }
public class Barrel : Obstacle { }
```
4. Try keep the line width not too long and don't align the parameters :
```
// compare these two :
Vector3 spawnPosition = new Vector3(Random.Range(-cone.spawnCPosValues.x, cone.spawnCPosValues.x),
cone.spawnCPosValues.y,
cone.spawnCPosValues.z);
Vector3 spawnPosition = new Vector3(
Random.Range(-cone.spawnCPosValues.x, cone.spawnCPosValues.x),
cone.spawnCPosValues.y,
cone.spawnCPosValues.z);
```
5. As you have already noticed, all 4 spawners' implementation are quite repetitive, namely the waiting part. However, each obstacle has its own spawn rotation and position. So, we will have to extract the former while isolating the latter :
```
public abstract class ObstacleSpawnerBase : MonoBehaviour
{
public Obstacle obstacle;
void Start()
{
StartCoroutine(SpawnObstacles());
}
// the repeated pattern in SpawnXXXXs has been extracted to here
IEnumerator SpawnObstacles()
{
yield return new WaitForSeconds(obstacle.startGameWait);
while (true)
{
foreach (var obstacle in SpawnObstaclesImpl())
yield return new WaitForSeconds(obstacle.spawnWait);
yield return new WaitForSeconds(obstacle.waveSpawnWait);
}
}
// with the actual implementation detail separated for customization
protected abstract IEnumerable<WaitForSeconds> SpawnObstaclesImpl();
}
```
And the concrete obstacle spawner classes :
```
public class HammerSpawner : ObstacleSpawnerBase
{
protected override IEnumerable SpawnObstaclesImpl()
{
for (int i = 0; i < obstacle.spawnCount; i++)
{
// randomize x-axis
var position = new Vector3(
Random.Range(-obstacle.spawnPosition.x, obstacle.spawnPosition.x),
obstacle.spawnPosition.y,
obstacle.spawnPosition.z);
// bring the object into the scene
yield return Instantiate(obstacle.gameObject, position, Quaternion.identity);
}
}
}
public class RoadBarrierSpawner : ObstacleSpawnerBase
{
protected override IEnumerable SpawnObstaclesImpl()
{
for (int i = 0; i < obstacle.spawnCount; i++)
{
var position = new Vector3(
Random.Range(-obstacle.spawnPosition.x, obstacle.spawnPosition.x),
obstacle.spawnPosition.y,
obstacle.spawnPosition.z);
yield return Instantiate(obstacle.gameObject, position, Quaternion.identity);
}
}
}
public class ConeSpawner : ObstacleSpawnerBase
{
protected override IEnumerable SpawnObstaclesImpl()
{
for (int i = 0; i < obstacle.spawnCount; i++)
{
var position = new Vector3(
Random.Range(-obstacle.spawnPosition.x, obstacle.spawnPosition.x),
obstacle.spawnPosition.y,
obstacle.spawnPosition.z);
// rotate 90 degrees on the Z axis
var rotation = Quaternion.Euler(0f, 0f, 90f);
yield return Instantiate(obstacle.gameObject, position, rotation);
}
}
}
public class BarrelSpawner : ObstacleSpawnerBase
{
protected override IEnumerable SpawnObstaclesImpl()
{
for (int i = 0; i < obstacle.spawnCount; i++)
{
var position = new Vector3(
Random.Range(-obstacle.spawnPosition.x, obstacle.spawnPosition.x),
obstacle.spawnPosition.y,
obstacle.spawnPosition.z);
// rotate 90 degrees on the Z axis
var rotation = Quaternion.Euler(0f, 0f, 90f);
yield return Instantiate(obstacle.gameObject, position, rotation);
}
}
}
```
Normally, I would use generic here, but Unity3D seems to have some problems with generic `MonoBehaviour`, so I left it out. However, do give them a try :
```
public abstract class ObstacleSpawnerBase<TObstacle> : MonoBehaviour
where TObstacle : Obstacle
{
// ...
}
public class HammerSpawner : ObstacleSpawnerBase<Hammer> { /*...*/ }
public class RoadBarrierSpawner : ObstacleSpawnerBase<RoadBarrier> { /*...*/ }
public class ConeSpawner : ObstacleSpawnerBase<Cone> { /*...*/ }
public class BarrelSpawner : ObstacleSpawnerBase<Barrel> { /*...*/ }
``` | You only need one `Obstacle` class, and then you can create four instances of it. Your "Spawn" methods can be extracted into a single method, with parameters to handle the differences. For example, because `spawnRotation` not the same for each obstacle, you can have that be a parameter or a variable in the `Obstacle` class. |
40,802 | I need to compute the Drazin inverse $A^D$ of a singular M-matrix $A$, i.e., a matrix in the form $A=\lambda I -P$, where $P$ has nonnegative entries and $\lambda$ is the spectral radius (Perron value) of $P$. I already know the right and left eigenvectors $v$ and $u^T$ of $P$ with eigenvalue $\lambda$ (that is, the vectors in the left and right kernel of $A$).
1) Is there a Matlab subroutine around for computing Drazin inverses? I can't seem to find any, so I had to create my own (which is probably very inefficient)
2) Is there a way to exploit the knowledge of the two nullspaces (and the fact that they are 1-dimensional) to speed up this computation? | 2010/10/02 | [
"https://mathoverflow.net/questions/40802",
"https://mathoverflow.net",
"https://mathoverflow.net/users/1898/"
] | If you have access to Matlab, and the matrix is not gigantic
you can use the following to calculate the Drazin inverse:
1. Determine the index of $A$, i.e, does $\mathrm{rank}(A^k) = \mathrm{rank}(A^{k+1})$
2. Solve the linear system $A^{k+1} X = A^k$
3. Use the fact that $A^D$, the Drazin inverse, is given by
$$A^D = A^k X^{k+1}$$
Jim Shoaf, N. C. Central University | This one might have some pertinent leads:
<http://www.sciencedirect.com/science/article/pii/0024379585902356> |
4,315 | Fred has a puzzle. The instruction sheet, which is separate from the equation,simply says: "Make this equation true. You may ONLY draw ONE, PERFECTLY straight line". The equation is all alone on a blank piece of paper and reads:
```
5+5+5=550
```
There are 4 acceptable answers. You must get all 4 for a correct answer. | 2014/11/12 | [
"https://puzzling.stackexchange.com/questions/4315",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5180/"
] | 1. >
> Cross out the equals sign
>
>
>
2. >
> Turn the first $+$ into a 4 giving $545+5=550$
>
>
>
3. >
> Turn the second $+$ into a 4 giving $5+545=550$
>
>
>
4. >
> Turn the equals sign into less than or equal to
>
>
> | >
> 5+5+5≠550
>
>
> negating the equality.
>
>
>
> Edit:
>
> You could negate the entire statement, depending on how you interpret the equation...
>
> \_\_\_\_\_\_\_\_\_
>
> 5+5+5=550 could evaluate to "true" in some contexts... ^^
>
>
> |
4,315 | Fred has a puzzle. The instruction sheet, which is separate from the equation,simply says: "Make this equation true. You may ONLY draw ONE, PERFECTLY straight line". The equation is all alone on a blank piece of paper and reads:
```
5+5+5=550
```
There are 4 acceptable answers. You must get all 4 for a correct answer. | 2014/11/12 | [
"https://puzzling.stackexchange.com/questions/4315",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5180/"
] | >
> 5+5+5≠550
>
>
> negating the equality.
>
>
>
> Edit:
>
> You could negate the entire statement, depending on how you interpret the equation...
>
> \_\_\_\_\_\_\_\_\_
>
> 5+5+5=550 could evaluate to "true" in some contexts... ^^
>
>
> | I'd put a line
>
> on one of the plus signs, straight up.
>
> The equation would read
> 545 + 5 = 550
>
>
> |
4,315 | Fred has a puzzle. The instruction sheet, which is separate from the equation,simply says: "Make this equation true. You may ONLY draw ONE, PERFECTLY straight line". The equation is all alone on a blank piece of paper and reads:
```
5+5+5=550
```
There are 4 acceptable answers. You must get all 4 for a correct answer. | 2014/11/12 | [
"https://puzzling.stackexchange.com/questions/4315",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5180/"
] | I think the fourth answer, which hasn't been posted yet is:
>
> $5+5+5≤550$
>
>
>
That makes all of them:
>
> $5+5+5≤550$
>
> $545+5=550$
>
> $5+545=550$
>
> $5+5+5≠550$
>
>
>
> | >
> 5+5+5≠550
>
>
> negating the equality.
>
>
>
> Edit:
>
> You could negate the entire statement, depending on how you interpret the equation...
>
> \_\_\_\_\_\_\_\_\_
>
> 5+5+5=550 could evaluate to "true" in some contexts... ^^
>
>
> |
4,315 | Fred has a puzzle. The instruction sheet, which is separate from the equation,simply says: "Make this equation true. You may ONLY draw ONE, PERFECTLY straight line". The equation is all alone on a blank piece of paper and reads:
```
5+5+5=550
```
There are 4 acceptable answers. You must get all 4 for a correct answer. | 2014/11/12 | [
"https://puzzling.stackexchange.com/questions/4315",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5180/"
] | 1. >
> Cross out the equals sign
>
>
>
2. >
> Turn the first $+$ into a 4 giving $545+5=550$
>
>
>
3. >
> Turn the second $+$ into a 4 giving $5+545=550$
>
>
>
4. >
> Turn the equals sign into less than or equal to
>
>
> | I'd put a line
>
> on one of the plus signs, straight up.
>
> The equation would read
> 545 + 5 = 550
>
>
> |
4,315 | Fred has a puzzle. The instruction sheet, which is separate from the equation,simply says: "Make this equation true. You may ONLY draw ONE, PERFECTLY straight line". The equation is all alone on a blank piece of paper and reads:
```
5+5+5=550
```
There are 4 acceptable answers. You must get all 4 for a correct answer. | 2014/11/12 | [
"https://puzzling.stackexchange.com/questions/4315",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5180/"
] | 1. >
> Cross out the equals sign
>
>
>
2. >
> Turn the first $+$ into a 4 giving $545+5=550$
>
>
>
3. >
> Turn the second $+$ into a 4 giving $5+545=550$
>
>
>
4. >
> Turn the equals sign into less than or equal to
>
>
> | I think the fourth answer, which hasn't been posted yet is:
>
> $5+5+5≤550$
>
>
>
That makes all of them:
>
> $5+5+5≤550$
>
> $545+5=550$
>
> $5+545=550$
>
> $5+5+5≠550$
>
>
>
> |
4,315 | Fred has a puzzle. The instruction sheet, which is separate from the equation,simply says: "Make this equation true. You may ONLY draw ONE, PERFECTLY straight line". The equation is all alone on a blank piece of paper and reads:
```
5+5+5=550
```
There are 4 acceptable answers. You must get all 4 for a correct answer. | 2014/11/12 | [
"https://puzzling.stackexchange.com/questions/4315",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/5180/"
] | I think the fourth answer, which hasn't been posted yet is:
>
> $5+5+5≤550$
>
>
>
That makes all of them:
>
> $5+5+5≤550$
>
> $545+5=550$
>
> $5+545=550$
>
> $5+5+5≠550$
>
>
>
> | I'd put a line
>
> on one of the plus signs, straight up.
>
> The equation would read
> 545 + 5 = 550
>
>
> |
345,024 | I found a theme I really like:
<https://de.wordpress.org/themes/online-consulting/>
Unfortunately, the "Read more" button is in a position I don't really like:
[](https://i.stack.imgur.com/DHg0E.png)
I would vastly prefer if the button was below the post. Sadly, I'm quite unfamiliar with wordpress and don't really know where to get started.
I suppose this could be done using CSS? I'm hoping someone can point me in the right direction. | 2019/08/13 | [
"https://wordpress.stackexchange.com/questions/345024",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/173432/"
] | If you go into your Admin section, under Appearance > Edit CSS, you will be able to override the CSS of the theme. In order to find out what the class is, you might want to Inspect the control with Google Chrome's Developer Tools. | If you look at the demo for your theme, you will see those buttons are on new lines.
<https://de.wordpress.org/themes/online-consulting/>
It looks like it just needs to be a paragraph and then the button. Do you maybe have the button inside the paragraph?
If you go to the demo in your browser and right click the button and select "Inspect". You can view the demo HTML and CSS.
You can make a [child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/) or save new CSS in `Appearance > Customize > Additional CSS`. |
65,483,417 | I get error: "UnhandledPromiseRejectionWarning: Error [ERR\_HTTP\_HEADERS\_SENT]: Cannot set headers after they are sent to the client",
guessing that the problem is with promises, but I don't understand how to fix it.
How do I fix my code to avoid this error, but keep the logic and work with the database?
```
router.post("/addNote", (req, res) => {
let currentTime = new Date();
currentTime.setUTCHours(currentTime.getUTCHours() + 3);
const post = new PostModel({
title: req.body.inputHeader,
text: req.body.inputText,
author: req.body.author,
createdAt: currentTime
});
post.save().then(() => {
res.json({status: "saved"});
})});
router.get("/getNotes", (req, res) => {
PostModel.find().sort({createdAt: 'descending'}).then( (err, notes) => {
if (err)
res.json(err);
res.json(notes);
});
});
router.delete("/deleteNote/:id", (req, res) => {
PostModel.deleteOne(
{
_id: req.params.id
}
).then((notes) => {
if (notes)
res.json({status: "deleted"});
res.json({status: "error while deleting"});
});
});
router.put("/updateNote/:id", (req, res) => {
PostModel.findByIdAndUpdate(
req.params.id,
{
$set: req.body
},
err => {
if (err)
res.send(err);
res.send({status: "updated"})
}
).then((notes) => {
if (notes)
res.json({status: "update"});
res.json({status: "error while updating"});
});
});
router.get("/getNote", (req, res) => {
PostModel.findOne({ _id: req.params.id}).then(post => {
if (!post){
res.send({error: "not found"});
} else {
res.json(post)
}
});
});
router.post("/authorize", (req, res) => {
// bcrypt.hash ("", saltRounds, (err, hash) => {
// console.log(hash);
// });
let resultAuthorization = false;
if (req.body.login === authorization.login) {
resultAuthorization = bcrypt.compareSync(req.body.password, authorization.password);
}
if (resultAuthorization)
res.json({statusAuthorization: "correct"});
res.json({statusAuthorization: "incorrect"});
});
module.exports = router;
``` | 2020/12/28 | [
"https://Stackoverflow.com/questions/65483417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14866914/"
] | You can declare listOfFileSignatures globally, but the signatures are computed asynchronously, so the list will be empty directly after the for loop. FileReader is always asynchronous, so you can't avoid that. One possibility to handle this is to check if the list is full inside onloadend (`listOfFileSignatures.length == uploadedFiles.length`) and then do what you want there.
A nicer approach is to use promises, like this:
```
var uploadedFiles = document.getElementById("notes").files;
Promise.all([...uploadedFiles].map(file => new Promise((resolve, reject) => {
var blob = file;
var fileReader = new FileReader();
fileReader.onloadend = function readFirstFourBytes(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var fileSignature = "";
for (var i = 0; i < arr.length; i++) {
fileSignature += arr[i].toString(16);
};
resolve(fileSignature);
};
fileReader.readAsArrayBuffer(blob);
}))).then(function(listOfFileSignatures) {
// this will be called once, when all results are collected.
console.log(listOfFileSignatures);
});
```
Additionally, reading all bytes and then select just the first 4 byte is inefficient. Improved version:
```
Promise.all([...uploadedFiles].map(file => new Promise((resolve, reject) => {
var blob = file;
var fileReader = new FileReader();
fileReader.onloadend = function readFirstFourBytes(e) {
var arr = new Uint8Array(e.target.result);
var fileSignature = "";
for (var i = 0; i < arr.length; i++) {
fileSignature += arr[i].toString(16);
};
resolve(fileSignature);
};
fileReader.readAsArrayBuffer(blob.slice(0, 4));
}))).then(function(listOfFileSignatures) {
// this will be called once, when all results are collected.
console.log(listOfFileSignatures);
});
``` | fileReader.onload is asynchronous, console.log (listOfFileSignatures); is called before files have been read
one option is to create an external function that returns a promise, returning the listOfFileSignatures array
```
function getListFile() {
return new Promise((resolve, reject) => {
var blob = file;
var fileReader = new FileReader();
fileReader.onloadend = function readFirstFourBytes(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var fileSignature = "";
for (var i = 0; i < arr.length; i++) {
fileSignature += arr[i].toString(16);
};
listOfFileSignatures.push(fileSignature);
resolve(listOfFileSignatures);
};
}
}
``` |
73,603,252 | I have the following data:
```
structure(list(cells = c("Adipocytes", "B-cells", "Basophils",
"CD4+ memory T-cells", "CD4+ naive T-cells", "CD4+ T-cells",
"CD4+ Tcm", "CD4+ Tem", "CD8+ naive T-cells", "CD8+ T-cells",
"CD8+ Tcm", "Class-switched memory B-cells", "DC", "Endothelial cells",
"Eosinophils", "Epithelial cells", "Fibroblasts", "Hepatocytes",
"ly Endothelial cells", "Macrophages", "Macrophages M1", "Macrophages M2",
"Mast cells", "Melanocytes", "Memory B-cells", "Monocytes", "mv Endothelial cells",
"naive B-cells", "Neutrophils", "NK cells", "pDC", "Pericytes",
"Plasma cells", "pro B-cells", "Tgd cells", "Th1 cells", "Th2 cells",
"Tregs"), Response = c(0, 8, 0, 5, 4, 4, 3, 3, 2, 3, 8, 5, 3,
0, 1, 1, 0, 2, 1, 5, 3, 3, 2, 2, 7, 4, 3, 5, 2, 2, 8, 0, 1, 2,
3, 3, 2, 8), No_Response = c(6, 0, 1, 1, 2, 2, 1, 3, 3, 1, 1,
2, 1, 2, 3, 5, 2, 2, 3, 1, 1, 2, 2, 1, 0, 0, 5, 0, 1, 0, 0, 3,
1, 1, 5, 3, 1, 3)), class = "data.frame", row.names = c(NA, -38L
))
```
I want to make a bar chart, so that for each cell type, I get the `Response` number in blue, and the `No_Response` number in red. Something that looks like this more or less: (cells in the x-axis and the values in the y-axis):
[](https://i.stack.imgur.com/2vH9f.png) | 2022/09/04 | [
"https://Stackoverflow.com/questions/73603252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17945841/"
] | `string` isn't a byte buffer, it has very hard rules for encoding. I can easily see how the normal encoding rules will lengthen or shorten the resulting bytes that you're then using to convert to an integer. In fact, even if everything works perfectly, your string has twice as many bytes as the resulting integer. Have you given half a thought about what happens to the other 4 bytes you're silently dropping?
Either do the right thing and use byte buffers (or even better spans), or do your own manual decoding from strings to integers and the other way around. Writing something equally broken, but at least well defined, is pretty trivial:
```
static int CVL(string s) =>
s[3] << 24 | s[2] << 16 | s[1] << 8 | s[0];
``` | Solution to problem.
1. Upgrade project to .NET 6 (<https://dotnet.microsoft.com/en-us/platform/upgrade-assistant/tutorial/install-upgrade-assistant>)
2. Add the `System.Text.Encoding.CodePages` NuGet package to solution
3. Register encoding in Startup.
4. Create a global variable (Encod in the sample) and assign to encoding in startup
```
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance)
Encod = Encoding.GetEncoding(1252)
```
5. Modify the functions to use encoding.
```
Function CVL(ByVal Value As String) As Integer
Dim Encoding As System.Text.Encoding = Encod
Dim Bytes() As Byte = Encoding.GetBytes(Value)
Return BitConverter.ToInt32(Bytes, 0)
End Function
Function MKL(ByVal Value As Integer) As String
Dim Encoding As System.Text.Encoding = Encod
Dim Bytes() As Byte = BitConverter.GetBytes(Value)
Return Encoding.GetString(Bytes)
End Function
```
I still don't understand why the C# program would affect the VB.Net program internally but this code solves the problem.
Thanks to those who gave me a couple of good ideas. |
64,206 | As the title suggests, a friend and I are writing a manga-plot
and there is this character that is having the speech disorder - he stutters.
---
Writing the question directly to avoid confusion.
Afterwards providing some attempts to clarify both what the question is about & details.
Finally I will add *Background*, and then some *Context* and *References*.
---
#### Question
How should I write a character - that suffers from a speech disorder (stuttering)?
I'll add some examples below, as the question might seem broad.
---
### Examples
Some previous attempts of mine have been:
* To write about how I myself as a stutterer feel (that is, I write on my phone).
+ However, other (stutterers) might disagree(everyone is different) other stutterers maybe, don't use any help at all (and talks either way)
* Because we all are different I try to be "inclusive" or, how to put it. I try to make it more "general" Instead of only writing how I myself feel about stuttering.
---
### Background
I have this speech disorder myself, I stutter so much so I write on notepads/my phone and show it to the person instead of talking in real life.
**What does this have to do with the question?**
It is, that I am unsure how to write the person (*not the stuttering-itself*).
---
### Context and References
**I have tried to search for specifically writing about the speech (disorder) and not the usual, brief stuttering one might get when scared or surprised.**
Like 'wow!'
>
> "Ww-w-wow!"
>
>
>
or 'really'?
>
> "r-really?"
>
>
>
What I actually mean is more like, actually **having difficulties**(actively struggling) to say the word "wow" or, "really".
---
#### A more concrete example
My real name is William. So I often have (major) difficulties saying my own name because of the 'W'.
So I end up just saying
>
> my name is W-www-w (...)
>
>
>
And then - after a few attempts - literally writing on my phone "William" and showing.
**But I didn't find any question** that is directly about what I am asking.
Note: some might think stuttering appears when there is a stressful situation, like "introduce yourself in front of a class" but, my stutter is, regardless if I am stressed or not. **that is, I stutter as much as alone as if I would be in front of a class**.
#### Comments
One thing I considered doing is, having the character just write on phone, (in some anime/mangas they write in notebooks so it's - kind of the same but different)
We can also of course use sign language; (both of which has been in manga before)
As a attempt to re-phrase what the question really is asking it is:
* How should I go with writing how the character feels, but so it doesn't feel as a cliche, because I guess writing about myself is not that good (I think?) this is my first question so sorry if trivial parts is missing.
---
### Internal References
Some references that were (in)directly helpful were:
Indirectly helpful:
* [Is there such thing as too much concept at a character and how do you know so?](https://writing.stackexchange.com/questions/63204/is-there-such-thing-as-too-much-concept-at-a-character-and-how-do-you-know-so/63242#63242)
* [How does one write a character smarter than oneself?](https://writing.stackexchange.com/questions/6670/how-does-one-write-a-character-smarter-than-oneself)
Directly helpful:
* [Should you always write a strong antagonist?](https://writing.stackexchange.com/q/64202/47418)
* [How to make sure that you don't end up writing a Self-Insert?](https://writing.stackexchange.com/q/26748/47418)
### External References
* <https://www.nidcd.nih.gov/health/stuttering>
* <https://en.wikipedia.org/wiki/Stuttering> | 2023/01/15 | [
"https://writers.stackexchange.com/questions/64206",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/47418/"
] | So if I'm interpreting this correctly, you want to write a character who stutters based off yourself, but want to know how to avoid them coming off as cliché or offending other people who stutter/stutterers due to being nonrepresentative, right? And have attempted to search for resources only to find a sum total of nothing useful? (can attest to this, the advice out there is terrible.)
I stutter myself and also often wrestle with how to bring this into fiction, so you're not alone! If you don't mind, I'm going to divide this answer into two parts:
**Avoiding cliché**
You would think that, especially because the clichés about stuttering are not exactly true to life, this would be easy to do. However.
A trap it's easy to fall into here is accidentally writing in a way that lets people project the clichés into your story, even though they're not actually there. This is because there are a few narratives about stuttering that are *incredibly* common in fiction (although, IMO, not realistic and actually fairly offensive), to the point where people will actively expect to see them if a stuttering character shows up. The three main ones I know are:
* stuttering as a symptom of cowardice
* stuttering as a symptom of shyness, anxiety, low self esteem, or similar
* the stutter magically vanishing, typically as a reward for character development
As someone who stutters myself and knows that RL doesn't work this way, I am not primed to look for these the way fluent people not familiar with stuttering outside fiction are. I have multiple times been surprised to find a stuttering character interpreted in a way that fits into these tropes when I didn't think it was there in the text. (Examples: Khalid from the video game Baldur's Gate 1 being treated as cowardly, Simon from Terry Pratchett's book Equal Rites losing his stutter and that being interpreted as a reward for his character development through the book by fluent readers) I've been taken aback to find that the cultural narrative here is *just that strong* that people will just... bring their own clichés.
This means that it's probably not enough to just not write these tropes, especially because you as a stutterer cannot judge very well whether a fluent reader will read them into your work anyway. I would suggest going to the effort of actively subverting or undermining them, or in SOME place spelling out clearly that the trope will not be happening. Things like - the stuttering character is brave to the point of recklessness, maybe saying that since they have to run a gauntlet just to order coffee every day everything else seems manageable. Or lampshading in a scene in which someone says something a la thinking the stutter will go away if they get over their Issues (TM), or suggesting that why don't they try singing instead of speaking? And the stuttering character rolling their eyes and telling them they've obviously been reading too much bad fiction, if it was that easy they wouldn't stutter.
For the record, needing to do this sucks. I don't think I'll ever be able to write a character who stutters who is also generally nervous because I know it'll be interpreted as causative - this sucks. The fact that if you manage to avoid these clichés you've probably already produced a refreshing unusually well-portrayed stuttering character is good for you in the moment, but overall also sucks. But with the state of stuttering portrayals it's the advice I have to give.
**Avoiding offending other people who stutter**
This is a reasonable worry, because as you may know the stuttering community has a lot of veeery different experiences and attitudes towards stuttering. I've worried about this myself a lot because I know my own attitude is an outlier.
That said. The fact that you stutter yourself means that if you base your character's attitudes on yourself they will definitely be representative of **one** person who stutters - you. And they will almost certainly *not* be representative of some other people who stutter, just because it's such a diverse condition. So where to go from there?
My main advice would be to make sure that you depict everything the character is going through and what they think and feel as *that character's experience of stuttering* and not The Way Stuttering Is, Always, For Everyone. An easy way to do this, if you can swing it, is to bring in another character who stutters at some point (potentially for a bit part) who has a very different experience and outlook on life. If that's not possible, maybe give your character some history of interacting with other stutterers with a different experience. Even something as simple as a memory of interacting with someone in a shop once who also stuttered and was significantly [more/less] accepting of it can help avert this. If you're not sure what other experiences and takes there *are*, I suggest checking out the stuttering community - some of the podcasts on [Stuttertalk](https://stuttertalk.com/) may be a place to start. | I'm not sure it can work, but maybe you can sometimes express your character thoughts using some graphical convention like specific speech bubble and sometimes use ordinary speech bubble where he stutter. It may even be possible to use both at once to show what the character wants to tell and how he fails to do it.
Just my two cents. I believe I would be quite empathic with a character written that way. |
13,110,276 | I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma.
>
> input text words: - one, two, three, four. Each of these words should not be repeated more than once.
> so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one
>
>
>
Here is what I wrote and found a partial solution by doing separate searches
```
^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b
```
But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails.
Can you please let me know how to avoid the duplicates and where am I doing a mistake? | 2012/10/28 | [
"https://Stackoverflow.com/questions/13110276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781007/"
] | It would be far easier to NOT do this particular problem with a single regular expression.
First off, `\b` is zero-width. So you do not need to follow it using a `?`, your intention is probably `\s?`.
Next, regex is pretty much stateless, in the general case, which means that you'd need to construct your regex as follows.
```
^\s*(one\s*,(two\s*,(three\s*,four|four\s*,three)|three\s*,(two\s*,four|four\s*,two)...
```
As you can see, you have to manually deal with combinatoric explosion. Which is far less than ideal.
You should instead, split on `,` and use java to check.
>
> Thanks for replying. From what i understand, you want me not use regex rather use java.can you detail a bit on how to check in java
>
>
>
Try this (untested code, will be bugs):
```
public parseList(String input) {
String[] numbers = { "one", "two", "three", "four" };
bool foundNumbers = { false, false, false, false };
String delims = "\s*,";
String[] tokens = input.split(delims);
if (tokens.length != 4) {
//deal with error case as you wish
}
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < tokens.length; ++j) {
if (numbers[i].equals(tokens[j])) {
if (!foundNumbers[i]) {
foundNumbers[i] = true;
} else {
//deal with error case as you wish
}
}
}
}
for (int i = 0; i < foundNumbers.length; ++i) {
if (!foundNumbers[i]) {
//deal with error case as you wish
}
}
//success
}
``` | Why do you want to use regex?
Just split the text on comma and do your usual array / list duplicate check |
13,110,276 | I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma.
>
> input text words: - one, two, three, four. Each of these words should not be repeated more than once.
> so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one
>
>
>
Here is what I wrote and found a partial solution by doing separate searches
```
^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b
```
But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails.
Can you please let me know how to avoid the duplicates and where am I doing a mistake? | 2012/10/28 | [
"https://Stackoverflow.com/questions/13110276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781007/"
] | ```
boolean valid( String input ) {
input.tokenize( ',' ).with { list ->
list.unique( false ) == list &&
list.every { it in ['one','two','three','four'] }
}
}
```
should do it without regular expressions | Why do you want to use regex?
Just split the text on comma and do your usual array / list duplicate check |
13,110,276 | I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma.
>
> input text words: - one, two, three, four. Each of these words should not be repeated more than once.
> so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one
>
>
>
Here is what I wrote and found a partial solution by doing separate searches
```
^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b
```
But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails.
Can you please let me know how to avoid the duplicates and where am I doing a mistake? | 2012/10/28 | [
"https://Stackoverflow.com/questions/13110276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781007/"
] | It would be far easier to NOT do this particular problem with a single regular expression.
First off, `\b` is zero-width. So you do not need to follow it using a `?`, your intention is probably `\s?`.
Next, regex is pretty much stateless, in the general case, which means that you'd need to construct your regex as follows.
```
^\s*(one\s*,(two\s*,(three\s*,four|four\s*,three)|three\s*,(two\s*,four|four\s*,two)...
```
As you can see, you have to manually deal with combinatoric explosion. Which is far less than ideal.
You should instead, split on `,` and use java to check.
>
> Thanks for replying. From what i understand, you want me not use regex rather use java.can you detail a bit on how to check in java
>
>
>
Try this (untested code, will be bugs):
```
public parseList(String input) {
String[] numbers = { "one", "two", "three", "four" };
bool foundNumbers = { false, false, false, false };
String delims = "\s*,";
String[] tokens = input.split(delims);
if (tokens.length != 4) {
//deal with error case as you wish
}
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < tokens.length; ++j) {
if (numbers[i].equals(tokens[j])) {
if (!foundNumbers[i]) {
foundNumbers[i] = true;
} else {
//deal with error case as you wish
}
}
}
}
for (int i = 0; i < foundNumbers.length; ++i) {
if (!foundNumbers[i]) {
//deal with error case as you wish
}
}
//success
}
``` | I believe you are trying to use regular expressions to parse a non regular input. In this case, the input is more like a context free language. I recommend tokenizing the string and counting. |
13,110,276 | I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma.
>
> input text words: - one, two, three, four. Each of these words should not be repeated more than once.
> so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one
>
>
>
Here is what I wrote and found a partial solution by doing separate searches
```
^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b
```
But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails.
Can you please let me know how to avoid the duplicates and where am I doing a mistake? | 2012/10/28 | [
"https://Stackoverflow.com/questions/13110276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781007/"
] | ```
boolean valid( String input ) {
input.tokenize( ',' ).with { list ->
list.unique( false ) == list &&
list.every { it in ['one','two','three','four'] }
}
}
```
should do it without regular expressions | I believe you are trying to use regular expressions to parse a non regular input. In this case, the input is more like a context free language. I recommend tokenizing the string and counting. |
13,110,276 | I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma.
>
> input text words: - one, two, three, four. Each of these words should not be repeated more than once.
> so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one
>
>
>
Here is what I wrote and found a partial solution by doing separate searches
```
^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b
```
But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails.
Can you please let me know how to avoid the duplicates and where am I doing a mistake? | 2012/10/28 | [
"https://Stackoverflow.com/questions/13110276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781007/"
] | It would be far easier to NOT do this particular problem with a single regular expression.
First off, `\b` is zero-width. So you do not need to follow it using a `?`, your intention is probably `\s?`.
Next, regex is pretty much stateless, in the general case, which means that you'd need to construct your regex as follows.
```
^\s*(one\s*,(two\s*,(three\s*,four|four\s*,three)|three\s*,(two\s*,four|four\s*,two)...
```
As you can see, you have to manually deal with combinatoric explosion. Which is far less than ideal.
You should instead, split on `,` and use java to check.
>
> Thanks for replying. From what i understand, you want me not use regex rather use java.can you detail a bit on how to check in java
>
>
>
Try this (untested code, will be bugs):
```
public parseList(String input) {
String[] numbers = { "one", "two", "three", "four" };
bool foundNumbers = { false, false, false, false };
String delims = "\s*,";
String[] tokens = input.split(delims);
if (tokens.length != 4) {
//deal with error case as you wish
}
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < tokens.length; ++j) {
if (numbers[i].equals(tokens[j])) {
if (!foundNumbers[i]) {
foundNumbers[i] = true;
} else {
//deal with error case as you wish
}
}
}
}
for (int i = 0; i < foundNumbers.length; ++i) {
if (!foundNumbers[i]) {
//deal with error case as you wish
}
}
//success
}
``` | You can use negative lookaheads in this way (see at [Regexr](http://regexr.com?32k60)):
```rb
\b(one|two|three|four)\b, # match one of the allowed words
\b(?!\1)(one|two|three|four)\b, # match one of them but not first matched one
\b(?!\1|\2)(one|two|three|four)\b, # match one of them but not first and second matched ones
\b(?!\1|\2|\3)(one|two|three|four)\b # match one of them but not first, second and third matched ones
``` |
13,110,276 | I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma.
>
> input text words: - one, two, three, four. Each of these words should not be repeated more than once.
> so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one
>
>
>
Here is what I wrote and found a partial solution by doing separate searches
```
^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b
```
But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails.
Can you please let me know how to avoid the duplicates and where am I doing a mistake? | 2012/10/28 | [
"https://Stackoverflow.com/questions/13110276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781007/"
] | It would be far easier to NOT do this particular problem with a single regular expression.
First off, `\b` is zero-width. So you do not need to follow it using a `?`, your intention is probably `\s?`.
Next, regex is pretty much stateless, in the general case, which means that you'd need to construct your regex as follows.
```
^\s*(one\s*,(two\s*,(three\s*,four|four\s*,three)|three\s*,(two\s*,four|four\s*,two)...
```
As you can see, you have to manually deal with combinatoric explosion. Which is far less than ideal.
You should instead, split on `,` and use java to check.
>
> Thanks for replying. From what i understand, you want me not use regex rather use java.can you detail a bit on how to check in java
>
>
>
Try this (untested code, will be bugs):
```
public parseList(String input) {
String[] numbers = { "one", "two", "three", "four" };
bool foundNumbers = { false, false, false, false };
String delims = "\s*,";
String[] tokens = input.split(delims);
if (tokens.length != 4) {
//deal with error case as you wish
}
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < tokens.length; ++j) {
if (numbers[i].equals(tokens[j])) {
if (!foundNumbers[i]) {
foundNumbers[i] = true;
} else {
//deal with error case as you wish
}
}
}
}
for (int i = 0; i < foundNumbers.length; ++i) {
if (!foundNumbers[i]) {
//deal with error case as you wish
}
}
//success
}
``` | You should definitely not use a regex for this. You can, though:
```
boolean foundMatch = subjectString.matches(
"(?x) # Verbose regex \n" +
"(?: # Match... \n" +
" (?:one()|two()|three()|four()) # one of the four words \n" +
" (?:\\s*,\\s*|\\s*$) # a comma or end-of-string \n" +
"){4} # four times \n" +
"$ # End of string \n" +
"\\1\\2\\3\\4 # Assert that all four words have matched");
```
The empty capturing groups ensure (together with `\1\2\3\4` at the end) that each word participates exactly once in the match :) |
13,110,276 | I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma.
>
> input text words: - one, two, three, four. Each of these words should not be repeated more than once.
> so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one
>
>
>
Here is what I wrote and found a partial solution by doing separate searches
```
^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b
```
But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails.
Can you please let me know how to avoid the duplicates and where am I doing a mistake? | 2012/10/28 | [
"https://Stackoverflow.com/questions/13110276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781007/"
] | ```
boolean valid( String input ) {
input.tokenize( ',' ).with { list ->
list.unique( false ) == list &&
list.every { it in ['one','two','three','four'] }
}
}
```
should do it without regular expressions | You can use negative lookaheads in this way (see at [Regexr](http://regexr.com?32k60)):
```rb
\b(one|two|three|four)\b, # match one of the allowed words
\b(?!\1)(one|two|three|four)\b, # match one of them but not first matched one
\b(?!\1|\2)(one|two|three|four)\b, # match one of them but not first and second matched ones
\b(?!\1|\2|\3)(one|two|three|four)\b # match one of them but not first, second and third matched ones
``` |
13,110,276 | I'm working on a regular expression where I need to verify a input text that contains 4 distinct words separated by a comma.
>
> input text words: - one, two, three, four. Each of these words should not be repeated more than once.
> so, it can be: two, three, four, one or three, four, two, one and not one, one, one, one
>
>
>
Here is what I wrote and found a partial solution by doing separate searches
```
^\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b?,\b(one|two|three|four)\b
```
But the problem with solution is words are getting repeated, and the test for "one, one, one, one" fails.
Can you please let me know how to avoid the duplicates and where am I doing a mistake? | 2012/10/28 | [
"https://Stackoverflow.com/questions/13110276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781007/"
] | ```
boolean valid( String input ) {
input.tokenize( ',' ).with { list ->
list.unique( false ) == list &&
list.every { it in ['one','two','three','four'] }
}
}
```
should do it without regular expressions | You should definitely not use a regex for this. You can, though:
```
boolean foundMatch = subjectString.matches(
"(?x) # Verbose regex \n" +
"(?: # Match... \n" +
" (?:one()|two()|three()|four()) # one of the four words \n" +
" (?:\\s*,\\s*|\\s*$) # a comma or end-of-string \n" +
"){4} # four times \n" +
"$ # End of string \n" +
"\\1\\2\\3\\4 # Assert that all four words have matched");
```
The empty capturing groups ensure (together with `\1\2\3\4` at the end) that each word participates exactly once in the match :) |
37,208,644 | I want to add new row to gridcontrol at every button click. I tried many ways but no success. I am sending my code.
```
private void B_Click(object sender, EventArgs e)
{
Button bt = (Button)sender;
int productId = (int)bt.Tag;
AddProductDataContext db = new AddProductDataContext();
decimal Quantity;
decimal.TryParse(txtCalculator.Text, out Quantity);
var results = from inv in db.Inventories
where inv.RecId == productId
select new
{
inventoryName = inv.InventoryName,
Quantity,
Total = Quantity * inv.InventoryPrice
};
DataTable dt = new DataTable();
dt.Columns.Add("inventoryName");
dt.Columns.Add("Quantity");
dt.Columns.Add("Total");
foreach (var x in results)
{
DataRow newRow = dt.Rows.Add();
newRow.SetField("inventoryName", x.inventoryName);
newRow.SetField("Quantity", x.Quantity);
newRow.SetField("Total", x.Total);
}
gridControl1.DataSource = dt;
gridView1.AddNewRow();
}
``` | 2016/05/13 | [
"https://Stackoverflow.com/questions/37208644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6325555/"
] | For god sake, protect your query against SQL injection :
```
$sql = "DELETE from utilisateur where pseudo = '".mysqli_real_escape_string($con, $pseudo)."'";
``` | ```
$sql = "DELETE from utilisateur where pseudo = '$pseudo'";
``` |
49,240,739 | I wanted to export data from *netezza database* to *CSV* file.
The format for the data will be:
```
col1,col2,col3
```
OR:
```
"col1","col2","col3"
```
I am using the query:
```
CREATE EXTERNAL TABLE 'H:\\test.csv' USING ( DELIMITER ',' REMOTESOURCE 'ODBC' ) AS
SELECT * FROM TEST_TABLE
```
Above query is not working when *col3* has the field including comma as it is saying to export it using escape char as '\'.
Example table:
```
A | B | C
a | b | Germany, NA
```
I tried that too, but I am getting as output in *csv*:
```
a,b,Germany\, NA
```
or by adding quotes to each column I am getting output:
```
"a","b","Germany\, NA"
```
Here, I am getting extra '\' character in field.
I am looking for the solution to resolve it using the *nzsql* or external table query method or writing own script methods only.
My expected output without changing field data:
"a","b","Germany, NA" | 2018/03/12 | [
"https://Stackoverflow.com/questions/49240739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3863192/"
] | Desired output can be achieved by using nzsql command line statement.The only limitation of this approach is max file will limit to **2 GB** .Here is the link from IBM KB [Sending query results to an output file](http://www-01.ibm.com/support/docview.wss?crawler=1&uid=swg21567479)
```
[nz@netezza ~]$ nzsql -d test -A -t -c "select quote_ident(col1),quote_ident(col2), quote_ident(col3) from test" -o '/nzscratch/test.csv'
```
**Output :**
```
[nz@netezza ~]$ cat /nzscratch/test.csv
"A"|"B"|"C"
a|b|"Germany, NA"
``` | You can use ~~`ESCAPECHAR '@'` to use an '@' rather than a backslash~~ only a backlash as an [escape character](https://en.wikipedia.org/wiki/Escape_character). The problem is that a csv file needs a way to say "this comma is data, not a delimiter" - which is what the escape char is used for. The code that consumes your csv file should be configured to expect that same escape character.
This is one of the quirks you run into when using a loosely defined data format like csv. As long as you define a delimiter and an escape character that the producer and consumer both expect - and you're using the same character encoding - you'll be fine.
This isn't changing your data, it's just making the interchange format more specific. If you provide some detail on what is consuming the data, I can update this answer to provide detail on informing the consumer that backslashes are used as an escape character.
-- EDIT --
Apparently some implementations of netezza *only support* backslash as a delimiter.
IBM References:
* [QuotedValue](https://www.ibm.com/support/knowledgecenter/SSULQD_7.2.1/com.ibm.nz.load.doc/r_load_quotedvalue.html)
* [EscapeChar](https://www.ibm.com/support/knowledgecenter/SSULQD_7.2.1/com.ibm.nz.load.doc/r_load_escapechar.html)
* [Delimiter](https://www.ibm.com/support/knowledgecenter/SSULQD_7.2.1/com.ibm.nz.load.doc/r_load_delimiter.html) |
70,444,674 | Hey all so I'll keep it short. I know there've been some questions asked similar to this but none of them are able to answer what I'm trying to achieve. This is what I want the code to do:
* Show a div when forward slash "/" is typed in textarea
* Not show a div when forward slash is not typed
* hide the pop up when the forward slash is deleted/backspaced
I can achieve the first two with the following code I'm working with right now: <https://jsfiddle.net/jtk37vs8/1/>. However the problem is, whenever I type forward slash and then delete it, the pop up still stays there. I'm new to JS and the code is kinda unorganized but it's quite easy to understand. So basically I'd appreciate if any of you could at least tell me if there is any straightforward way to achieve this? Thank you for your patience and reading my query.
```
function getCaretCoordinates() {
let x = 0,
y = 0;
const isSupported = typeof window.getSelection !== "undefined";
if (isSupported) {
const selection = window.getSelection();
// Check if there is a selection (i.e. cursor in place)
if (selection.rangeCount !== 0) {
// Clone the range
const range = selection.getRangeAt(0).cloneRange();
// Collapse the range to the start, so there are not multiple chars selected
range.collapse(true);
// getCientRects returns all the positioning information we need
const rect = range.getClientRects()[0];
if (rect) {
x = rect.left; // since the caret is only 1px wide, left == right
y = rect.top; // top edge of the caret
}
}
}
return { x, y };
}
function getCaretIndex(element) {
let position = 0;
const isSupported = typeof window.getSelection !== "undefined";
if (isSupported) {
const selection = window.getSelection();
// Check if there is a selection (i.e. cursor in place)
if (selection.rangeCount !== 0) {
// Store the original range
const range = window.getSelection().getRangeAt(0);
// Clone the range
const preCaretRange = range.cloneRange();
// Select all textual contents from the contenteditable element
preCaretRange.selectNodeContents(element);
// And set the range end to the original clicked position
preCaretRange.setEnd(range.endContainer, range.endOffset);
// Return the text length from contenteditable start to the range end
position = preCaretRange.toString().length;
}
}
return position;
}
$("#contenteditable").bind("keypress", function toggleTooltip(e) {
const tooltip = document.getElementById("tooltip");
if(String.fromCharCode(e.keyCode) == '/') {
const { x, y } = getCaretCoordinates();
$(".tooltip").show();
// tooltip.setAttribute("aria-hidden", "false");
tooltip.setAttribute( "style", `display: inline-block; left: ${x - -10}px; top: ${y - 160}px`
);
}
else if (document.getElementById('contenteditable').innerHTML.indexOf("/") != -1) {
// $(".tooltip").hide();
// tooltip.setAttribute("aria-hidden", "true");
tooltip.setAttribute("style", "display: none;");
}
// else if (document.getElementById('contenteditable').innerHTML.indexOf("/") >=0) {
// tooltip.setAttribute("aria-hidden", "true");
//tooltip.setAttribute("style", "display: none;");
// }
else {
// $(".tooltip").hide();
// tooltip.setAttribute("aria-hidden", "true");
//tooltip.setAttribute("style", "display: none;");
}
} )
``` | 2021/12/22 | [
"https://Stackoverflow.com/questions/70444674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16663406/"
] | I think the problem is a combination of Stencil's tree-shakable API and a problem with its build-time analysis of dynamic imports.
Stencil tries to ship as little "Stencil" code as possible, so it will analyze your project to find out which features you're actually using and only include those in the final bundle. If you check the `./build/index-{hash}.js` (in a dev www build) on line 2 you'll find a list of which features it detected.
I created my own quick reproduction and compared this file when using a dynamic and static import. Here are the differences:
**Dynamic Import**
```
{ vdomAttribute: false, vdomListener: false }
```
**Static Import**
```
{ vdomAttribute: true, vdomListener: true }
```
So it seems that Stencil isn't aware of the features you're only using in the dynamically imported template and therefore doesn't include it in the build. But if you use the same features in any component (or file that is statically imported into a component), Stencil should include it.
So a simple work around would be to attach any listener to any element in any component of your project. And you'd have to do that for every single Stencil feature you're currently only using in a dynamically loaded template.
Another option is to create a Stencil component that statically includes all your dynamic templates. AFAIK this would detect all used features and enable them for the project even without having to use this new component anywhere.
**Example:**
```
import { Component, Host, h } from '@stencil/core';
import { Template1 } from "../../templates/template1";
import { Template2 } from "../../templates/template2";
import { Template3 } from "../../templates/template3";
@Component({
tag: 'template-imports',
})
export class TemplateImports {
render() {
return (
<Host>
<Template1></Template1>
<Template2></Template2>
<Template3></Template3>
</Host>
);
}
}
``` | I think it should be
```js
@Component({
tag: 'component-two',
styleUrl: 'component-two.css',
shadow: true,
})
export class ComponentTwo {
// omitting all code that didn't change ...
render() {
// probably not needed
let this_ = this;
/* ---------------------------------------------------- */
/* Note the change in the following line: */
/* showComponentOne must be the template function here. */
/* ---------------------------------------------------- */
return this.showComponentOne ? <this.showComponentOne onclick={this.onClick.bind(this)} /> : <div></div>;
}
}
``` |
19,767,553 | I am using a `UIAlertView` to prompt users for a password. If the password is correct, I'd like the alert view to go away normally; if the password is incorrect, I'd like the alert view to remain (with the text changed to something like "Please try again."). How do I alter the default behaviour so that the view doesn't go away when a button is pressed?
I've tried the subclassing method suggested at [Is it possible to NOT dismiss a UIAlertView](https://stackoverflow.com/questions/2051402/is-it-possible-to-not-dismiss-a-uialertview), but the `dismissWithClickedButtonIndex` wasn't being called in my subclass. After reading the documentation I see that subclassing `UIAlertView` isn't supported, so I'd like to try another approach.
If this isn't possible with `UIAlertView`, is the best option to simply make a password view from scratch? Thanks for reading. | 2013/11/04 | [
"https://Stackoverflow.com/questions/19767553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781058/"
] | You could design a **UIView** similar to the alertview and can cal the functions inside this. Removing a UIView is controlled by you. | It's not possible to leave the alert there when a button has been clicked.
You can either disable the "OK" button by delegate method `alertViewShouldEnableFirstOtherButton:`, if you are checking the password locally, or just show another alert later. The second alert can contain a different information, e.g. "Password incorrect" instead of "Enter password". |
19,767,553 | I am using a `UIAlertView` to prompt users for a password. If the password is correct, I'd like the alert view to go away normally; if the password is incorrect, I'd like the alert view to remain (with the text changed to something like "Please try again."). How do I alter the default behaviour so that the view doesn't go away when a button is pressed?
I've tried the subclassing method suggested at [Is it possible to NOT dismiss a UIAlertView](https://stackoverflow.com/questions/2051402/is-it-possible-to-not-dismiss-a-uialertview), but the `dismissWithClickedButtonIndex` wasn't being called in my subclass. After reading the documentation I see that subclassing `UIAlertView` isn't supported, so I'd like to try another approach.
If this isn't possible with `UIAlertView`, is the best option to simply make a password view from scratch? Thanks for reading. | 2013/11/04 | [
"https://Stackoverflow.com/questions/19767553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1781058/"
] | As this is very old question,but I got one solution and though of posting if any other developer need in near future.
Implement protocol methods in .h file
In order to respond to button taps in our UIAlertView, we will use the – alertView:clickedButtonAtIndex: protocol method as
```
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
}
//Now below code will check if uitextfield value.
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
NSString *inputText = [[alertView textFieldAtIndex:0] text];
if( [inputText length] > 0)
{
//text field value is greater than zero ,then Done button will appear as blue,or else it will be blurred
return YES;
}
else
{
return NO;
}
}
``` | It's not possible to leave the alert there when a button has been clicked.
You can either disable the "OK" button by delegate method `alertViewShouldEnableFirstOtherButton:`, if you are checking the password locally, or just show another alert later. The second alert can contain a different information, e.g. "Password incorrect" instead of "Enter password". |
4,229,732 | initially, my textarea has a value of Enter Comment... set via `<textarea>Enter Comment...</textarea>`
I have a .focus like:
`$("textarea.commentTextArea").live('focus', function() {
if($(this).val() == "Enter Comment...") {
$(this).val('');
}
});`
and a .blur() like:
`$("textarea.commentTextArea").live('blur', function() {
if($(this).val() == "Enter Comment..." || $(this).val() == "") {
$(this).text("Enter Comment...");
$(this).parent().addClass("hide");
$(this).parent().hide();
}
});`
However, after I set the val in the .blur() function, and try to retrieve the value using .val(), it's always returning 'Enter Comment...' as opposed to the text that was user inputted. I'm at a loss here.
Thanks for the help!
Edit- I have a more in depth selector for the "textarea", that's not the issue. It wouldn't be returning "Enter Comment" if the selector was returning null. Thanks for trying though.
Same goes with my .focus() function. I just wanted to show the core of what's going on | 2010/11/19 | [
"https://Stackoverflow.com/questions/4229732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/409993/"
] | You don't have quotes around the word 'textarea' in the second statement. Also, your focus event will delete anything the user entered if they return to the textarea to edit again.
do this to solve the second problem (same trick you used on the blur event):
```
$("textarea").focus(function() { if ($(this).val() == 'Enter Comment...') $(this).val(''); });
``` | My first guess would be that `$(textarea)` is returning null -- I'm guessing that it should be `$("textarea")`. I think this is fine. I tried it out using [jsfiddle](http://www.jsfiddle.net/jwiscarson/a55qD/1/), and it worked. |
4,229,732 | initially, my textarea has a value of Enter Comment... set via `<textarea>Enter Comment...</textarea>`
I have a .focus like:
`$("textarea.commentTextArea").live('focus', function() {
if($(this).val() == "Enter Comment...") {
$(this).val('');
}
});`
and a .blur() like:
`$("textarea.commentTextArea").live('blur', function() {
if($(this).val() == "Enter Comment..." || $(this).val() == "") {
$(this).text("Enter Comment...");
$(this).parent().addClass("hide");
$(this).parent().hide();
}
});`
However, after I set the val in the .blur() function, and try to retrieve the value using .val(), it's always returning 'Enter Comment...' as opposed to the text that was user inputted. I'm at a loss here.
Thanks for the help!
Edit- I have a more in depth selector for the "textarea", that's not the issue. It wouldn't be returning "Enter Comment" if the selector was returning null. Thanks for trying though.
Same goes with my .focus() function. I just wanted to show the core of what's going on | 2010/11/19 | [
"https://Stackoverflow.com/questions/4229732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/409993/"
] | You don't have quotes around the word 'textarea' in the second statement. Also, your focus event will delete anything the user entered if they return to the textarea to edit again.
do this to solve the second problem (same trick you used on the blur event):
```
$("textarea").focus(function() { if ($(this).val() == 'Enter Comment...') $(this).val(''); });
``` | I presume it's because you missed the quotes around the `$(textarea).blur()` method.
I've created an [example with your code](http://jsfiddle.net/AScM4/) which works. |
1,245,376 | Hey Exchange community,
We have finite-dimensional vector spaces $V$ and $W$ with ordered bases $B$ and $A$ respectively.
Is it true/false that $L(V,W)=L(W,V)$?
Just wondering if someone could articulate what the difference is between the two notations. Having someone write it down as if they were verbally explaining it to someone would really help.
Thanks! | 2015/04/21 | [
"https://math.stackexchange.com/questions/1245376",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/233092/"
] | The symbols $\mathcal{L}(V,W)$ indicates the linear transformations from vector space $V$ into vector space $W$, and the analogous statement is made for $\mathcal{L}(W,V)$. If $V$ and $W$ are not the same space (e.g. isomorphic) then you don't in general have the same maps going from $V$ to $W$ as you do from $W$ to $V$. For instance, if $V$ were $2$-dimensional and $W$ were $3$-dimensional then the linear maps in $\mathcal{L}(V,W)$ could be represented by $3\times 2$ matrices, but the maps in $\mathcal{L}(W,V)$ would be $2\times 3$ matrices. | $\mathcal{L}(U,W)=\{T\colon U\to W/ T \mbox{ is a linear transformation }\}$
$\mathcal{L}(W,U)=\{T\colon W\to U/ T \mbox{ is a linear transformation }\}$
There are different because $Im(\mathcal{L}(U,V))\subset U$ and $Im((\mathcal{L}(V,U))\subset V$ and $ U, V$ nor always will be subsets of the same space.
For example $\mathcal{L}(U,\mathbb{K})$ obviusly not equal to $\mathcal{L}(\mathbb{K},U)$ |
35,527,163 | I created a simple Jekyll blog by following the instructions in the Quick-start guide in <http://jekyllrb.com/docs/quickstart/>.
I changed the blog a little bit to suit my needs and was able to successfully implement these changes and view them locally. But, as soon as I deployed the blog on Github Pages, I get this
<http://palpen.github.io/palpen_articles/>
which is nothing like the local version of the site. What did I do wrong?
I'm new to all of this, so forgive me if my mistakes are trivial. The GitHub repository for the blog lives here:
<https://github.com/palpen/palpen_articles>
Thank you | 2016/02/20 | [
"https://Stackoverflow.com/questions/35527163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3649966/"
] | By going off the assumption that you mean the styling is off.
I opened the dev console in your website and noticed there was this error
```
http://palpen.github.io/palpen_articles/palpen_articles/css/main.css Failed to load resource: the server responded with a status of 404 (Not Found)
```
Notice that it's attempting to access a nested deep resource with your site host.
The culprit is this line
```
<link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
```
<https://github.com/palpen/palpen_articles/blob/gh-pages/_includes/head.html#L9>
When you prepend the base url for the site it creates a link
```
<link rel="stylesheet" href="palpen_articles/css/main.css">
```
If you prepend the `/` to that href your site style actually looks better.
Note that there are a couple of other links which are broken as well because of this reason.
The issue is that your `_config.yml` file contains a bad `baseurl`. The `baseurl` should be `/palpen_articles` instead of just `palpen_articles`. | Perhaps you might face more trouble in the future if locally you don't use the same environment as GitHub does. You'll need to serve Jekyll with bundler to accomplish that.
Take a look at this [answer](https://stackoverflow.com/a/35449384/5455207) to check how to do it.
Hope to have helped! |
676,357 | My Ubuntu Linux server has an mdadm array (RAID 5) with four 2TB SATA disks that keeps "loosing" two disks from time to time. Rebooting and re-assembling the arrays has worked out fine up until now.
Hardware is a Dell PowerEdge T20 with an Exsys EX-3400 card that provides four additional SATA ports. Two of the fours disks in the RAID array are connected to the Exsys card, and the remaining two disks are connected to the onboard SATA ports (the remaining onboard SATA ports are in use for other disks). I checked for disk faults using smart utilities, they all seem good.
The disks that are being "lost" from the RAID are the two connected to the add-on SATA controller, so I replaced the add-on card with another one (didn't help, same symptoms). I replaced the SATA cables of the relevant disks (didn't help, same symptoms).
Does anyone have an idea what the source for these issues might be, and what else I could test? | 2015/03/18 | [
"https://serverfault.com/questions/676357",
"https://serverfault.com",
"https://serverfault.com/users/276935/"
] | You have these three commands
```
mkdir test_dir test_dir1 test_dir2 test_dir3
touch file1 file2 file3
cp -v file* test_dir*/
```
Assuming no other files or directories in `.` before the example is started, the wildcards in that last line get expanded thus:
```
cp -v file1 file2 file3 test_dir/ test_dir1/ test_dir2/ test_dir3/
```
(You can see this by changing `cp` to `echo cp` and observing the result.) What you didn't tell us is the diagnostic messages produced by `cp -v`, which show what it is trying to do, i.e. copy every item on the command line but the last into the last item, which must therefore be a directory:
```
‘file1’ -> ‘test_dir3/file1’
‘file2’ -> ‘test_dir3/file2’
‘file3’ -> ‘test_dir3/file3’
cp: omitting directory ‘test_dir/’
cp: omitting directory ‘test_dir1/’
cp: omitting directory ‘test_dir2/’
``` | Because the `cp` commands works so. If it has more as 2 argument, the last argument must be a directory, and every argument before that will be copied into.
I think you want a `cp` which behaves much more like the windows `copy` command, and yes, there are such tools, although they aren't widely used. Even I had to google for that.
Your actual goal could be easily reached by a simple loop:
```
for i in test_dir*; do cp -v test_file* $i; done
```
It is much more simple as it seems on the first spot. Bash is actually a basic-like programming language, and doing loops or even more complex operations in single-line commands in a unix environment is quite common. |
9,898,773 | I realize there are similar posts to this out there, but rest assured, this isn't a duplicate post!
I have a site on a godaddy server. I DO NOT have access to the outside of the root of my server (everything is public).
I have a file delete.php that needs to run on CRON, and only by CRON. The file should not execute manually at all by anyone for any reason.
Given the above, I am trying to secure my file as much as possible so let'smake this an experiment in security.
So far, I have the following with the goal of making the file as secure as possible:
```
<?php
$isCLI = ( php_sapi_name() == 'cli' );
if (!$isCLI) {
die("cannot run!");
} else {
if(!isset($_SERVER['REQUEST_METHOD'])){
// Do the task here
}else{
die("cannot run!");
}
}
?>
```
So, is this logically secure? How can it be made even more secure? godaddy can only allow me to set a date/time to run a file, nothing more. | 2012/03/27 | [
"https://Stackoverflow.com/questions/9898773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/910737/"
] | Checking for the `cli` SAPI is sufficient; a user executing it via apache (be it mod\_php or fastcgi or cgi) will never cause PHP to be called through the CLI sapi. You can get rid of the ugly `else {}` around your real code though; if you `exit;` at the end of the *then* block there is no need for an *else* block.
However, not putting that kind of script in the document root at all would be much cleaner. If that's not possible, also consider using `.htaccess`:
```
Order deny,allow
Deny from all
```
If the files are in a folder which shouldn't be locked down completely, wrap those lines in `<Files whatever.php>...</Files>` | Of course, placing those files outside the webroot would be the preferred way of doing it.
On the other hand, you could create `.htaccess` which defines `Deny all` rule for all access. This way `Deny all` prevents direct server access but PHP CLI would still be able to access it. |
41,346,681 | i have a set of code that i copied from someone on youtube and i completely understand and there is some unused logic in there but basically at the moment all it is meant to do is grab the rocket.show function and draw a rectangle and i cannot for the life of me work out why it is not doing so. it is throwing out no errors and drawing the background, i can draw the rectangle if i just put the code for "rect..." in the draw function therefore there is a problem with the way that i am referring to the function but i cannot for the life of me work it out, the code is below, any help would be appreciated.
```
function setup() {
createCanvas(800, 600);
background(0);
rocket = new rocket();
}
function draw() {
rocket.update;
rocket.show;
}
function rocket() {
this.pos = createVector();
this.vel = createVector();
this.acc = createVector();
this.applyforce = function (force) {
this.acc.add(force);
}
this.update = function () {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.mult(0);
}
this.show = function () {
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
rectMode(CENTER);
rect(0, 0, 10, 50);
pop();
}
}
```
edit: I worked it out, sorry for taking up needless posting space | 2016/12/27 | [
"https://Stackoverflow.com/questions/41346681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6308045/"
] | You should check for the *first* property that might not exist: so don't check the `coconut.color` property before you are sure that `coconut` exists.
If the property you check for should be an object (which is your case) then you can do so with the `!` operator:
```
if (!myObj.fruits.coconut) myObj.fruits.coconut = { color: 'brown' };
``` | If you want to test for the presence of a property on an object you can use the `Object.prototype.hasOwnProperty()`:
```
myObj.fruits.hasOwnProperty("apples") //true
myObj.fruits.hasOwnProperty("oranges") //false
``` |
41,346,681 | i have a set of code that i copied from someone on youtube and i completely understand and there is some unused logic in there but basically at the moment all it is meant to do is grab the rocket.show function and draw a rectangle and i cannot for the life of me work out why it is not doing so. it is throwing out no errors and drawing the background, i can draw the rectangle if i just put the code for "rect..." in the draw function therefore there is a problem with the way that i am referring to the function but i cannot for the life of me work it out, the code is below, any help would be appreciated.
```
function setup() {
createCanvas(800, 600);
background(0);
rocket = new rocket();
}
function draw() {
rocket.update;
rocket.show;
}
function rocket() {
this.pos = createVector();
this.vel = createVector();
this.acc = createVector();
this.applyforce = function (force) {
this.acc.add(force);
}
this.update = function () {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.mult(0);
}
this.show = function () {
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
rectMode(CENTER);
rect(0, 0, 10, 50);
pop();
}
}
```
edit: I worked it out, sorry for taking up needless posting space | 2016/12/27 | [
"https://Stackoverflow.com/questions/41346681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6308045/"
] | You should check for the *first* property that might not exist: so don't check the `coconut.color` property before you are sure that `coconut` exists.
If the property you check for should be an object (which is your case) then you can do so with the `!` operator:
```
if (!myObj.fruits.coconut) myObj.fruits.coconut = { color: 'brown' };
``` | As someone pointed out in the comments, you have at least two ways.
First one, the simplest, is simply doing
```
if(!myObj.fruits.cononut)
// do stuff
```
However this is not very safe since it *"does stuffs"* even if `.coconut` is `false`, for example.
What people usually does is
```
if(typeof myObj.fruits.cononut === "undefined")
// do stuff
```
that checks if the field actually doesn't exist and is not set (`===` also checks for the same type).
However, this time I think you can ever try with this (not tested deeply):
```
if(!("cononut" in myObj.fruits))
// do stuff
```
That checks for the existance of the key.
**EDIT**
As @hackerrdave pointed out, you can also use `.hasOwnProperty` method. |
41,346,681 | i have a set of code that i copied from someone on youtube and i completely understand and there is some unused logic in there but basically at the moment all it is meant to do is grab the rocket.show function and draw a rectangle and i cannot for the life of me work out why it is not doing so. it is throwing out no errors and drawing the background, i can draw the rectangle if i just put the code for "rect..." in the draw function therefore there is a problem with the way that i am referring to the function but i cannot for the life of me work it out, the code is below, any help would be appreciated.
```
function setup() {
createCanvas(800, 600);
background(0);
rocket = new rocket();
}
function draw() {
rocket.update;
rocket.show;
}
function rocket() {
this.pos = createVector();
this.vel = createVector();
this.acc = createVector();
this.applyforce = function (force) {
this.acc.add(force);
}
this.update = function () {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.mult(0);
}
this.show = function () {
push();
translate(this.pos.x, this.pos.y);
rotate(this.vel.heading());
rectMode(CENTER);
rect(0, 0, 10, 50);
pop();
}
}
```
edit: I worked it out, sorry for taking up needless posting space | 2016/12/27 | [
"https://Stackoverflow.com/questions/41346681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6308045/"
] | You should check for the *first* property that might not exist: so don't check the `coconut.color` property before you are sure that `coconut` exists.
If the property you check for should be an object (which is your case) then you can do so with the `!` operator:
```
if (!myObj.fruits.coconut) myObj.fruits.coconut = { color: 'brown' };
``` | Underscore js contains **\_.has** [link](http://underscorejs.org/#has)
>
> \_.has(object, key)
> Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.
>
>
>
```
_.has({a: 1, b: 2, c: 3}, "b");
=> true
```
Obviously, hackerrdave answer is suffice, but if you're using underscorejs then it's slightly simpler. |
6,658 | В чем их отличие?
Согласно некоторым источникам "просветительская" - принадлежащая тому, кто просвещает, - просветителю. "Просветительная" - направленная на просвещение. Путаница, да и только.
Например, просветительная работа для родителей. Думаю, этот вариант верен. | 2012/07/19 | [
"https://rus.stackexchange.com/questions/6658",
"https://rus.stackexchange.com",
"https://rus.stackexchange.com/users/653/"
] | >
>
> >
> >
> > >
> > > Согласно некоторым источникам "просветительская" - принадлежащая тому, кто просвещает, - просветителю. "Просветительная" - направленная на просвещение.
> > >
> > >
> > >
> >
> >
> >
>
>
>
Всё так. Никакой путаницы. Другое дело, что во многих случаях подходят оба варианта.
"Просветительская" ведь не только принадлежащая просветителю, а ещё и свойсвенная ему, этот вариант более частый. "Просветительская деятельность" - деятельность просветителя.
>
>
> >
> >
> > >
> > > Просветительная работа для родителей
> > >
> > >
> > >
> > >
> > >
> >
> >
> >
>
>
>
О чем речь? Очень может быть, что и "просветительская". | ПРОСВЕТИТЕЛЬНЫЙ, -ая, -ое.
1.
Служащий просвещению;распространяющий знания. П. кружок. **П-ая работа.**
2.
Связанный с учениями и деятельностью представителей эпохи Просвещения или просветительства. П-ие идеи
(о просветительских учениях 17 - 18 вв.). П-ая философия.
ПРОСВЕТИТЕЛЬСКИЙ, -ая, -ое.
к Просветитель и Просветительство. **П-ая деятельность.** П-ие идеи.
(Большой толковый словарь Кузнецова. С "Грамоты")
**Просветитель - 1.Распространитель знаний, просвещения**.2.Представитель т. наз. Эпохи просвещения в 18 в. и русского просветительства середины 19 века (истор.)
Разницу видите? Я -нет. Надо признать, что эти слова в данном контексте являются синонимами. |
46,808,446 | I'm working on a responsive website. I have tried EVERYTHING and my footer won't stay down. It's because I used float:left. I don't want it to be fixed, i want it only to appear when i scroll to the bottom of the page. This is my code:
EDIT: ok so i took position:absolute out and now it works on the pages it didn't before. but on the pages where i didn't use float:left it doesn't work anymore.
```css
footer {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 1.2em;
background-color: #24478f;
color: black;
text-align: center;
font-family: Calibri;
font-size: 4vw;
max-width: 100%;
clear: both;
}
#container figure {
width: 100%;
float: left;
display: block;
overflow: hidden;
}
...
@media only screen and (min-device-width: 1000px) {
#container figure {
width: 33%;
display: block;
overflow: hidden;
}
}
```
```html
<section id="container">
<figure>
<a href="Portfolio.html#applications">
<img src="../imgs/74599-200.png">
</a>
<figcaption>Multimedia Applications</figcaption>
</figure>
<figure>
<a href="Portfolio.html#retrieval">
<img src="../imgs/info1600.png">
</a>
<figcaption>Information Retrieval</figcaption>
</figure>
<figure>
<a href="Portfolio.html#games">
<img src="../imgs/3281-200.png">
</a>
<figcaption>Computer Games</figcaption>
</figure>
</section>
<footer>
<p> Infia Abelha</p>
</footer>
``` | 2017/10/18 | [
"https://Stackoverflow.com/questions/46808446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7906130/"
] | `random.randint` only takes two arguments, a start and an end. The third argument mentioned by Python is `self`, which is done automatically.
To pick a number between 1 and 3, just do `random.randint(1,3)`.
Those `if` statements don't make any sense, by the way; they should look something like:
```
if userInput == "paper":
# send discord messages
``` | if you need more than one random number,you can also use `numpy.random.randint(start,stop-1,number of randoms)` |
46,808,446 | I'm working on a responsive website. I have tried EVERYTHING and my footer won't stay down. It's because I used float:left. I don't want it to be fixed, i want it only to appear when i scroll to the bottom of the page. This is my code:
EDIT: ok so i took position:absolute out and now it works on the pages it didn't before. but on the pages where i didn't use float:left it doesn't work anymore.
```css
footer {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 1.2em;
background-color: #24478f;
color: black;
text-align: center;
font-family: Calibri;
font-size: 4vw;
max-width: 100%;
clear: both;
}
#container figure {
width: 100%;
float: left;
display: block;
overflow: hidden;
}
...
@media only screen and (min-device-width: 1000px) {
#container figure {
width: 33%;
display: block;
overflow: hidden;
}
}
```
```html
<section id="container">
<figure>
<a href="Portfolio.html#applications">
<img src="../imgs/74599-200.png">
</a>
<figcaption>Multimedia Applications</figcaption>
</figure>
<figure>
<a href="Portfolio.html#retrieval">
<img src="../imgs/info1600.png">
</a>
<figcaption>Information Retrieval</figcaption>
</figure>
<figure>
<a href="Portfolio.html#games">
<img src="../imgs/3281-200.png">
</a>
<figcaption>Computer Games</figcaption>
</figure>
</section>
<footer>
<p> Infia Abelha</p>
</footer>
``` | 2017/10/18 | [
"https://Stackoverflow.com/questions/46808446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7906130/"
] | `random.randint` only takes two arguments, a start and an end. The third argument mentioned by Python is `self`, which is done automatically.
To pick a number between 1 and 3, just do `random.randint(1,3)`.
Those `if` statements don't make any sense, by the way; they should look something like:
```
if userInput == "paper":
# send discord messages
``` | I had the same problem, I was building a guess-the-number script, and since I provided all the numbers between 1 and 10. I think you are supposed to format it as random.randit(1,3) instead of listing the variable in between. If you use (1,3) it also accounts for the variable in between those two numbers.
-edit
I did not see that someone already answered this question, if you have anymore questions I am happy to help. |
46,808,446 | I'm working on a responsive website. I have tried EVERYTHING and my footer won't stay down. It's because I used float:left. I don't want it to be fixed, i want it only to appear when i scroll to the bottom of the page. This is my code:
EDIT: ok so i took position:absolute out and now it works on the pages it didn't before. but on the pages where i didn't use float:left it doesn't work anymore.
```css
footer {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 1.2em;
background-color: #24478f;
color: black;
text-align: center;
font-family: Calibri;
font-size: 4vw;
max-width: 100%;
clear: both;
}
#container figure {
width: 100%;
float: left;
display: block;
overflow: hidden;
}
...
@media only screen and (min-device-width: 1000px) {
#container figure {
width: 33%;
display: block;
overflow: hidden;
}
}
```
```html
<section id="container">
<figure>
<a href="Portfolio.html#applications">
<img src="../imgs/74599-200.png">
</a>
<figcaption>Multimedia Applications</figcaption>
</figure>
<figure>
<a href="Portfolio.html#retrieval">
<img src="../imgs/info1600.png">
</a>
<figcaption>Information Retrieval</figcaption>
</figure>
<figure>
<a href="Portfolio.html#games">
<img src="../imgs/3281-200.png">
</a>
<figcaption>Computer Games</figcaption>
</figure>
</section>
<footer>
<p> Infia Abelha</p>
</footer>
``` | 2017/10/18 | [
"https://Stackoverflow.com/questions/46808446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7906130/"
] | if you need more than one random number,you can also use `numpy.random.randint(start,stop-1,number of randoms)` | I had the same problem, I was building a guess-the-number script, and since I provided all the numbers between 1 and 10. I think you are supposed to format it as random.randit(1,3) instead of listing the variable in between. If you use (1,3) it also accounts for the variable in between those two numbers.
-edit
I did not see that someone already answered this question, if you have anymore questions I am happy to help. |
52,914,982 | I'm trying to implement my own TabBar design in flutter. I was able to get a pretty good result. However, when I tap another tab to change the tab, there is a highlight create by default as shown in the image [here](https://i.stack.imgur.com/XBwMg.png). I'm wondering if there is any way I can get rid of the square highlight on tapped. I've been looking around for like almost a day not and did not find any solution.
If anyone have any solution please let me know. Thanks.
Edited: as CopsOnRoad suggestion I wrapped the TabBar in the Container and set the color to `Colors.transparent`, but it does not really disappear so I tried to set the color to `Theme.of(context).canvasColor` for now.
```
Container(
color: Theme.of(context).canvasColor,
child: TabBar(
isScrollable: true,
indicator: ShapeDecoration(
color: Color(0xFFE6E6E6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(99.0)
)
),
tabs: List<Widget>.generate(
categories.length,
(index) => Tab(
child: Text(
categories[index],
style: TextStyle(
fontFamily: 'Hiragino Sans',
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Color(0xFF4D4D4D),
),
),
)
),
)
)
``` | 2018/10/21 | [
"https://Stackoverflow.com/questions/52914982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4914834/"
] | That's the ripple effect. You can remove it by wrapping it in a `Container` and giving transparent color to it. | You can also disable the ripple/highlight/splash effect with the code below. Add the Theme with the data of ThemeData where the hightlight and splash color is both transparent.
```
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(70),
child: Theme(
data: ThemeData(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
),
child: AppBar( ... )
``` |
52,914,982 | I'm trying to implement my own TabBar design in flutter. I was able to get a pretty good result. However, when I tap another tab to change the tab, there is a highlight create by default as shown in the image [here](https://i.stack.imgur.com/XBwMg.png). I'm wondering if there is any way I can get rid of the square highlight on tapped. I've been looking around for like almost a day not and did not find any solution.
If anyone have any solution please let me know. Thanks.
Edited: as CopsOnRoad suggestion I wrapped the TabBar in the Container and set the color to `Colors.transparent`, but it does not really disappear so I tried to set the color to `Theme.of(context).canvasColor` for now.
```
Container(
color: Theme.of(context).canvasColor,
child: TabBar(
isScrollable: true,
indicator: ShapeDecoration(
color: Color(0xFFE6E6E6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(99.0)
)
),
tabs: List<Widget>.generate(
categories.length,
(index) => Tab(
child: Text(
categories[index],
style: TextStyle(
fontFamily: 'Hiragino Sans',
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Color(0xFF4D4D4D),
),
),
)
),
)
)
``` | 2018/10/21 | [
"https://Stackoverflow.com/questions/52914982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4914834/"
] | That's the ripple effect. You can remove it by wrapping it in a `Container` and giving transparent color to it. | Here is my custom solution from @Tempelriter
```
Theme(
data: Theme.of(context).copyWith(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
),
child: Container(
decoration: BoxDecoration(
color: Colors.gray,
border: Border.all(
color: Colors.red
),
borderRadius: BorderRadius.circular(50),
),
child: TabBar(
isScrollable: true,
tabs: [
Tab(text: 'comingSoon'),
Tab(text: 'selling'),
],
),
),
);
``` |
52,914,982 | I'm trying to implement my own TabBar design in flutter. I was able to get a pretty good result. However, when I tap another tab to change the tab, there is a highlight create by default as shown in the image [here](https://i.stack.imgur.com/XBwMg.png). I'm wondering if there is any way I can get rid of the square highlight on tapped. I've been looking around for like almost a day not and did not find any solution.
If anyone have any solution please let me know. Thanks.
Edited: as CopsOnRoad suggestion I wrapped the TabBar in the Container and set the color to `Colors.transparent`, but it does not really disappear so I tried to set the color to `Theme.of(context).canvasColor` for now.
```
Container(
color: Theme.of(context).canvasColor,
child: TabBar(
isScrollable: true,
indicator: ShapeDecoration(
color: Color(0xFFE6E6E6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(99.0)
)
),
tabs: List<Widget>.generate(
categories.length,
(index) => Tab(
child: Text(
categories[index],
style: TextStyle(
fontFamily: 'Hiragino Sans',
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Color(0xFF4D4D4D),
),
),
)
),
)
)
``` | 2018/10/21 | [
"https://Stackoverflow.com/questions/52914982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4914834/"
] | That's the ripple effect. You can remove it by wrapping it in a `Container` and giving transparent color to it. | you should set tabbar `splashFactory: NoSplash.splashFactory` as this post mentioned.
```
TabBar(splashFactory: NoSplash.splashFactory,)
```
[How to disable default Widget splash effect in Flutter?](https://stackoverflow.com/questions/50020523/how-to-disable-default-widget-splash-effect-in-flutter) |
52,914,982 | I'm trying to implement my own TabBar design in flutter. I was able to get a pretty good result. However, when I tap another tab to change the tab, there is a highlight create by default as shown in the image [here](https://i.stack.imgur.com/XBwMg.png). I'm wondering if there is any way I can get rid of the square highlight on tapped. I've been looking around for like almost a day not and did not find any solution.
If anyone have any solution please let me know. Thanks.
Edited: as CopsOnRoad suggestion I wrapped the TabBar in the Container and set the color to `Colors.transparent`, but it does not really disappear so I tried to set the color to `Theme.of(context).canvasColor` for now.
```
Container(
color: Theme.of(context).canvasColor,
child: TabBar(
isScrollable: true,
indicator: ShapeDecoration(
color: Color(0xFFE6E6E6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(99.0)
)
),
tabs: List<Widget>.generate(
categories.length,
(index) => Tab(
child: Text(
categories[index],
style: TextStyle(
fontFamily: 'Hiragino Sans',
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Color(0xFF4D4D4D),
),
),
)
),
)
)
``` | 2018/10/21 | [
"https://Stackoverflow.com/questions/52914982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4914834/"
] | You can also disable the ripple/highlight/splash effect with the code below. Add the Theme with the data of ThemeData where the hightlight and splash color is both transparent.
```
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(70),
child: Theme(
data: ThemeData(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
),
child: AppBar( ... )
``` | Here is my custom solution from @Tempelriter
```
Theme(
data: Theme.of(context).copyWith(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
),
child: Container(
decoration: BoxDecoration(
color: Colors.gray,
border: Border.all(
color: Colors.red
),
borderRadius: BorderRadius.circular(50),
),
child: TabBar(
isScrollable: true,
tabs: [
Tab(text: 'comingSoon'),
Tab(text: 'selling'),
],
),
),
);
``` |
52,914,982 | I'm trying to implement my own TabBar design in flutter. I was able to get a pretty good result. However, when I tap another tab to change the tab, there is a highlight create by default as shown in the image [here](https://i.stack.imgur.com/XBwMg.png). I'm wondering if there is any way I can get rid of the square highlight on tapped. I've been looking around for like almost a day not and did not find any solution.
If anyone have any solution please let me know. Thanks.
Edited: as CopsOnRoad suggestion I wrapped the TabBar in the Container and set the color to `Colors.transparent`, but it does not really disappear so I tried to set the color to `Theme.of(context).canvasColor` for now.
```
Container(
color: Theme.of(context).canvasColor,
child: TabBar(
isScrollable: true,
indicator: ShapeDecoration(
color: Color(0xFFE6E6E6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(99.0)
)
),
tabs: List<Widget>.generate(
categories.length,
(index) => Tab(
child: Text(
categories[index],
style: TextStyle(
fontFamily: 'Hiragino Sans',
fontWeight: FontWeight.bold,
fontSize: 18.0,
color: Color(0xFF4D4D4D),
),
),
)
),
)
)
``` | 2018/10/21 | [
"https://Stackoverflow.com/questions/52914982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4914834/"
] | You can also disable the ripple/highlight/splash effect with the code below. Add the Theme with the data of ThemeData where the hightlight and splash color is both transparent.
```
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(70),
child: Theme(
data: ThemeData(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
),
child: AppBar( ... )
``` | you should set tabbar `splashFactory: NoSplash.splashFactory` as this post mentioned.
```
TabBar(splashFactory: NoSplash.splashFactory,)
```
[How to disable default Widget splash effect in Flutter?](https://stackoverflow.com/questions/50020523/how-to-disable-default-widget-splash-effect-in-flutter) |
22,329,950 | I want to share multi images with caption on Facebook using Intent. I tried some ways but it doesn't work. I can share photos but not the caption. Can you help me, please? Thanks!!!
My share function
```
private void share(String nameApp, ArrayList<String> imagePath, String text) {
try {
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent share = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
share.setType("image/*");
List<ResolveInfo> resInfo = getActivity().getPackageManager().queryIntentActivities(share, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(
android.content.Intent.ACTION_SEND_MULTIPLE);
targetedShare.setType("image/*");
if (info.activityInfo.packageName.toLowerCase().contains(nameApp)
|| info.activityInfo.name.toLowerCase().contains(nameApp)) {
ArrayList<Uri> uris = new ArrayList<Uri>();
for (int i = 0; i < nImageCount; i++){
uris.add(Uri.parse("file://" + imagePath.get(i)));
}
targetedShare.putExtra(Intent.EXTRA_TITLE, text);
targetedShare.putExtra(Intent.EXTRA_TEXT, text);
targetedShare.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
}
}
Intent chooserIntent = Intent.createChooser(
targetedShareIntents.remove(0), "Select app to share");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
targetedShareIntents.toArray(new Parcelable[] {}));
startActivity(chooserIntent);
}
} catch (Exception e) {
}
}
``` | 2014/03/11 | [
"https://Stackoverflow.com/questions/22329950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2714606/"
] | ```
SELECT Car, Shop, Prices
FROM `Car List`
WHERE Car = 'Mercedes'
```
Depending on your DB engine you need to escape tables names containing spaces differently. | ```
SELECT Car, Shop, Prices
FROM "Car List"
WHERE UPPER(Car) LIKE '%MERCEDES%'
```
You may need to change double quotes depending on the RDBMS you are using. Also, this solution is slower than the equal solution for several reasons but it is more compatible if your data is messy. |
22,329,950 | I want to share multi images with caption on Facebook using Intent. I tried some ways but it doesn't work. I can share photos but not the caption. Can you help me, please? Thanks!!!
My share function
```
private void share(String nameApp, ArrayList<String> imagePath, String text) {
try {
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent share = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
share.setType("image/*");
List<ResolveInfo> resInfo = getActivity().getPackageManager().queryIntentActivities(share, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(
android.content.Intent.ACTION_SEND_MULTIPLE);
targetedShare.setType("image/*");
if (info.activityInfo.packageName.toLowerCase().contains(nameApp)
|| info.activityInfo.name.toLowerCase().contains(nameApp)) {
ArrayList<Uri> uris = new ArrayList<Uri>();
for (int i = 0; i < nImageCount; i++){
uris.add(Uri.parse("file://" + imagePath.get(i)));
}
targetedShare.putExtra(Intent.EXTRA_TITLE, text);
targetedShare.putExtra(Intent.EXTRA_TEXT, text);
targetedShare.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
}
}
Intent chooserIntent = Intent.createChooser(
targetedShareIntents.remove(0), "Select app to share");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
targetedShareIntents.toArray(new Parcelable[] {}));
startActivity(chooserIntent);
}
} catch (Exception e) {
}
}
``` | 2014/03/11 | [
"https://Stackoverflow.com/questions/22329950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2714606/"
] | Define "it doesn't work." Surely there's an error message that's trying to help you?
For example, what is the data type of `Car`? Based on the attempted comparison, it sounds like it's a string. In which case the value being compared would need to be wrapped in quotes:
```
SELECT Car, Shop, Prices WHERE Car = 'Mercedes' FROM Car List
```
Otherwise the query will look for a column called "Mercedes" in the table, which doesn't exist.
Also, your clauses are out of order. The order should be `SELECT FROM WHERE` not `SELECT WHERE FROM` (at least, I've never *seen* the latter used):
```
SELECT Car, Shop, Prices FROM Car List WHERE Car = 'Mercedes'
```
Additionally, your table name has a space in it. In general it's best to avoid this, but if you *must* use spaces then in order for the database to parse the query you need to tell it that both of those words form a single identifier. In SQL Server this is done with square brackets:
```
SELECT Car, Shop, Prices FROM [Car List] WHERE Car = 'Mercedes'
```
If you're using another database engine, you may need to use another enclosing standard. For example, MySQL uses backticks:
```
SELECT Car, Shop, Prices FROM `Car List` WHERE Car = 'Mercedes'
```
Continuing in this regard, it's often good practice to enclose any database object identifier in square brackets just to be explicit and consistent (using whichever identifier your database engine uses):
```
SELECT [Car], [Shop], [Prices] FROM [Car List] WHERE [Car] = 'Mercedes'
``` | ```
SELECT Car, Shop, Prices
FROM "Car List"
WHERE UPPER(Car) LIKE '%MERCEDES%'
```
You may need to change double quotes depending on the RDBMS you are using. Also, this solution is slower than the equal solution for several reasons but it is more compatible if your data is messy. |
24,366,351 | I have a string that contains an exe full path and exe name like so:
```
mainExePath = "c:\Folder1\Folder2\MyProgram.exe"
```
I want to get jus the path like so:
```
"c:\Folder1\Folder2\"
```
I have tried this:
```
string mainPath = System.IO.Path.GetFullPath(mainExePath);
```
but this returned the same string.
How can I do this? | 2014/06/23 | [
"https://Stackoverflow.com/questions/24366351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2339664/"
] | Use `Path.GetDirectoryName(mainExePath)` | That would be
```
string mainPath = Path.GetDirectoryName(mainExePath);
```
This works for both paths including file names and paths only.
See the [documentation here](http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname%28v=vs.110%29.aspx). |
24,366,351 | I have a string that contains an exe full path and exe name like so:
```
mainExePath = "c:\Folder1\Folder2\MyProgram.exe"
```
I want to get jus the path like so:
```
"c:\Folder1\Folder2\"
```
I have tried this:
```
string mainPath = System.IO.Path.GetFullPath(mainExePath);
```
but this returned the same string.
How can I do this? | 2014/06/23 | [
"https://Stackoverflow.com/questions/24366351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2339664/"
] | Use `Path.GetDirectoryName(mainExePath)` | You could use the following one:
```
string mainPath = Directory.GetParent(mainExePath);
```
For further documentation on this, please haev a look [here](http://msdn.microsoft.com/en-us/library/system.io.directory.getparent%28v=vs.110%29.aspx).
**Update**
In order you use the `Directory` class, you have to use the `System.IO`. So please, on the sections of your source file, where you have placed the `using` statements for namespaces, please add also the below one:
```
using System.IO;
``` |
29,094 | How does one set a flash message in the templates? I can't find any documentation about this, only for plugins or getting the message.
My use-case is, I am checking if a user is allowed to access a certain page and if they cannot I want to set a flash message, then redirect them to another page. I prefer this than to keep them on the same page and is if else logic to show the message or the rest of the page.
Thanks | 2019/01/12 | [
"https://craftcms.stackexchange.com/questions/29094",
"https://craftcms.stackexchange.com",
"https://craftcms.stackexchange.com/users/4993/"
] | You can set [flash messages](https://www.yiiframework.com/doc/guide/2.0/en/runtime-sessions-cookies#flash-data) using [yii\web\Session::setFlash()](https://www.yiiframework.com/doc/api/2.0/yii-web-session#setFlash()-detail).
The `session` component is available to templates via `craft.app.session`.
```
{% do craft.app.session.setFlash('error', 'You’re not allowed to go there.') %}
```
For convenience, Craft’s [SessionBehavior](https://docs.craftcms.com/api/v3/craft-behaviors-sessionbehavior.html) class adds shortcut [setError()](https://docs.craftcms.com/api/v3/craft-behaviors-sessionbehavior.html#method-seterror) and [setNotice()](https://docs.craftcms.com/api/v3/craft-behaviors-sessionbehavior.html#method-setnotice) methods to the `session` component as well.
```
{% do craft.app.session.setError('You’re not allowed to go there.') %}
```
You can place that right before your `{% redirect %}` tag. | **Edit: Brandon replied as I was writing this. Feel free to remove :)**
You can do that using this in your conditional, just above your redirect tag
```
{% do craft.app.session.setFlash('error', 'no no no') %}
{% redirect "tosomewhere" %}
```
Then in the template you are redirecting to
```
{% set message = craft.app.session.getFlash('error', null, true) %}
{% if message %}
{{ message }}
{% endif %}
``` |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | This sounds like one of those rules that someone made up because they could think of examples where breaking it caused problems, but didn't try to think through if breaking it would ALWAYS cause problems.
Well, off the top let me point out that the rule as worded, "never use two possessives in a row", is clearly wrong. People do that all the time and it makes perfect sense. "My dog's bone", "Fred's car's engine", etc. In examples like that, the first possessive modifies the first noun, and then that phrase is used as a possessive to modify the second noun. I mean, in "my dog's bone", I am saying that the dog belongs to me, and that the bone belongs to this dog which belongs to me. Both possessives are not modifying the same word. It is not "my bone" and also some "dog's bone".
But I assume that whoever made up this rule meant that you cannot have two possessives modifying the same noun. You can't say "Fred's Bob's car". That example clearly doesn't make sense. Is it Fred's car, or is it Bob's car? If it belongs to both, you need to join them with an "and", like "Fred's and Bob's car". If you're not sure of the ownership, you need to join them with an "or", like, "The red Chevy is either Fred's or Bob's car".
But possessives are used for many things other than ownership. If I am at work and I refer to "my desk", I probably don't mean that I own the desk, but rather that this is the desk where the company has assigned me to sit while I work. If I say, "my state", I don't mean that I personally own the entire state and everything in it. I simply mean that I live there. Etc.
So if I say "our meeting", I don't mean that I own the meeting. I don't know what that would even mean. I mean the meeting between you and me, or possibly the meeting that you and I organized. If I say "last week's meeting", I mean the meeting that happened last week. There is no reason why a meeting could not be both "our meeting" and "last week's meeting", so "our last week's meeting" is a perfectly sensible thing to say. And indeed people say things like that all the time.
Yes, USUALLY two possessives in a row that both apply to the same noun is wrong. But it's not valid to say that because something is USUALLY wrong that therefore you should NEVER do it. | "Our today's meeting" means literally "(the) meeting of our today". This is why it's wrong. I believe we all agree that nobody would say "meeting of our today". |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | I've answered essentially the same question over at english.stackexchange.com: [Why is “our today's meeting” wrong?](https://english.stackexchange.com/questions/251561/why-is-our-todays-meeting-wrong)
Usually, a noun phrase in English must have exactly one determiner: you can say "I drove this car" or "I drove my car", but not "I drove car" or "I drove this my car".
Certain nouns (such as plural nouns and proper nouns) don't need determiners: "I love bees", "I love milk", "I love Paris", "I love biology". But it's never acceptable for a noun phrase to have more than one determiner (with possible extremely rare exceptions).
"Our last week's meeting" is unacceptable because the noun phrase "meeting" has two determiners, "our" and "last week's". It would also be unacceptable to say "the today's meeting" or "our the meeting".
Here are some phrases which may *seem* to have multiple determiners, but don't actually:
* your father's home - this noun phrase has only one determiner, namely, "your father's". Meanwhile, the phrase "your father" is also a noun phrase which only has one determiner, namely, "your".
* the brass men's wristwatches - the determiner of this noun phrase is "the", and "brass" and "men's" are adjectives.
* an old people's home - the determiner of this noun phrase is "an". The phrase "old people's home" is an idiom which acts as a simple noun, even though it looks like it contains a determiner. | It's either:
>
> Last week's meeting
>
>
>
or:
>
> Our meeting last week
>
>
>
but I agree with your teacher that:
>
> Our last week's meeting
>
>
>
sounds awkward and should probably be avoided. |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | There isn't a rule that you can't use two possessives, but they don't indicate possession of the noun at the end, but instead each one modifies the next phrase.
>
> Our last week's meeting
>
>
>
Is naturally read as
>
> (Our last week)'s meeting
>
>
>
So, unless you are talking about meeting someone with in the week before you both die, it is unlikely to mean what you intend.
Multiple possessives tend to combine left to right, so
>
> your mother's old uncle's shepherds pie
>
>
>
Is the pie of a type associated with shepherds belonging to the old uncle of your mother.
>
> (((your mother)'s old uncle)'s (shepherds pie)
>
>
>
It doesn't mean that there is an old pie which belongs to you, your mother, an uncle and a number of shepherds all at the same time!
The example of course proves the rule - 'shepherds pie' is an idiomatic noun phrase so doesn't combine. | You can use two possessives in a row, that is not an issue. For example, if I have a cat, and my cat has a toy, I can say "my cat's toy." If there is a manufacturer for that toy, it would be somewhat acceptable, although convoluted, to say "my cat's toy's manufacturer," which would be three possessives in a row. If that manufacturer had subsidiaries, it would be much harder to follow, but you could probably still say "my cat's toy's manufacturer's subsidiaries." Though, with four possessives in a row, we'd probably rearrange the sentence structure to break them up some.
In English, we would commonly say "last week's meeting," or perhaps "our meeting last week." We don't put an "our" modifier before a chronological modifier, such as "our last week's meeting," or "our today's meeting." The expectation is that "our" probably modifies the word that directly follows it, in other words, it sounds like "our" modifies "last week." But "last week," doesn't belong to us, so this sounds very weird. Unless you actually need the "our" modifier to clarify whose meeting *and* you need the "last week" modifier to clarify the time of the meeting, it makes sense to drop the modifier that is less helpful at conveying meeting. |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | There is no such rule: "our last week's meeting" is perfectly grammatical. There could be a last week's meeting that is not our: "the other team's last week's meeting raised the issue that we covering in our this week's meeting".
The phrase "in our last week's episode" is often heard in broadcasting, from native speakers of English.
The issue is that possessives don't always indicate possession. "last week's meeting" isn't a meeting that is possessed by last week; it just happened last week. That the meeting happened last week doesn't prevent it from also being our meeting.
Possession is exclusive. We can't have "Bob's John's pencil". The pen is either Bob's or John's. If there is a joint ownership arrangement with regard to the pencil, then this is expressed as "Bob and John's pencil". However, there can be a "Bob's carpenter's pencil". The second 's-word isn't a possessive; it's not saying that Bob owns a pencil which also belongs to some carpenter; the word "carpenter" here is a class, and the 's syntax indicates the pencil object's association with that class. That association is compatible with Bob owning the pencil, so both qualifiers can be applied.
Note that order is important; we would not say "carpenter's Bob's pen". The class relationship is applied to the pen first, then the specific ownership by Bob. There aren't pens which are primarily owned by Bob, and, secondarily, are carpenter's pens.
For similar reasons, we don't have "last week's our episode". We are not saying that the last week owns the meeting and so do we. If that were the case, it would be expressed as "ours and last week's meeting" (just like "Bob and John's pencil"), which is grammatical, but nonsense.
It seems that the time constraint "last week's" has to be applied first, and then the specific possessive.
What if we have multiple such 's qualifiers? How about "my last year's driver's license". This cannot be "my driver's last year's license" or any other permutation: the order has to be "owner -> time/space -> class -> object". | "Our today's meeting" means literally "(the) meeting of our today". This is why it's wrong. I believe we all agree that nobody would say "meeting of our today". |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | I've answered essentially the same question over at english.stackexchange.com: [Why is “our today's meeting” wrong?](https://english.stackexchange.com/questions/251561/why-is-our-todays-meeting-wrong)
Usually, a noun phrase in English must have exactly one determiner: you can say "I drove this car" or "I drove my car", but not "I drove car" or "I drove this my car".
Certain nouns (such as plural nouns and proper nouns) don't need determiners: "I love bees", "I love milk", "I love Paris", "I love biology". But it's never acceptable for a noun phrase to have more than one determiner (with possible extremely rare exceptions).
"Our last week's meeting" is unacceptable because the noun phrase "meeting" has two determiners, "our" and "last week's". It would also be unacceptable to say "the today's meeting" or "our the meeting".
Here are some phrases which may *seem* to have multiple determiners, but don't actually:
* your father's home - this noun phrase has only one determiner, namely, "your father's". Meanwhile, the phrase "your father" is also a noun phrase which only has one determiner, namely, "your".
* the brass men's wristwatches - the determiner of this noun phrase is "the", and "brass" and "men's" are adjectives.
* an old people's home - the determiner of this noun phrase is "an". The phrase "old people's home" is an idiom which acts as a simple noun, even though it looks like it contains a determiner. | There isn't a rule that you can't use two possessives, but they don't indicate possession of the noun at the end, but instead each one modifies the next phrase.
>
> Our last week's meeting
>
>
>
Is naturally read as
>
> (Our last week)'s meeting
>
>
>
So, unless you are talking about meeting someone with in the week before you both die, it is unlikely to mean what you intend.
Multiple possessives tend to combine left to right, so
>
> your mother's old uncle's shepherds pie
>
>
>
Is the pie of a type associated with shepherds belonging to the old uncle of your mother.
>
> (((your mother)'s old uncle)'s (shepherds pie)
>
>
>
It doesn't mean that there is an old pie which belongs to you, your mother, an uncle and a number of shepherds all at the same time!
The example of course proves the rule - 'shepherds pie' is an idiomatic noun phrase so doesn't combine. |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | I've answered essentially the same question over at english.stackexchange.com: [Why is “our today's meeting” wrong?](https://english.stackexchange.com/questions/251561/why-is-our-todays-meeting-wrong)
Usually, a noun phrase in English must have exactly one determiner: you can say "I drove this car" or "I drove my car", but not "I drove car" or "I drove this my car".
Certain nouns (such as plural nouns and proper nouns) don't need determiners: "I love bees", "I love milk", "I love Paris", "I love biology". But it's never acceptable for a noun phrase to have more than one determiner (with possible extremely rare exceptions).
"Our last week's meeting" is unacceptable because the noun phrase "meeting" has two determiners, "our" and "last week's". It would also be unacceptable to say "the today's meeting" or "our the meeting".
Here are some phrases which may *seem* to have multiple determiners, but don't actually:
* your father's home - this noun phrase has only one determiner, namely, "your father's". Meanwhile, the phrase "your father" is also a noun phrase which only has one determiner, namely, "your".
* the brass men's wristwatches - the determiner of this noun phrase is "the", and "brass" and "men's" are adjectives.
* an old people's home - the determiner of this noun phrase is "an". The phrase "old people's home" is an idiom which acts as a simple noun, even though it looks like it contains a determiner. | >
> Our last week's meeting
>
>
>
is a little akward, but I for one do **not** think that it is incorrect.
The answer by Tanner Swett says "it's never acceptable for a noun phrase to have more than one determiner." However, [the Wikipedia article](https://en.wikipedia.org/wiki/English_determiners#Combinations_of_determiners) lists eight different "common" cases where multiple determiners are acceptable. Specifically:
>
> * A definite determiner can be followed by certain quantifiers (*the many problems, these three things, my very few faults*).
> * The words all and both can be followed by a definite determiner (*all the green apples, both the boys*), which can also be followed by a quantifier as above (*all the many outstanding issues*).
> * The word all can be followed by a cardinal number (*all three things*).
> * The word some can be followed by a cardinal number (*some eight packets*, meaning "approximately eight").
> * Words and phrases expressing fractions and multiples, such as *half, double, twice, three times*, etc. can be followed by a definite determiner: *half a minute, double the risk, twice my age, three times my salary, three-quarters the diameter*, etc.
> * The words such and exclamative-what can be followed by an indefinite article (as mentioned in the section above).
> * The word many can be used with the indefinite article and a singular noun (*many a night, many an awkward moment*).
> * The words each and every can be followed by a cardinal number or other expression of definite quantity (*each two seats, every five grams of flour*).
>
>
>
...
>
> As with other parts of speech, it is often possible to connect determiners of the same type with the conjunctions and and or: *his and her children, two or three beans*.
>
>
>
The same answer says that "I drove this my car" is wrong. The form "this" followed by a possessive is now rare, but was once more common, especially in formal writing. In particular sentences such as:
>
> It is a mistake to regard aspects of **this our present society** as unchangeable rules.
>
>
>
were sufficiently common to be a style marker in the writings of the late Robert A Heinlein.
Since the question title asks about using "two possessives in a row", this can certainly be proper.
>
> * This was John's father's watch.
> * This was King Mark's wife's cousin's castle.
>
>
>
are both quite correct. |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | I've answered essentially the same question over at english.stackexchange.com: [Why is “our today's meeting” wrong?](https://english.stackexchange.com/questions/251561/why-is-our-todays-meeting-wrong)
Usually, a noun phrase in English must have exactly one determiner: you can say "I drove this car" or "I drove my car", but not "I drove car" or "I drove this my car".
Certain nouns (such as plural nouns and proper nouns) don't need determiners: "I love bees", "I love milk", "I love Paris", "I love biology". But it's never acceptable for a noun phrase to have more than one determiner (with possible extremely rare exceptions).
"Our last week's meeting" is unacceptable because the noun phrase "meeting" has two determiners, "our" and "last week's". It would also be unacceptable to say "the today's meeting" or "our the meeting".
Here are some phrases which may *seem* to have multiple determiners, but don't actually:
* your father's home - this noun phrase has only one determiner, namely, "your father's". Meanwhile, the phrase "your father" is also a noun phrase which only has one determiner, namely, "your".
* the brass men's wristwatches - the determiner of this noun phrase is "the", and "brass" and "men's" are adjectives.
* an old people's home - the determiner of this noun phrase is "an". The phrase "old people's home" is an idiom which acts as a simple noun, even though it looks like it contains a determiner. | This sounds like one of those rules that someone made up because they could think of examples where breaking it caused problems, but didn't try to think through if breaking it would ALWAYS cause problems.
Well, off the top let me point out that the rule as worded, "never use two possessives in a row", is clearly wrong. People do that all the time and it makes perfect sense. "My dog's bone", "Fred's car's engine", etc. In examples like that, the first possessive modifies the first noun, and then that phrase is used as a possessive to modify the second noun. I mean, in "my dog's bone", I am saying that the dog belongs to me, and that the bone belongs to this dog which belongs to me. Both possessives are not modifying the same word. It is not "my bone" and also some "dog's bone".
But I assume that whoever made up this rule meant that you cannot have two possessives modifying the same noun. You can't say "Fred's Bob's car". That example clearly doesn't make sense. Is it Fred's car, or is it Bob's car? If it belongs to both, you need to join them with an "and", like "Fred's and Bob's car". If you're not sure of the ownership, you need to join them with an "or", like, "The red Chevy is either Fred's or Bob's car".
But possessives are used for many things other than ownership. If I am at work and I refer to "my desk", I probably don't mean that I own the desk, but rather that this is the desk where the company has assigned me to sit while I work. If I say, "my state", I don't mean that I personally own the entire state and everything in it. I simply mean that I live there. Etc.
So if I say "our meeting", I don't mean that I own the meeting. I don't know what that would even mean. I mean the meeting between you and me, or possibly the meeting that you and I organized. If I say "last week's meeting", I mean the meeting that happened last week. There is no reason why a meeting could not be both "our meeting" and "last week's meeting", so "our last week's meeting" is a perfectly sensible thing to say. And indeed people say things like that all the time.
Yes, USUALLY two possessives in a row that both apply to the same noun is wrong. But it's not valid to say that because something is USUALLY wrong that therefore you should NEVER do it. |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | >
> Our last week's meeting
>
>
>
is a little akward, but I for one do **not** think that it is incorrect.
The answer by Tanner Swett says "it's never acceptable for a noun phrase to have more than one determiner." However, [the Wikipedia article](https://en.wikipedia.org/wiki/English_determiners#Combinations_of_determiners) lists eight different "common" cases where multiple determiners are acceptable. Specifically:
>
> * A definite determiner can be followed by certain quantifiers (*the many problems, these three things, my very few faults*).
> * The words all and both can be followed by a definite determiner (*all the green apples, both the boys*), which can also be followed by a quantifier as above (*all the many outstanding issues*).
> * The word all can be followed by a cardinal number (*all three things*).
> * The word some can be followed by a cardinal number (*some eight packets*, meaning "approximately eight").
> * Words and phrases expressing fractions and multiples, such as *half, double, twice, three times*, etc. can be followed by a definite determiner: *half a minute, double the risk, twice my age, three times my salary, three-quarters the diameter*, etc.
> * The words such and exclamative-what can be followed by an indefinite article (as mentioned in the section above).
> * The word many can be used with the indefinite article and a singular noun (*many a night, many an awkward moment*).
> * The words each and every can be followed by a cardinal number or other expression of definite quantity (*each two seats, every five grams of flour*).
>
>
>
...
>
> As with other parts of speech, it is often possible to connect determiners of the same type with the conjunctions and and or: *his and her children, two or three beans*.
>
>
>
The same answer says that "I drove this my car" is wrong. The form "this" followed by a possessive is now rare, but was once more common, especially in formal writing. In particular sentences such as:
>
> It is a mistake to regard aspects of **this our present society** as unchangeable rules.
>
>
>
were sufficiently common to be a style marker in the writings of the late Robert A Heinlein.
Since the question title asks about using "two possessives in a row", this can certainly be proper.
>
> * This was John's father's watch.
> * This was King Mark's wife's cousin's castle.
>
>
>
are both quite correct. | You can use two possessives in a row, that is not an issue. For example, if I have a cat, and my cat has a toy, I can say "my cat's toy." If there is a manufacturer for that toy, it would be somewhat acceptable, although convoluted, to say "my cat's toy's manufacturer," which would be three possessives in a row. If that manufacturer had subsidiaries, it would be much harder to follow, but you could probably still say "my cat's toy's manufacturer's subsidiaries." Though, with four possessives in a row, we'd probably rearrange the sentence structure to break them up some.
In English, we would commonly say "last week's meeting," or perhaps "our meeting last week." We don't put an "our" modifier before a chronological modifier, such as "our last week's meeting," or "our today's meeting." The expectation is that "our" probably modifies the word that directly follows it, in other words, it sounds like "our" modifies "last week." But "last week," doesn't belong to us, so this sounds very weird. Unless you actually need the "our" modifier to clarify whose meeting *and* you need the "last week" modifier to clarify the time of the meeting, it makes sense to drop the modifier that is less helpful at conveying meeting. |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | I've answered essentially the same question over at english.stackexchange.com: [Why is “our today's meeting” wrong?](https://english.stackexchange.com/questions/251561/why-is-our-todays-meeting-wrong)
Usually, a noun phrase in English must have exactly one determiner: you can say "I drove this car" or "I drove my car", but not "I drove car" or "I drove this my car".
Certain nouns (such as plural nouns and proper nouns) don't need determiners: "I love bees", "I love milk", "I love Paris", "I love biology". But it's never acceptable for a noun phrase to have more than one determiner (with possible extremely rare exceptions).
"Our last week's meeting" is unacceptable because the noun phrase "meeting" has two determiners, "our" and "last week's". It would also be unacceptable to say "the today's meeting" or "our the meeting".
Here are some phrases which may *seem* to have multiple determiners, but don't actually:
* your father's home - this noun phrase has only one determiner, namely, "your father's". Meanwhile, the phrase "your father" is also a noun phrase which only has one determiner, namely, "your".
* the brass men's wristwatches - the determiner of this noun phrase is "the", and "brass" and "men's" are adjectives.
* an old people's home - the determiner of this noun phrase is "an". The phrase "old people's home" is an idiom which acts as a simple noun, even though it looks like it contains a determiner. | You can use two possessives in a row, that is not an issue. For example, if I have a cat, and my cat has a toy, I can say "my cat's toy." If there is a manufacturer for that toy, it would be somewhat acceptable, although convoluted, to say "my cat's toy's manufacturer," which would be three possessives in a row. If that manufacturer had subsidiaries, it would be much harder to follow, but you could probably still say "my cat's toy's manufacturer's subsidiaries." Though, with four possessives in a row, we'd probably rearrange the sentence structure to break them up some.
In English, we would commonly say "last week's meeting," or perhaps "our meeting last week." We don't put an "our" modifier before a chronological modifier, such as "our last week's meeting," or "our today's meeting." The expectation is that "our" probably modifies the word that directly follows it, in other words, it sounds like "our" modifies "last week." But "last week," doesn't belong to us, so this sounds very weird. Unless you actually need the "our" modifier to clarify whose meeting *and* you need the "last week" modifier to clarify the time of the meeting, it makes sense to drop the modifier that is less helpful at conveying meeting. |
212,569 | Following a previous discussion about **I would like** vs **I would have liked**, I have a similar question.
What is the difference between
>
> I wanted to come to your party but I couldn't
>
>
> I would have liked to come to your party but I couldn't.
>
>
> | 2019/05/28 | [
"https://ell.stackexchange.com/questions/212569",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/96204/"
] | It's either:
>
> Last week's meeting
>
>
>
or:
>
> Our meeting last week
>
>
>
but I agree with your teacher that:
>
> Our last week's meeting
>
>
>
sounds awkward and should probably be avoided. | "Our today's meeting" means literally "(the) meeting of our today". This is why it's wrong. I believe we all agree that nobody would say "meeting of our today". |
73,829,087 | I've created a control and it has a bindable property, but when I try to set its value, it does not set, when I check its setter, it's not getting hit while debugging, not sure what am I doing wrong.
```
public decimal MetricValue
{
get => (decimal)GetValue(MetricValueProperty);
set => SetValue(MetricValueProperty, value);
}
public static readonly BindableProperty MetricValueProperty =
BindableProperty.Create(
propertyName: nameof(MetricValue),
returnType: typeof(decimal),
declaringType: typeof(HeightSelection),
defaultBindingMode: BindingMode.TwoWay,
propertyChanged: MetricValuePropertyChanged);
```
I also have a propertychanged, which is not getting raised
```
<controls:customControl
CurrentSystemOfMeasure="{Binding CurrentSystemOfMeasure}"
MetricValue="{Binding CurrentHeight}"
TextAlignment="Start"
OnHeightSelectedCommand="{Binding HeightSelectionCommand}"
IsValid="True" />
```
any inputs would be helpful | 2022/09/23 | [
"https://Stackoverflow.com/questions/73829087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6155965/"
] | ```
LiteDB `5.x` is .NET Framework 4.5 and .NET Standard 2.0 compatible. You can work with LiteDB in any target framework that .NE TStantard 2.0 is compatible, like:
- .NET 5
- .NET Core 2+
- .NET Framework 4.6.1
- Mono 5.4
- Xamarin.iOS 10.14
- Xamarin.Mac 3.8
- Xamarin.Android 8
- UWP 10.0.16299
- Unity 2018.1
https://learn.microsoft.com/pt-br/dotnet/standard/net-standard
``` | Found that actually liteDB '5.x' works fine with .NET 6. I was just having some trouble with the installation |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | The **@** symbol in front of a string literal tells the compiler to ignore and escape sequences in the string (ie things that begin with a slash) and just to create the string "as-is"
It can also be used to create variables whose name is a reserved work. For example:
```
int @class=10;
```
If you don't prefix the @ then you'd get a compile-time error.
You can also prefix it to variables that are not reserved word:
```
int @foo=22;
```
Note that you can refer to the variable as **foo** or **@foo** in your code. | The @ symbol goes right before the quotes. It only works on string literals, and it simply changes the way the string is understood by the compiler. The main thing it does is cause `\` to be interpreted as a literal backslash, rather than escaping the next character. So you want:
```
String location = args[0] + id + @"\\";
``` |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | It is used for two things:
* create "verbatim" strings (ignores the escape character): `string path = @"C:\Windows"`
* escape language keywords to use them as identifiers: `string @class = "foo"`
In your case you need to do this:
```
String location = args[0] + id + @"\\";
``` | In this case you may not need to use @; just make it
```
String location = args[0] + id + "\\";
``` |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | The @ prefix means the string is a literal string and the processing of escape characters is not performed by the compiler, so:
```
@"\n"
```
is not translated to a newline character. Without it, you'd have:
```
String location = "\\\\192.168.2.10\\datastore\\\\" + id + "\\\\";
```
which looks a bit messy. The '@' tidies things up a bit. The '@' can only be prefixed to string constants, that is, things inside a pair of double quotes ("). Since it is a compiler directive it is only applied at compile time so the string must be known at compile time, hence,
```
@some_string_var
```
doesn't work the way you think. However, since all the '@' does is stop processing of escaped characters by the compiler, a string in a variable already has the escaped character values in it (10,13 for '\n', etc). If you want to convert a '\n' to 10,13 for example at run time you'll need to parse it yourself doing the required substitutions (but I'm sure someone knows a better way).
To get what you want, do:
```
String location = args[0] + id + "\\";
``` | The @ symbol goes right before the quotes. It only works on string literals, and it simply changes the way the string is understood by the compiler. The main thing it does is cause `\` to be interpreted as a literal backslash, rather than escaping the next character. So you want:
```
String location = args[0] + id + @"\\";
``` |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | The @ prefix means the string is a literal string and the processing of escape characters is not performed by the compiler, so:
```
@"\n"
```
is not translated to a newline character. Without it, you'd have:
```
String location = "\\\\192.168.2.10\\datastore\\\\" + id + "\\\\";
```
which looks a bit messy. The '@' tidies things up a bit. The '@' can only be prefixed to string constants, that is, things inside a pair of double quotes ("). Since it is a compiler directive it is only applied at compile time so the string must be known at compile time, hence,
```
@some_string_var
```
doesn't work the way you think. However, since all the '@' does is stop processing of escaped characters by the compiler, a string in a variable already has the escaped character values in it (10,13 for '\n', etc). If you want to convert a '\n' to 10,13 for example at run time you'll need to parse it yourself doing the required substitutions (but I'm sure someone knows a better way).
To get what you want, do:
```
String location = args[0] + id + "\\";
``` | By default the '\' character is an escape character for strings in C#. That means that if you want to have a backslash in your string you need two slashes the first to escape the second as follows:
```
string escaped = "This is a backslash \\";
//The value of escaped is - This is a backslash \
```
An easier example to follow is with the use of quotes:
```
string escaped = "To put a \" in a string you need to escape it";
//The value of escaped is - To put a " in a string you need to escape it
```
The @ symbol is the equivalent of "ignore all escape characters in this string" and declare it verbatim. Without it your first declaration would look like this:
```
"\\\\192.168.2.10\\datastore\\\\" + id + "\\";
```
Note that you already didn't have the @ on your second string, so that string hasn't changed and still only contains a single backslash.
You only need to use the @ symbol when you are declaring strings. Since your argument is already declared it is not needed. So your new line can be:
```
String location = args[0] + id + "\\";
```
or
```
String location = args[0] + id + @"\";
``` |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | In this case you may not need to use @; just make it
```
String location = args[0] + id + "\\";
``` | By default the '\' character is an escape character for strings in C#. That means that if you want to have a backslash in your string you need two slashes the first to escape the second as follows:
```
string escaped = "This is a backslash \\";
//The value of escaped is - This is a backslash \
```
An easier example to follow is with the use of quotes:
```
string escaped = "To put a \" in a string you need to escape it";
//The value of escaped is - To put a " in a string you need to escape it
```
The @ symbol is the equivalent of "ignore all escape characters in this string" and declare it verbatim. Without it your first declaration would look like this:
```
"\\\\192.168.2.10\\datastore\\\\" + id + "\\";
```
Note that you already didn't have the @ on your second string, so that string hasn't changed and still only contains a single backslash.
You only need to use the @ symbol when you are declaring strings. Since your argument is already declared it is not needed. So your new line can be:
```
String location = args[0] + id + "\\";
```
or
```
String location = args[0] + id + @"\";
``` |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | @-quoted string literals start with @ and are enclosed in double quotation marks. For example:
```
@"good morning" // a string literal
```
The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
```
@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"
```
To include a double quotation mark in an @-quoted string, double it:
```
@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.
```
Another use of the @ symbol is to use referenced (/reference) identifiers that happen to be C# keywords. For more information, see 2.4.2 Identifiers.
<http://msdn.microsoft.com/en-us/library/362314fe(v=vs.71).aspx> | The @ symbol is only relevant for string literals in code. Variables should never modify the contents of a string. |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | The **@** symbol in front of a string literal tells the compiler to ignore and escape sequences in the string (ie things that begin with a slash) and just to create the string "as-is"
It can also be used to create variables whose name is a reserved work. For example:
```
int @class=10;
```
If you don't prefix the @ then you'd get a compile-time error.
You can also prefix it to variables that are not reserved word:
```
int @foo=22;
```
Note that you can refer to the variable as **foo** or **@foo** in your code. | If you load from the command line, it will already be escaped for you. This is why your escapes are "ignored" from your perspective. Note that the same is true when you load from config, so don't do this:
```
<add key="pathToFile" value="C:\\myDirectory\\myFile.txt"/>
```
If you do, you end up with double strings, as ".NET" is smart enough to escape thins for you when you load them in this manner. |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | The `@` symbol has two uses in C#.
1. To use a quotes instead of escaping. "\windows" can be represented as @"\windows". "\"John!\"" can be represented @"""John!""".
2. To escape variable names (for example to use a keyword as a parameter name)
private static void InsertSafe (string item, object @lock)
{
lock (@lock)
{
mylist.Insert(0,item);
}
} | If you load from the command line, it will already be escaped for you. This is why your escapes are "ignored" from your perspective. Note that the same is true when you load from config, so don't do this:
```
<add key="pathToFile" value="C:\\myDirectory\\myFile.txt"/>
```
If you do, you end up with double strings, as ".NET" is smart enough to escape thins for you when you load them in this manner. |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | It is used for two things:
* create "verbatim" strings (ignores the escape character): `string path = @"C:\Windows"`
* escape language keywords to use them as identifiers: `string @class = "foo"`
In your case you need to do this:
```
String location = args[0] + id + @"\\";
``` | The @ symbol goes right before the quotes. It only works on string literals, and it simply changes the way the string is understood by the compiler. The main thing it does is cause `\` to be interpreted as a literal backslash, rather than escaping the next character. So you want:
```
String location = args[0] + id + @"\\";
``` |
6,413,842 | >
> **Possible Duplicate:**
>
> [What's the @ in front of a string for .NET?](https://stackoverflow.com/questions/556133/whats-the-in-front-of-a-string-for-net)
>
>
>
I understand using the `@` symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
`String location = @"\\192.168.2.10\datastore\\" + id + "\\";`
The above works fine but now I would like to get a string from the command line so I have done this:
`String location = @args[0] + id + "\\";`
The above doesn't work and it seems my slashes aren't ignored. This my command:
`MyProgram.exe "\\192.168.2.10\datastore\\"`
How can I get the effect of the `@` symbol back? | 2011/06/20 | [
"https://Stackoverflow.com/questions/6413842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51649/"
] | The **@** symbol in front of a string literal tells the compiler to ignore and escape sequences in the string (ie things that begin with a slash) and just to create the string "as-is"
It can also be used to create variables whose name is a reserved work. For example:
```
int @class=10;
```
If you don't prefix the @ then you'd get a compile-time error.
You can also prefix it to variables that are not reserved word:
```
int @foo=22;
```
Note that you can refer to the variable as **foo** or **@foo** in your code. | The @ symbol is only relevant for string literals in code. Variables should never modify the contents of a string. |
6,625,598 | My iPhone app badly leaks when flipping back and forth between a main uiviewcontroller and a help uiviewcontroller .
Here is the source of the main view, followed by source of the help view.
MAIN VIEW - FLIP TO HELP.....................
```
// Changes from operational view to Help view.
- (IBAction)showHelp:(id)sender
{
// End trial mode:
self.stop_trial_if_started;
self.rename_trial_if_edited;
// Switch to trial help:
help_view_context = 0;
HelpView *controller = [[HelpView alloc] initWithNibName:@"HelpView" bundle:nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
```
HELP VIEW - INIT.............................
```
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
help_scroll.editable = FALSE;
return;
}
```
HELP - RETURN TO MAIN VIEW.........................
```
// User clicked the button to return to operational view:
- (IBAction)done:(id)sender {
NSLog(@"help- done");
if( help_view_context == 0 ) {
[self.delegate trial_help_DidFinish:self];
}else{
[self.delegate file_help_DidFinish:self];
}
}
```
MAIN VIEW - RETURN FROM HELP...............................
```
// Inits operational view when user changes from Help view back to operational view.
- (void)trial_help_DidFinish:(HelpView *)controller {
NSLog(@"trial_help_DidFinish");
[self dismissModalViewControllerAnimated:YES];
self.init_trial_operation;
}
``` | 2011/07/08 | [
"https://Stackoverflow.com/questions/6625598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/746100/"
] | You are creating a controller with ref count of 1 and a local reference each time `showHelp:` is called:
```
HelpView *controller = [[HelpView alloc] initWithNibName:@"HelpView" bundle:nil];
```
you are losing your reference to it at the end of this method.
You happen to have references to it in `done:` (self) and `*_help_didFinish` (controller), but you never release it in either of those locations. Dismissing the controller is fine, but you also have to `release` it.
(Another option would be to never create a second one, and maintain an iVar to the original.) | You could well be leaking on this line
```
controller.delegate = self;
```
What is your property declaration for the delegate. If it's anything other than assign, then you either need to change it (*preferred option*) or make sure you are releasing it in the `dealloc` method of `HelpView` controller. |
69,474,555 | ---
**Thanks everyone, especially Mr.Drew Reese. If you are newbie as me, see his [answer](https://stackoverflow.com/a/69474833/14745811).**
---
I don't know why but when I console log state **data** if I use **useEffect**, it always rerender although state **generalInfo** not change :/ so someone can help me to fix it and explain my wrong?
I want the result which is the **data** will be updated when **generalInfo** changes.
Thanks so much!
This is my **useEffect**
======================== **Problem** in here:
```
const {onGetGeneralInfo, generalInfo} = props;
const [data, setData] = useState(generalInfo);
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo);
}, [generalInfo]);
```
======================== **fix:**
```
useEffect(() => {
onGetGeneralInfo();
}, []);
useEffect(() => {
setData(generalInfo);
}, [generalInfo, setData]);
```
this is **mapStateToProps**
```
const mapStateToProps = state => {
const {general} = state;
return {
generalInfo: general.generalInfo,
};
};
```
this is **mapDispatchToProps**
```
const mapDispatchToProps = dispatch => {
return {
onGetGeneralInfo: bindActionCreators(getGeneralInfo, dispatch),
};
};
```
this is **reducer**
```
case GET_GENERAL_INFO_SUCCESS: {
const {payload} = action;
return {
...state,
generalInfo: payload,
};
}
```
this is **action**
```
export function getGeneralInfo(data) {
return {
type: GET_GENERAL_INFO,
payload: data,
};
}
export function getGeneralInfoSuccess(data) {
return {
type: GET_GENERAL_INFO_SUCCESS,
payload: data,
};
}
export function getGeneralInfoFail(data) {
return {
type: GET_GENERAL_INFO_FAIL,
payload: data,
};
}
```
and this is **saga**
```
export function* getGeneralInfoSaga() {
try {
const tokenKey = yield AsyncStorage.getItem('tokenKey');
const userId = yield AsyncStorage.getItem('userId');
const params = {
method: 'GET',
headers: {
Authorization: `Bearer ${tokenKey}`,
},
};
const response = yield call(
fetch,
`${API_GET_GENERAL_INFO}?id=${userId}`,
params,
);
const body = yield call([response, response.json]);
if (response.status === 200) {
yield put(getGeneralInfoSuccess(body));
} else {
yield put(getGeneralInfoFail());
throw new Error(response);
}
} catch (error) {
yield put(getGeneralInfoFail());
console.log(error);
}
}
``` | 2021/10/07 | [
"https://Stackoverflow.com/questions/69474555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14745811/"
] | in your `useEfect` you are setting `generalInfo` and it causes change in the dependency array of `useEffect`. So, it runs over and over:
```
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo);
}, [generalInfo]);
```
try this instead:
```
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo); // or try to remove it if it is unnecessary based on below question.
}, []);
```
However, I don't understand why you have used `setData(generalInfo);` in `useEffect` when you have set it before. does it change in `onGetGeneralInfo();` function? | Yow hook has or uses things that are not listed in the dependencies list
```
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo);
}, [ onGetGeneralInfo, setData, generalInfo]);
```
Also let's remember that useEffect is call before the component mounts and after it mounts, so if you add a log it will be printed |
69,474,555 | ---
**Thanks everyone, especially Mr.Drew Reese. If you are newbie as me, see his [answer](https://stackoverflow.com/a/69474833/14745811).**
---
I don't know why but when I console log state **data** if I use **useEffect**, it always rerender although state **generalInfo** not change :/ so someone can help me to fix it and explain my wrong?
I want the result which is the **data** will be updated when **generalInfo** changes.
Thanks so much!
This is my **useEffect**
======================== **Problem** in here:
```
const {onGetGeneralInfo, generalInfo} = props;
const [data, setData] = useState(generalInfo);
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo);
}, [generalInfo]);
```
======================== **fix:**
```
useEffect(() => {
onGetGeneralInfo();
}, []);
useEffect(() => {
setData(generalInfo);
}, [generalInfo, setData]);
```
this is **mapStateToProps**
```
const mapStateToProps = state => {
const {general} = state;
return {
generalInfo: general.generalInfo,
};
};
```
this is **mapDispatchToProps**
```
const mapDispatchToProps = dispatch => {
return {
onGetGeneralInfo: bindActionCreators(getGeneralInfo, dispatch),
};
};
```
this is **reducer**
```
case GET_GENERAL_INFO_SUCCESS: {
const {payload} = action;
return {
...state,
generalInfo: payload,
};
}
```
this is **action**
```
export function getGeneralInfo(data) {
return {
type: GET_GENERAL_INFO,
payload: data,
};
}
export function getGeneralInfoSuccess(data) {
return {
type: GET_GENERAL_INFO_SUCCESS,
payload: data,
};
}
export function getGeneralInfoFail(data) {
return {
type: GET_GENERAL_INFO_FAIL,
payload: data,
};
}
```
and this is **saga**
```
export function* getGeneralInfoSaga() {
try {
const tokenKey = yield AsyncStorage.getItem('tokenKey');
const userId = yield AsyncStorage.getItem('userId');
const params = {
method: 'GET',
headers: {
Authorization: `Bearer ${tokenKey}`,
},
};
const response = yield call(
fetch,
`${API_GET_GENERAL_INFO}?id=${userId}`,
params,
);
const body = yield call([response, response.json]);
if (response.status === 200) {
yield put(getGeneralInfoSuccess(body));
} else {
yield put(getGeneralInfoFail());
throw new Error(response);
}
} catch (error) {
yield put(getGeneralInfoFail());
console.log(error);
}
}
``` | 2021/10/07 | [
"https://Stackoverflow.com/questions/69474555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14745811/"
] | >
> the initial state in redux and state in component is an empty array.
> so I want to GET data from API. and I push it to redux's state. then I
> useState it. I want to use useEffect because I want to update state
> when I PUT the data and update local state after update.
>
>
>
Ok, so I've gathered that you want fetch the data when the component mounts, and then store the fetched data into local state when it is populated. For this you will want to separate out the concerns into individual effect hooks. One to dispatch the data fetch once when the component mounts, the other to "listen" for changes to the redux state to update the local state. *Note that it is generally considered anti-pattern to store passed props in local state.*
```
const {onGetGeneralInfo, generalInfo} = props;
const [data, setData] = useState(generalInfo);
// fetch data on mount
useEffect(() => {
onGetGeneralInfo();
}, []);
// Update local state when `generalInfo` updates.
useEffect(() => {
setData(generalInfo);
}, [generalInfo, setData]);
``` | in your `useEfect` you are setting `generalInfo` and it causes change in the dependency array of `useEffect`. So, it runs over and over:
```
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo);
}, [generalInfo]);
```
try this instead:
```
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo); // or try to remove it if it is unnecessary based on below question.
}, []);
```
However, I don't understand why you have used `setData(generalInfo);` in `useEffect` when you have set it before. does it change in `onGetGeneralInfo();` function? |
69,474,555 | ---
**Thanks everyone, especially Mr.Drew Reese. If you are newbie as me, see his [answer](https://stackoverflow.com/a/69474833/14745811).**
---
I don't know why but when I console log state **data** if I use **useEffect**, it always rerender although state **generalInfo** not change :/ so someone can help me to fix it and explain my wrong?
I want the result which is the **data** will be updated when **generalInfo** changes.
Thanks so much!
This is my **useEffect**
======================== **Problem** in here:
```
const {onGetGeneralInfo, generalInfo} = props;
const [data, setData] = useState(generalInfo);
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo);
}, [generalInfo]);
```
======================== **fix:**
```
useEffect(() => {
onGetGeneralInfo();
}, []);
useEffect(() => {
setData(generalInfo);
}, [generalInfo, setData]);
```
this is **mapStateToProps**
```
const mapStateToProps = state => {
const {general} = state;
return {
generalInfo: general.generalInfo,
};
};
```
this is **mapDispatchToProps**
```
const mapDispatchToProps = dispatch => {
return {
onGetGeneralInfo: bindActionCreators(getGeneralInfo, dispatch),
};
};
```
this is **reducer**
```
case GET_GENERAL_INFO_SUCCESS: {
const {payload} = action;
return {
...state,
generalInfo: payload,
};
}
```
this is **action**
```
export function getGeneralInfo(data) {
return {
type: GET_GENERAL_INFO,
payload: data,
};
}
export function getGeneralInfoSuccess(data) {
return {
type: GET_GENERAL_INFO_SUCCESS,
payload: data,
};
}
export function getGeneralInfoFail(data) {
return {
type: GET_GENERAL_INFO_FAIL,
payload: data,
};
}
```
and this is **saga**
```
export function* getGeneralInfoSaga() {
try {
const tokenKey = yield AsyncStorage.getItem('tokenKey');
const userId = yield AsyncStorage.getItem('userId');
const params = {
method: 'GET',
headers: {
Authorization: `Bearer ${tokenKey}`,
},
};
const response = yield call(
fetch,
`${API_GET_GENERAL_INFO}?id=${userId}`,
params,
);
const body = yield call([response, response.json]);
if (response.status === 200) {
yield put(getGeneralInfoSuccess(body));
} else {
yield put(getGeneralInfoFail());
throw new Error(response);
}
} catch (error) {
yield put(getGeneralInfoFail());
console.log(error);
}
}
``` | 2021/10/07 | [
"https://Stackoverflow.com/questions/69474555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14745811/"
] | >
> the initial state in redux and state in component is an empty array.
> so I want to GET data from API. and I push it to redux's state. then I
> useState it. I want to use useEffect because I want to update state
> when I PUT the data and update local state after update.
>
>
>
Ok, so I've gathered that you want fetch the data when the component mounts, and then store the fetched data into local state when it is populated. For this you will want to separate out the concerns into individual effect hooks. One to dispatch the data fetch once when the component mounts, the other to "listen" for changes to the redux state to update the local state. *Note that it is generally considered anti-pattern to store passed props in local state.*
```
const {onGetGeneralInfo, generalInfo} = props;
const [data, setData] = useState(generalInfo);
// fetch data on mount
useEffect(() => {
onGetGeneralInfo();
}, []);
// Update local state when `generalInfo` updates.
useEffect(() => {
setData(generalInfo);
}, [generalInfo, setData]);
``` | Yow hook has or uses things that are not listed in the dependencies list
```
useEffect(() => {
onGetGeneralInfo();
setData(generalInfo);
}, [ onGetGeneralInfo, setData, generalInfo]);
```
Also let's remember that useEffect is call before the component mounts and after it mounts, so if you add a log it will be printed |
53,497,455 | I have default laravel `users` table and my custom `educations` table in my database. In `educations` table users can save education histories.
Example `educations` data:
```
------------------------------------------------------------
id | user_id | university | speciality | finish_year | level
------------------------------------------------------------
1 | 16 | Boston | Developer | 2018 | 4
------------------------------------------------------------
2 | 10 | Sinergy | Designer | 2014 | 4
------------------------------------------------------------
9 | 16 | Sinergy | Economist | 2010 | 8
------------------------------------------------------------
```
Now how I can get users using laravel eloquent by education level?
For example get users where education level == 4 | 2018/11/27 | [
"https://Stackoverflow.com/questions/53497455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7496039/"
] | Considering that you have a `educations` method in your User model that represents a `HasMany` association, you can use eloquent's `has` (or `whereHas`) method:
```
$users = App\User::whereHas('educations', function ($query) {
$query->where('level', 4);
})->get();
```
Here's a link to the [docs](https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence). | If you have the relationship setup correctly, so in your `User` model you should have something like this:
```
public function educations() {
return $this->hasMany(Education::class);
}
```
Then a simple use will be the following:
```
User::with(['educations' => function($query) {
$query->where('level', 4);
}])->get()->filter(function($user) {
return $user->educations->count() > 0;
});
```
The opposite approach would be:
```
Education::with('user')->where('level', 4)->get();
```
This will give you list of educations where the level is 4, and for each the user assigned to it. |
5,059,506 | I am trying to clean up some of my projects, and one of the things that are puzzling me is how to deal with header files in static libraries that I have added as "project dependencies" (by adding the project file itself). The basic structure is like this:
```
MyProject.xcodeproj
Contrib
thirdPartyLibrary.xcodeproj
Classes
MyClass1.h
MyClass1.m
...
```
Now, the dependencies are all set up and built correctly, but how can I specify the public headers for "thirdPartyLibrary.xcodeproj" so that they are on the search path when building MyProject.xcodeproj. Right now, I have hard-coded the include directory in the thirdPartyLibrary.xcodeproj, but obviously this is clumsy and non-portable. I assume that, since the headers are public and already built to some temporary location in ~/Library (where the .a file goes as well), there is a neat way to reference this directory. Only.. how? An hour of Googling turned up blank, so any help is greatly appreciated! | 2011/02/20 | [
"https://Stackoverflow.com/questions/5059506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292477/"
] | If I understand correctly, I believe you want to add a path containing $(BUILT\_PRODUCTS\_DIR) to the HEADER\_SEARCH\_PATHS in your projects build settings.
As an example, I took an existing iOS project which contains a static library, which is included just in the way you describe, and set the libraries header files to public. I also noted that the PUBLIC\_HEADERS\_FOLDER\_PATH for this project was set to "/usr/local/include" and these files are copied to $(BUILT\_PRODUCTS\_DIR)/usr/local/include when the parent project builds the dependent project. So, the solution was to add $(BUILT\_PRODUCTS\_DIR)/usr/local/include to HEADER\_SEARCH\_PATHS in my project's build settings.
```
HEADER_SEARCH_PATHS = $(BUILT_PRODUCTS_DIR)/usr/local/include
```
Your situation may be slightly different but the exact path your looking for can probably be found in [Xcode's build settings](http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/0-Introduction/introduction.html). Also you may find it helpful to add a Run Script build phase to your target and note the values of various settings at build time with something like:
```
echo "BUILT_PRODUCTS_DIR " $BUILT_PRODUCTS_DIR
echo "HEADER_SEARCH_PATHS " $HEADER_SEARCH_PATHS
echo "PUBLIC_HEADERS_FOLDER_PATH " $PUBLIC_HEADERS_FOLDER_PATH
.
.
.
etc.
``` | I think that your solution is sufficient and a generally accepted one. One alternative would be to have all header files located under an umbrella directory that can describe the interface to using the depended-on libraries and put that in your include path. I see this as being similar to /usr/include. Another alternative that I have never personally tried, but I think would work would be to create references to all the headers of *thirdPartyLibrary* from *MyProject* so that they appear to be members of the *MyProject*. You would do this by dragging them from some location into *MyProject*, and then deselecting the checkbox that says to copy them into the project's top level directory. From one perspective this seems feasible to me because it is as if you are explicitly declaring that your project depends on those specific classes, but it is not directly responsible for compiling them.
One of the things to be wary of when addressing this issue is depending on implementation-specific details of Xcode for locating libraries automatically. Doing so may seem innocuous in the meantime but the workflows that it uses to build projects are subject to change with updates and could potentially break your project in subtle and confusing ways. If they are not well-defined in some documentation, I would take any effect as being coincidental and not worth leveraging in your project when you can enforce the desired behavior by some other means. In the end, you may have to define a convention that you follow or find one that you adopt from someone else. By doing so, you can rest assured that if your solution is documented and reproducible, any developer (including yourself in the future) can pick it up and proceed without tripping over it, and that it will stand the testament of time. |
5,059,506 | I am trying to clean up some of my projects, and one of the things that are puzzling me is how to deal with header files in static libraries that I have added as "project dependencies" (by adding the project file itself). The basic structure is like this:
```
MyProject.xcodeproj
Contrib
thirdPartyLibrary.xcodeproj
Classes
MyClass1.h
MyClass1.m
...
```
Now, the dependencies are all set up and built correctly, but how can I specify the public headers for "thirdPartyLibrary.xcodeproj" so that they are on the search path when building MyProject.xcodeproj. Right now, I have hard-coded the include directory in the thirdPartyLibrary.xcodeproj, but obviously this is clumsy and non-portable. I assume that, since the headers are public and already built to some temporary location in ~/Library (where the .a file goes as well), there is a neat way to reference this directory. Only.. how? An hour of Googling turned up blank, so any help is greatly appreciated! | 2011/02/20 | [
"https://Stackoverflow.com/questions/5059506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292477/"
] | I think that your solution is sufficient and a generally accepted one. One alternative would be to have all header files located under an umbrella directory that can describe the interface to using the depended-on libraries and put that in your include path. I see this as being similar to /usr/include. Another alternative that I have never personally tried, but I think would work would be to create references to all the headers of *thirdPartyLibrary* from *MyProject* so that they appear to be members of the *MyProject*. You would do this by dragging them from some location into *MyProject*, and then deselecting the checkbox that says to copy them into the project's top level directory. From one perspective this seems feasible to me because it is as if you are explicitly declaring that your project depends on those specific classes, but it is not directly responsible for compiling them.
One of the things to be wary of when addressing this issue is depending on implementation-specific details of Xcode for locating libraries automatically. Doing so may seem innocuous in the meantime but the workflows that it uses to build projects are subject to change with updates and could potentially break your project in subtle and confusing ways. If they are not well-defined in some documentation, I would take any effect as being coincidental and not worth leveraging in your project when you can enforce the desired behavior by some other means. In the end, you may have to define a convention that you follow or find one that you adopt from someone else. By doing so, you can rest assured that if your solution is documented and reproducible, any developer (including yourself in the future) can pick it up and proceed without tripping over it, and that it will stand the testament of time. | The way we do it is to go into build target settings for the main project and add:
```
User Header Search Path = "Contrib"
```
and check that it searches recursively. We don't see performance problems with searching recursively even with many (10-15 in some projects) dependencies. |
5,059,506 | I am trying to clean up some of my projects, and one of the things that are puzzling me is how to deal with header files in static libraries that I have added as "project dependencies" (by adding the project file itself). The basic structure is like this:
```
MyProject.xcodeproj
Contrib
thirdPartyLibrary.xcodeproj
Classes
MyClass1.h
MyClass1.m
...
```
Now, the dependencies are all set up and built correctly, but how can I specify the public headers for "thirdPartyLibrary.xcodeproj" so that they are on the search path when building MyProject.xcodeproj. Right now, I have hard-coded the include directory in the thirdPartyLibrary.xcodeproj, but obviously this is clumsy and non-portable. I assume that, since the headers are public and already built to some temporary location in ~/Library (where the .a file goes as well), there is a neat way to reference this directory. Only.. how? An hour of Googling turned up blank, so any help is greatly appreciated! | 2011/02/20 | [
"https://Stackoverflow.com/questions/5059506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292477/"
] | If I understand correctly, I believe you want to add a path containing $(BUILT\_PRODUCTS\_DIR) to the HEADER\_SEARCH\_PATHS in your projects build settings.
As an example, I took an existing iOS project which contains a static library, which is included just in the way you describe, and set the libraries header files to public. I also noted that the PUBLIC\_HEADERS\_FOLDER\_PATH for this project was set to "/usr/local/include" and these files are copied to $(BUILT\_PRODUCTS\_DIR)/usr/local/include when the parent project builds the dependent project. So, the solution was to add $(BUILT\_PRODUCTS\_DIR)/usr/local/include to HEADER\_SEARCH\_PATHS in my project's build settings.
```
HEADER_SEARCH_PATHS = $(BUILT_PRODUCTS_DIR)/usr/local/include
```
Your situation may be slightly different but the exact path your looking for can probably be found in [Xcode's build settings](http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/0-Introduction/introduction.html). Also you may find it helpful to add a Run Script build phase to your target and note the values of various settings at build time with something like:
```
echo "BUILT_PRODUCTS_DIR " $BUILT_PRODUCTS_DIR
echo "HEADER_SEARCH_PATHS " $HEADER_SEARCH_PATHS
echo "PUBLIC_HEADERS_FOLDER_PATH " $PUBLIC_HEADERS_FOLDER_PATH
.
.
.
etc.
``` | The way we do it is to go into build target settings for the main project and add:
```
User Header Search Path = "Contrib"
```
and check that it searches recursively. We don't see performance problems with searching recursively even with many (10-15 in some projects) dependencies. |
53,719,824 | Say I have an array of objects like so:
```
[{"taco":"","burrito":"","scone":"","beans":"true"},
{"taco":"true","burrito":"","scone":"true","beans":""},
{"taco":"true","burrito":"","scone":"","beans":""},
{"taco":"true","burrito":"","scone":"","beans":"true"}]
```
I need to count the occurrence of each element and return in it in an array
```
[3, 0, 1, 2]
```
any ideas would be appreciated, thanks!
I have attempted
```
var a = datasets.reduce(function (item, index) {
if (typeof item[index] == 'undefined') {
item[index] = 1;
} else {
item[index] += 1;
}
return item;
}, {});
```
could not get anything like that to work so i attempted converting it to json and then removing any key: value pairs with no value then counting remaining ones but have had no success with that either
```
function tableToJson(table) {
var data = [];
var headers = [];
for (var i=0; i < table[0].rows[0].cells.length; i++) {
headers[i] = table[0].rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
for (var i=1; i< table[0].rows.length; i++) {
var tableRow = table[0].rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data
}
function removeEmpty(jsonObj) {
var newObj = Object.getOwnPropertyNames(jsonObj);
for (var i = 0; i < newObj.length; i++) {
var value = newObj[i];
if (jsonObj[value] === null || jsonObj[value] === undefined) {
delete jsonObj[value];
}
}
}
``` | 2018/12/11 | [
"https://Stackoverflow.com/questions/53719824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9633658/"
] | **You can try this**
You can do it with `reduce()`.
What i have done is first i check is the **`object property of current element`** if it is already in **`output object`**. If it's present than i check the value of **`current element property`**. if it is true than i increment the property of **`output object`** by `1`.
If the **`object property of current element`** is not available in output than i check for the value of **`current element property`**. if it is true i assign output object property with value `1`. if false i assign output object property with `0`.
```js
let obj = [{"taco":"","burrito":"","scone":"","beans":"true"},
{"taco":"true","burrito":"","scone":"true","beans":""},
{"taco":"true","burrito":"","scone":"","beans":""},
{"taco":"true","burrito":"","scone":"","beans":"true"}]
let op = obj.reduce((output,current)=>{
for(let key in current){
if( output[key] ){
if( current[key] ) output[key]+=1;
} else {
if( current[key] ){
output[key] = 1;
} else{
output[key] = 0;
}
}
}
return output;
},{})
console.log(op);
``` | Try this:
```js
var data = [{
taco: "",
burrito: "",
scone: "",
beans: "true"
},
{
taco: "true",
burrito: "",
scone: "true",
beans: ""
},
{
taco: "",
burrito, "true",
scone: "",
beans: "",
}, {
taco: "true",
burrito: "",
scone: "",
beans: "true"
}]
var total = [0, 0, 0, 0];
data.forEach(function(obj) {
if (obj.taco) {
total[0]++;
}
if (burrito) {
total[1]++;
}
if (obj.scone) {
total[2]++;
}
if (obj.beans) {
total[3]++;
}
})
console.log(total)
``` |
53,719,824 | Say I have an array of objects like so:
```
[{"taco":"","burrito":"","scone":"","beans":"true"},
{"taco":"true","burrito":"","scone":"true","beans":""},
{"taco":"true","burrito":"","scone":"","beans":""},
{"taco":"true","burrito":"","scone":"","beans":"true"}]
```
I need to count the occurrence of each element and return in it in an array
```
[3, 0, 1, 2]
```
any ideas would be appreciated, thanks!
I have attempted
```
var a = datasets.reduce(function (item, index) {
if (typeof item[index] == 'undefined') {
item[index] = 1;
} else {
item[index] += 1;
}
return item;
}, {});
```
could not get anything like that to work so i attempted converting it to json and then removing any key: value pairs with no value then counting remaining ones but have had no success with that either
```
function tableToJson(table) {
var data = [];
var headers = [];
for (var i=0; i < table[0].rows[0].cells.length; i++) {
headers[i] = table[0].rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
for (var i=1; i< table[0].rows.length; i++) {
var tableRow = table[0].rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data
}
function removeEmpty(jsonObj) {
var newObj = Object.getOwnPropertyNames(jsonObj);
for (var i = 0; i < newObj.length; i++) {
var value = newObj[i];
if (jsonObj[value] === null || jsonObj[value] === undefined) {
delete jsonObj[value];
}
}
}
``` | 2018/12/11 | [
"https://Stackoverflow.com/questions/53719824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9633658/"
] | **You can try this**
You can do it with `reduce()`.
What i have done is first i check is the **`object property of current element`** if it is already in **`output object`**. If it's present than i check the value of **`current element property`**. if it is true than i increment the property of **`output object`** by `1`.
If the **`object property of current element`** is not available in output than i check for the value of **`current element property`**. if it is true i assign output object property with value `1`. if false i assign output object property with `0`.
```js
let obj = [{"taco":"","burrito":"","scone":"","beans":"true"},
{"taco":"true","burrito":"","scone":"true","beans":""},
{"taco":"true","burrito":"","scone":"","beans":""},
{"taco":"true","burrito":"","scone":"","beans":"true"}]
let op = obj.reduce((output,current)=>{
for(let key in current){
if( output[key] ){
if( current[key] ) output[key]+=1;
} else {
if( current[key] ){
output[key] = 1;
} else{
output[key] = 0;
}
}
}
return output;
},{})
console.log(op);
``` | You can loop through the array and then loop through the keys of each object. Then increment the `key` of the `countObject` if it already exists or assign it zero.
This is dynamic. Even if one of the object has an extra `key`, it will count them. This doesn't expect all the items of array to have the same keys.
```js
var array = [
{"taco":"","burrito":"","scone":"","beans":"true"},
{"taco":"true","burrito":"","scone":"true","beans":""},
{"taco":"true","burrito":"","scone":"","beans":""},
{"taco":"true","burrito":"","scone":"","beans":"true"}
]
var countObject = {};
array.forEach(item => {
Object.keys(item).forEach(key => {
if (item[key] === "true")
countObject[key] = countObject[key] + 1 || 1
else
countObject[key] = countObject[key] || 0
})
})
console.log(countObject); // get the key and count pair
console.log(Object.values(countObject)); // get the counts in an array
``` |
23,241 | I'm sure there will be variation depending on what the contaminated item or surface is made of - linens, I could imagine, would remain dangerous for longer than a door-knob. But if the items are not decontaminated in some way, how long can the virus survive outside a host? | 2014/10/17 | [
"https://biology.stackexchange.com/questions/23241",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/9817/"
] | This really depends on the environment, one study (listed below as reference 1) found that the Ebola virus can survive under ideal conditions on flat surfaces in the dark for up to six days - see the figure from the same publication.

However, the virus is quite sensitive to UV radiation (see reference 2 for all the details) and most viral particles are likely to get inactivated within relatively short time. It might still be possible to get positive tests for Ebola from really sensitive PCR-based tests, but these are most likely not infectious anymore. The CDC lists common bleach (or any other routinely used disinfected) as a good way to get rid of Ebola viruses.
References:
1. [Persistence in darkness of virulent alphaviruses, Ebola virus, and
Lassa virus deposited on solid surfaces](http://link.springer.com/article/10.1007/s00705-010-0791-0/fulltext.html)
2. [Sensitivity to ultraviolet radiation of Lassa, vaccinia, and Ebola
viruses dried on surfaces](http://link.springer.com/article/10.1007/s00705-010-0847-1/fulltext.html) | I found this safety sheet in the topic.
>
> SECTION IV – STABILITY AND VIABILITY
>
>
> DRUG SUSCEPTIBILITY: Unknown. S-adenosylhomocysteine hydrolase
> inhibitors have been found to have complete mortality protection in
> mice infected with a lethal dose of Ebola virus (30).
>
>
> DRUG RESISTANCE: There are no known antiviral treatments available for
> human infections.
>
>
> SUSCEPTIBILITY TO DISINFECTANTS: Ebola virus is susceptible to sodium
> hypochlorite, lipid solvents, phenolic disinfectants, peracetic acid,
> methyl alcohol, ether, sodium deoxycholate, 2% glutaraldehyde, 0.25%
> Triton X-100, β-propiolactone, 3% acetic acid (pH 2.5), formaldehyde
> and paraformaldehyde, and detergents such as SDS (20, 21, 31-34).
>
>
> PHYSICAL INACTIVATION: Ebola are moderately thermolabile and can be
> inactivated by heating for 30 minutes to 60 minutes at 60ºC, boiling
> for 5 minutes, gamma irradiation (1.2 x106 rads to 1.27 x106 rads),
> and/or UV radiation (3, 6, 20, 32, 33).
>
>
> SURVIVAL OUTSIDE HOST: The virus can survive in liquid or dried
> material for a number of days (23). Infectivity is found to be stable
> at room temperature or at 4°C for several days, and indefinitely
> stable at -70°C (6, 20). Infectivity can be preserved by
> lyophilisation.
>
>
>
* 2010 - [Free Safety Data Sheet Index - Ebola virus](http://www.msdsonline.com/resources/msds-resources/free-safety-data-sheet-index/ebola-virus.aspx)
However there are no references on the site, so I checked the data provided. According to scientific articles it is trusty, however these articles are related to not the current West African strain, so it can be slightly different.
* 1982 - [Inactivation of Lassa, Marburg, and Ebola viruses by gamma irradiation.](http://jcm.asm.org/content/16/4/704.short)
>
> Clinical specimens from patients infected with Lassa, Ebola, or
> Marburg virus may present a serious biohazard to laboratory workers.
> We have examined the effects of heat, alteration of pH, and gamma
> radiation on these viruses in human blood and on the electrolytes,
> enzymes, and coagulation factors measured in laboratory tests that are
> important in the care of an infected patient. Heating serum at 60
> degrees C for 1 h reduced high titers of these viruses to
> noninfectious levels without altering the serum levels of glucose,
> blood urea nitrogen, and electrolytes. Dilution of blood in 3% acetic
> acid, diluent for a leukocyte count, inactivated all of these viruses.
> All of the methods tested for viral inactivation markedly altered
> certain serum proteins, making these methods unsuitable for samples
> that are to be tested for certain enzyme levels and coagulation
> factors.
>
>
>
* 1984 - [Physicochemical inactivation of Lassa, Ebola, and Marburg viruses and effect on clinical laboratory analyses.](http://jcm.asm.org/content/20/3/486.short)
>
> Ebola, Lassa, Venezuelan equine encephalitis, and Sindbis viruses were
> dried onto solid surfaces, incubated for various time periods under
> controlled conditions of temperature and relative humidity, and
> quantitatively eluted from surfaces, and viral titers in the recovered
> samples were determined. The viral inactivation kinetics that were
> obtained indicated that viral resistance to natural inactivation in
> the dark follows (in decreasing order of stability) alphavirus > Lassa
> virus > Ebola virus. The findings reported in this study on the
> natural decay in the dark should assist in understanding the
> biophysical properties of enveloped RNA viruses outside the host and
> in estimating the persistence of viruses in the environment during
> epidemics or after an accidental or intentional release.
>
>
>
* 2010 - [Persistence in darkness of virulent alphaviruses, Ebola virus, and Lassa virus deposited on solid surfaces](http://link.springer.com/article/10.1007/s00705-010-0791-0/fulltext.html)
>
> Our study has shown that Lake Victoria marburgvirus (MARV) and Zaire
> ebolavirus (ZEBOV) can survive for long periods in different liquid
> media and can also be recovered from plastic and glass surfaces at low
> temperatures for over 3 weeks. The decay rates of ZEBOV and Reston
> ebolavirus (REBOV) plus MARV within a dynamic aerosol were calculated.
> ZEBOV and MARV had similar decay rates, whilst REBOV showed
> significantly better survival within an aerosol.
>
>
>
* 2010 - [The survival of filoviruses in liquids, on solid substrates and in a dynamic aerosol](http://onlinelibrary.wiley.com/doi/10.1111/j.1365-2672.2010.04778.x/abstract) |
42,232,606 | I'm using Django 1.10 and trying to catch all exceptions with exception middleware.
The code below causes an internal server error:
```
mw_instance = middleware(handler)
TypeError: object() takes no parameters
```
views.py
```
from django.http import HttpResponse
def my_view(request):
x = 1/0 # cause an exception
return HttpResponse("ok")
```
settings.py
```
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'myproject.middleware.ExceptionMiddleware',
]
```
middleware.py
```
from django.http import HttpResponse
class ExceptionMiddleware(object):
def process_exception(self, request, exception):
return HttpResponse("in exception")
```
I have seen these [object() takes no parameters in django 1.10](https://stackoverflow.com/questions/39457381/object-takes-no-parameters-in-django-1-10) and other questions talking about middleware versus middleware\_classes, but I'm not sure how that applies to this case, or what I'd actually need to change to fix the issue. | 2017/02/14 | [
"https://Stackoverflow.com/questions/42232606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/984003/"
] | Since you are using the new `MIDDLEWARE` settings, your Middleware class must accept a `get_response` argument: <https://docs.djangoproject.com/en/1.10/topics/http/middleware/#writing-your-own-middleware>
You could write your class like this:
```
from django.http import HttpResponse
class ExceptionMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_exception(self, request, exception):
return HttpResponse("in exception")
```
You could also use the `MiddlewareMixin` to make your Middleware compatible with pre-1.10 and post-1.10 Django versions: <https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware>
```
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class ExceptionMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
return HttpResponse("in exception")
``` | in the newer version of Django, the middleware should be written like this
```
import datetime
from django.core.cache import cache
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class ActiveUserMiddleware(MiddlewareMixin):
def process_request(self, request):
current_user = request.user
if request.user.is_authenticated:
now = datetime.datetime.now()
cache.set('seen_%s' % (current_user.username), now,
settings.USER_LASTSEEN_TIMEOUT)
``` |
59,278,991 | Alright I'm trying to allow user input to include only letters, numbers, and dashes. Any other characters would be invalid. I also only want the characters to be 1-9 characters in length.
Here is what I have so far:
```
def main():
tag = input("Please enter your ID Tag: ")
while(not rSeriesValidate(tag)):
print("INVALID ID: Try again")
tag = input("Please reenter your ID Tag: ")
print("VALID ID. Move along, move along.")
def rSeriesValidate(tag):
isValid = True
if(len(tag)<1 or len(tag)> 9):
isValid = False
elif(not tag.isalnum()):
isValid = False
return isValid
main()
```
With this I am able to make sure the worker inputs letters between 1-9 and that they are letters or numbers. However I can't figure out how to also allow dashes "-" to be inputted. Any suggestions?
Thank you | 2019/12/11 | [
"https://Stackoverflow.com/questions/59278991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you don't want to use regular expressions, try simply going character by character:
```
def rSeriesValidate(tag):
if len(tag) < 1 or len(tag) > 9:
return False
for currChar in tag:
if not currChar.isalnum() and currChar != "-":
return False
return True
```
This first checks for the input length requirement, and returns False if it is not met. For input of suitable length, it goes on to check each character of the input. If it finds a disallowed character (one that is not alphanumeric and not a dash), it returns False. | Use `regex` to solve your problem. Example below:
```
import re
#pattern to search for any character other then [- A-Z a-z 0-9]
pattern = r'[^\-A-Za-z0-9]'
def check_str(sample_str):
if re.search(pattern, sample_str):
#Character other then [- A-Z a-z 0-9] was found
print('Invalid : {}'.format(sample_str))
else:
#Character other then [- A-Z a-z 0-9] was not found
print('Valid : {}'.format(sample_str))
check_str('AB-12')
check_str('AB-12#')
check_str('_-/>"!@#AB-12<')
#output
>>Valid : AB-12
>>Invalid : AB-12#
>>Invalid : _-/>"!@#AB-12<
``` |
59,278,991 | Alright I'm trying to allow user input to include only letters, numbers, and dashes. Any other characters would be invalid. I also only want the characters to be 1-9 characters in length.
Here is what I have so far:
```
def main():
tag = input("Please enter your ID Tag: ")
while(not rSeriesValidate(tag)):
print("INVALID ID: Try again")
tag = input("Please reenter your ID Tag: ")
print("VALID ID. Move along, move along.")
def rSeriesValidate(tag):
isValid = True
if(len(tag)<1 or len(tag)> 9):
isValid = False
elif(not tag.isalnum()):
isValid = False
return isValid
main()
```
With this I am able to make sure the worker inputs letters between 1-9 and that they are letters or numbers. However I can't figure out how to also allow dashes "-" to be inputted. Any suggestions?
Thank you | 2019/12/11 | [
"https://Stackoverflow.com/questions/59278991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you don't want to use regular expressions, try simply going character by character:
```
def rSeriesValidate(tag):
if len(tag) < 1 or len(tag) > 9:
return False
for currChar in tag:
if not currChar.isalnum() and currChar != "-":
return False
return True
```
This first checks for the input length requirement, and returns False if it is not met. For input of suitable length, it goes on to check each character of the input. If it finds a disallowed character (one that is not alphanumeric and not a dash), it returns False. | There are several ways to tackle this problem:
Check each character in the tag:
```
def rSeriesValidate(tag):
return 1 <= len(tag) <= 9 and all(ch.isalnum() or ch=='-' for ch in tag)
```
Split the tag on '-' and test each part with `isalnum()`:
```
def rSeriesValidate(tag):
return 1 <= len(tag) <= 9 and all(part.isalnum() for part in tag.split('-'))
```
Use a regex as suggested by @SubhrajyotiDas |
5,485,338 | What version of Eclipse do I need for Google Web Toolkit? I see about 7 versions, but none make any references to GWT. Google doesn't mention it to. I did install the PHP version. | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340761/"
] | Since GWT means Java programming I would recommend the Java (default) Version of Eclipse or Java EE Version because they contain the Java Development Tools which will help you very when coding in Java | I suppose you should install JavaEE version.. Because GWT produce a war file, and it should be deployed to a web application server. |
5,485,338 | What version of Eclipse do I need for Google Web Toolkit? I see about 7 versions, but none make any references to GWT. Google doesn't mention it to. I did install the PHP version. | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340761/"
] | Definitely the Java EE version. The regular java version doesn't seem to work with the google plugin. | Since GWT means Java programming I would recommend the Java (default) Version of Eclipse or Java EE Version because they contain the Java Development Tools which will help you very when coding in Java |
5,485,338 | What version of Eclipse do I need for Google Web Toolkit? I see about 7 versions, but none make any references to GWT. Google doesn't mention it to. I did install the PHP version. | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340761/"
] | Well I download the Eclipse for Java EE:
<http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliossr2>
But one which is great is Spring STS (based on eclipse). You can choose to install GWT at the beginning.
<http://www.springsource.com/downloads/sts> | I suppose you should install JavaEE version.. Because GWT produce a war file, and it should be deployed to a web application server. |
5,485,338 | What version of Eclipse do I need for Google Web Toolkit? I see about 7 versions, but none make any references to GWT. Google doesn't mention it to. I did install the PHP version. | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340761/"
] | Definitely the Java EE version. The regular java version doesn't seem to work with the google plugin. | I suppose you should install JavaEE version.. Because GWT produce a war file, and it should be deployed to a web application server. |
5,485,338 | What version of Eclipse do I need for Google Web Toolkit? I see about 7 versions, but none make any references to GWT. Google doesn't mention it to. I did install the PHP version. | 2011/03/30 | [
"https://Stackoverflow.com/questions/5485338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340761/"
] | Definitely the Java EE version. The regular java version doesn't seem to work with the google plugin. | Well I download the Eclipse for Java EE:
<http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/heliossr2>
But one which is great is Spring STS (based on eclipse). You can choose to install GWT at the beginning.
<http://www.springsource.com/downloads/sts> |
1,441,063 | I have some code like:
```
Lookup(Of String)("Testing")
Lookup(Of Integer)("Testing")
```
And both of those Lookups work great. What I'm trying to is call the appropriate LookUp based on the type of another variable. Something that would look like...
```
Lookup(Of GetType(MyStringVariable))("Testing")
```
I've tried to Google this but I'm having a hard time coming up with an appropriate search. Can anyone tell me how to do what I want? | 2009/09/17 | [
"https://Stackoverflow.com/questions/1441063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73381/"
] | You do not specify the full signature for the method that you're calling, but my psychic powers tell me that it is this:
```
Function Lookup(Of T)(key As String) As T
```
And you want to avoid having to repeat `Integer` twice as in the example below:
```
Dim x As Integer
x = Lookup(Of Integer)("foo");
```
The problem is that type parameters are only deduced when they're used in argument context, but never in return value context. So, you need a helper function with a `ByRef` argument to do the trick:
```
Sub Lookup(Of T)(key As String, ByRef result As T)
T = Lookup(Of T)(key)
End Sub
```
With that, you can write:
```
Dim x As Integer
Lookup("foo", x);
``` | One solution to this is to use reflection. See this [question](https://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) for details. |
1,441,063 | I have some code like:
```
Lookup(Of String)("Testing")
Lookup(Of Integer)("Testing")
```
And both of those Lookups work great. What I'm trying to is call the appropriate LookUp based on the type of another variable. Something that would look like...
```
Lookup(Of GetType(MyStringVariable))("Testing")
```
I've tried to Google this but I'm having a hard time coming up with an appropriate search. Can anyone tell me how to do what I want? | 2009/09/17 | [
"https://Stackoverflow.com/questions/1441063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73381/"
] | You do not specify the full signature for the method that you're calling, but my psychic powers tell me that it is this:
```
Function Lookup(Of T)(key As String) As T
```
And you want to avoid having to repeat `Integer` twice as in the example below:
```
Dim x As Integer
x = Lookup(Of Integer)("foo");
```
The problem is that type parameters are only deduced when they're used in argument context, but never in return value context. So, you need a helper function with a `ByRef` argument to do the trick:
```
Sub Lookup(Of T)(key As String, ByRef result As T)
T = Lookup(Of T)(key)
End Sub
```
With that, you can write:
```
Dim x As Integer
Lookup("foo", x);
``` | The VB.NET compiler in VS2008 actually uses type-inference. That means if you are using a generic method, and one of the parameters is of the generic type, then you don't need to specify the generic type in your call.
Take the following definition...
```
Function DoSomething(Of T)(Target As T) As Boolean
```
If you call it with a strongly-typed String for **Target**, and don't specify the generic parameter, it will infer **T** as String.
If you call it with a strongly-typed Integer for **Target**, and don't specify the generic parameter, it will infer **T** as Integer.
So you could call this function as follows:
```
Dim myResult As Boolean = DoSomething("my new string")
```
And it will automatically infer the type of **T** as String.
**EDIT:**
NOTE: This works for single or multiple generic parameters.
NOTE: This works also for variables in the argument list, not just literals. |
1,441,063 | I have some code like:
```
Lookup(Of String)("Testing")
Lookup(Of Integer)("Testing")
```
And both of those Lookups work great. What I'm trying to is call the appropriate LookUp based on the type of another variable. Something that would look like...
```
Lookup(Of GetType(MyStringVariable))("Testing")
```
I've tried to Google this but I'm having a hard time coming up with an appropriate search. Can anyone tell me how to do what I want? | 2009/09/17 | [
"https://Stackoverflow.com/questions/1441063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/73381/"
] | You do not specify the full signature for the method that you're calling, but my psychic powers tell me that it is this:
```
Function Lookup(Of T)(key As String) As T
```
And you want to avoid having to repeat `Integer` twice as in the example below:
```
Dim x As Integer
x = Lookup(Of Integer)("foo");
```
The problem is that type parameters are only deduced when they're used in argument context, but never in return value context. So, you need a helper function with a `ByRef` argument to do the trick:
```
Sub Lookup(Of T)(key As String, ByRef result As T)
T = Lookup(Of T)(key)
End Sub
```
With that, you can write:
```
Dim x As Integer
Lookup("foo", x);
``` | You can't use a dynamic type unless you do runtime compiling, which of course is really inefficient.
Although generics allows you to use different types, the type still has to be known at compile time so that the compiler can generate the specific code for that type.
This is not the way to go. You should ask about what problem you are trying to solve, instead of asking about the way that you think that it should be solved. Even if it might be possible to do something close to what you are asking, it's most likely that the best solution is something completely different. |
49,649,819 | I am currently using this code to screen capture the panel I created, but whenever I am saving it, the quality is bad. Is there any way to maintain the good quality when saving it?
I tried resizing the panel but the result is still the same.
I tried doing a normal screen shot with the snipping tool and it also has the same result with the codes I use.
Any suggestions? or help?
```
private void SaveControlImage(Control theControl)
{
snapCount++;
int width = panel1.Size.Width;
int height = panel1.Size.Height;
Bitmap bm = new Bitmap(width, height, PixelFormat.Format64bppPArgb);
panel1.DrawToBitmap(bm, new Rectangle(0, 0, width, height));
//bm.Save(@"D:\TestDrawToBitmap.bmp", ImageFormat.Bmp);
bm.Save(deskTopPath + @"/Offer_" + snapCount.ToString() + "_" + DateTime.Now.ToString("yyyyMMdd") + @".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
```
---
Like here, it looks pixelated if you compare it to what you're reading now (like this website). I tried to screen cap the form but it looks like the uploaded picture so its useless
Screenshot:
 | 2018/04/04 | [
"https://Stackoverflow.com/questions/49649819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7899801/"
] | This is what I use to save a screenshot:
```
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
private void SaveControlAsImage(Control control, string path)
{
Bitmap bitmap = new Bitmap(control.Width, control.Height);
control.DrawToBitmap(bitmap, control.Bounds);
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
/* using ImageFormat.Png or ImageFormat.Bmp saves the image with better quality */
bitmap.Save(fs, ImageFormat.Png);
}
}
```
[Control screenshot using Windows Snipping Tool](https://i.stack.imgur.com/B58J4.png)
[Control screenshot using SaveControlAsImage (ImageFormat.Png)](https://i.stack.imgur.com/XtZcQ.png)
[Control screenshot using SaveControlAsImage (ImageFormat.Jpeg)](https://i.stack.imgur.com/Wf9Vw.jpg)
It's not the best quality (just a little blurry), but this removes the distortion around the text and keeps the right color.
Sidenote: You're not using the parameter (`theControl`) passed to your method, so you might as well remove it (not recommended), or change all the calls to `panel1` inside the method to `theControl` and call the method like
```
this.SaveControlImage(this.panel1);
```
Also, when you're accessing just a property (i.e. `this.panel1.Size.Width`) it's better to just call the property instead of assign it to a variable. If you're calling a method and getting a value back (which you'll be using more than once), you must assign it to a variable (i.e. `int arrayCount = array.Count()`). | Windows Forms is not using vector graphics to draw the user interface. Therefore, all you can get generically is to draw the control to a Bitmap instead of to the screen. This works independently of whether your control is visible on the screen, but there is not more than that. If you want a higher-resolution image from a Windows Forms control, the only way is to resize the control and hope that it supports zooming. |
49,649,819 | I am currently using this code to screen capture the panel I created, but whenever I am saving it, the quality is bad. Is there any way to maintain the good quality when saving it?
I tried resizing the panel but the result is still the same.
I tried doing a normal screen shot with the snipping tool and it also has the same result with the codes I use.
Any suggestions? or help?
```
private void SaveControlImage(Control theControl)
{
snapCount++;
int width = panel1.Size.Width;
int height = panel1.Size.Height;
Bitmap bm = new Bitmap(width, height, PixelFormat.Format64bppPArgb);
panel1.DrawToBitmap(bm, new Rectangle(0, 0, width, height));
//bm.Save(@"D:\TestDrawToBitmap.bmp", ImageFormat.Bmp);
bm.Save(deskTopPath + @"/Offer_" + snapCount.ToString() + "_" + DateTime.Now.ToString("yyyyMMdd") + @".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
```
---
Like here, it looks pixelated if you compare it to what you're reading now (like this website). I tried to screen cap the form but it looks like the uploaded picture so its useless
Screenshot:
 | 2018/04/04 | [
"https://Stackoverflow.com/questions/49649819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7899801/"
] | ```
Bitmap bmp= new Bitmap(controls.Width, controls.Height-50, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics Grap = Graphics.FromImage(bmp);
Grap.CopyFromScreen(PointToScreen(controls.Location).X, PointToScreen(controls.Location).Y, 0, 0, AnhDoThi.Size, CopyPixelOperation.SourceCopy);
SaveFileDialog save = new SaveFileDialog();
save.Filter = "JPEG|*.jpg";
DialogResult tl = save.ShowDialog();
if (tl == DialogResult.OK)
{
bmp.Save(save.FileName);
MessageBox.Show("Completed !");
}
``` | Windows Forms is not using vector graphics to draw the user interface. Therefore, all you can get generically is to draw the control to a Bitmap instead of to the screen. This works independently of whether your control is visible on the screen, but there is not more than that. If you want a higher-resolution image from a Windows Forms control, the only way is to resize the control and hope that it supports zooming. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.