qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
9,201,161 | I spoke about this in a previous question, but I have since narrowed down the issue to make it possible to be answered. First, some background.
I have an ASP.net website that functions normally on the local server, but when it's on the live server and accessed externally, it has some session data issues that make occasionally throw errors. The first issue turned out to be an problem with IE9. The session variable just wouldn't persist after it reached the second page and hit the stored procedure. I fixed this by foring the page to run in IE7 mode with -
This still occurs on some browsers (specifically it occurs -once- with firefox) but I created a loop that forces it back to the menu page when the session variable is blank so it just appears as the page didn't load and the "open" button can be pressed again.
However, the new problem happens when I attempt to save the data on a form. It passes a few session variables in to the stored procedure interface (like staff ID and such) and what appears to happen is that it times out. However, all of the timeouts for the session set in webconfig and IIS are extremely high numbers (many hours) and the worker processes are set to never expire or recycle. Also, it happens even after a minute or two so it can't be the timeout hitting. It's just like it randomly loses the session values. The weird thing is that if you go back and save again - performing the same actions with the same data - it tends to work. Sometimes it takes a few iterations of this but ultimately it will work.
The strange thing is also that it tends to randomly lose pieces of the viewstate - such as field values - but that might be unrelated and have more to do with the fields that are filled automatically at load. But I thought I'd include that in case it offers and information as to why it might be doing this.
I'm considering a workaround by dumping the session variables in to viewstate variables as soon as the page loads, but I'd really like to address the problem directly so I don't have to deal with it in the future when I can't do something like that. Is there some poriton of IIS (It is IIS 6 by the way) that could be the culprit? Are session variables just known for dying when being thrown around a lot? I can't say I know a great deal about server set up but I've learned a lot from this situation and beating this will be a wonderful victory for my morale. Thank you for reading and sorry it' so long! | 2012/02/08 | [
"https://Stackoverflow.com/questions/9201161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812647/"
]
| Sure, use `mktime` and `date`:
```
$days = 322;
$year = 2009;
echo date('Y-m-d', mktime( 0, 0, 0, 1, $days, $year));
```
**[Output:](http://codepad.viper-7.com/JSVWem)** 2009-11-18 | ```
$newformat = new DateTime::createFromFormat('Y z', "2009 322")->format('Y-M-d');
```
Relevant docs here: <http://php.net/manual/en/datetime.createfromformat.php> |
9,201,161 | I spoke about this in a previous question, but I have since narrowed down the issue to make it possible to be answered. First, some background.
I have an ASP.net website that functions normally on the local server, but when it's on the live server and accessed externally, it has some session data issues that make occasionally throw errors. The first issue turned out to be an problem with IE9. The session variable just wouldn't persist after it reached the second page and hit the stored procedure. I fixed this by foring the page to run in IE7 mode with -
This still occurs on some browsers (specifically it occurs -once- with firefox) but I created a loop that forces it back to the menu page when the session variable is blank so it just appears as the page didn't load and the "open" button can be pressed again.
However, the new problem happens when I attempt to save the data on a form. It passes a few session variables in to the stored procedure interface (like staff ID and such) and what appears to happen is that it times out. However, all of the timeouts for the session set in webconfig and IIS are extremely high numbers (many hours) and the worker processes are set to never expire or recycle. Also, it happens even after a minute or two so it can't be the timeout hitting. It's just like it randomly loses the session values. The weird thing is that if you go back and save again - performing the same actions with the same data - it tends to work. Sometimes it takes a few iterations of this but ultimately it will work.
The strange thing is also that it tends to randomly lose pieces of the viewstate - such as field values - but that might be unrelated and have more to do with the fields that are filled automatically at load. But I thought I'd include that in case it offers and information as to why it might be doing this.
I'm considering a workaround by dumping the session variables in to viewstate variables as soon as the page loads, but I'd really like to address the problem directly so I don't have to deal with it in the future when I can't do something like that. Is there some poriton of IIS (It is IIS 6 by the way) that could be the culprit? Are session variables just known for dying when being thrown around a lot? I can't say I know a great deal about server set up but I've learned a lot from this situation and beating this will be a wonderful victory for my morale. Thank you for reading and sorry it' so long! | 2012/02/08 | [
"https://Stackoverflow.com/questions/9201161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812647/"
]
| ```
$newformat = new DateTime::createFromFormat('Y z', "2009 322")->format('Y-M-d');
```
Relevant docs here: <http://php.net/manual/en/datetime.createfromformat.php> | The hard way ( and as a bonus, I parse the input example you gave :p ):
```
list($day, $foo, $year, $bar) = sscanf("322 days 2009 year", "%d %s %d %s");
$timestamp = mktime (0,0,0, 1, $day, $year);
echo date('Y-m-d', $timestamp);
``` |
9,201,161 | I spoke about this in a previous question, but I have since narrowed down the issue to make it possible to be answered. First, some background.
I have an ASP.net website that functions normally on the local server, but when it's on the live server and accessed externally, it has some session data issues that make occasionally throw errors. The first issue turned out to be an problem with IE9. The session variable just wouldn't persist after it reached the second page and hit the stored procedure. I fixed this by foring the page to run in IE7 mode with -
This still occurs on some browsers (specifically it occurs -once- with firefox) but I created a loop that forces it back to the menu page when the session variable is blank so it just appears as the page didn't load and the "open" button can be pressed again.
However, the new problem happens when I attempt to save the data on a form. It passes a few session variables in to the stored procedure interface (like staff ID and such) and what appears to happen is that it times out. However, all of the timeouts for the session set in webconfig and IIS are extremely high numbers (many hours) and the worker processes are set to never expire or recycle. Also, it happens even after a minute or two so it can't be the timeout hitting. It's just like it randomly loses the session values. The weird thing is that if you go back and save again - performing the same actions with the same data - it tends to work. Sometimes it takes a few iterations of this but ultimately it will work.
The strange thing is also that it tends to randomly lose pieces of the viewstate - such as field values - but that might be unrelated and have more to do with the fields that are filled automatically at load. But I thought I'd include that in case it offers and information as to why it might be doing this.
I'm considering a workaround by dumping the session variables in to viewstate variables as soon as the page loads, but I'd really like to address the problem directly so I don't have to deal with it in the future when I can't do something like that. Is there some poriton of IIS (It is IIS 6 by the way) that could be the culprit? Are session variables just known for dying when being thrown around a lot? I can't say I know a great deal about server set up but I've learned a lot from this situation and beating this will be a wonderful victory for my morale. Thank you for reading and sorry it' so long! | 2012/02/08 | [
"https://Stackoverflow.com/questions/9201161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812647/"
]
| ```
$newformat = new DateTime::createFromFormat('Y z', "2009 322")->format('Y-M-d');
```
Relevant docs here: <http://php.net/manual/en/datetime.createfromformat.php> | We do have [`strtotime()`](http://php.net/manual/en/function.strtotime.php) in php, which can easily pull timestamp from year:
```
echo $time = strtotime( '1.1.2009');
// 1230764400
```
And chain it with adding days:
```
echo $newTime = strtotime( '+322 days', $time);
// 1258585200
echo date( 'r', $newTime);
// Thu, 19 Nov 2009 00:00:00 +0100
echo date( 'Y-m-d', $newTime);
// 2009-11-19
// output will be 19 instead of 18 (due to how strtotime handles + days), you
// should use +321 days instead than
```
btw: I like Marc B's answer better .) |
9,201,161 | I spoke about this in a previous question, but I have since narrowed down the issue to make it possible to be answered. First, some background.
I have an ASP.net website that functions normally on the local server, but when it's on the live server and accessed externally, it has some session data issues that make occasionally throw errors. The first issue turned out to be an problem with IE9. The session variable just wouldn't persist after it reached the second page and hit the stored procedure. I fixed this by foring the page to run in IE7 mode with -
This still occurs on some browsers (specifically it occurs -once- with firefox) but I created a loop that forces it back to the menu page when the session variable is blank so it just appears as the page didn't load and the "open" button can be pressed again.
However, the new problem happens when I attempt to save the data on a form. It passes a few session variables in to the stored procedure interface (like staff ID and such) and what appears to happen is that it times out. However, all of the timeouts for the session set in webconfig and IIS are extremely high numbers (many hours) and the worker processes are set to never expire or recycle. Also, it happens even after a minute or two so it can't be the timeout hitting. It's just like it randomly loses the session values. The weird thing is that if you go back and save again - performing the same actions with the same data - it tends to work. Sometimes it takes a few iterations of this but ultimately it will work.
The strange thing is also that it tends to randomly lose pieces of the viewstate - such as field values - but that might be unrelated and have more to do with the fields that are filled automatically at load. But I thought I'd include that in case it offers and information as to why it might be doing this.
I'm considering a workaround by dumping the session variables in to viewstate variables as soon as the page loads, but I'd really like to address the problem directly so I don't have to deal with it in the future when I can't do something like that. Is there some poriton of IIS (It is IIS 6 by the way) that could be the culprit? Are session variables just known for dying when being thrown around a lot? I can't say I know a great deal about server set up but I've learned a lot from this situation and beating this will be a wonderful victory for my morale. Thank you for reading and sorry it' so long! | 2012/02/08 | [
"https://Stackoverflow.com/questions/9201161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812647/"
]
| Sure, use `mktime` and `date`:
```
$days = 322;
$year = 2009;
echo date('Y-m-d', mktime( 0, 0, 0, 1, $days, $year));
```
**[Output:](http://codepad.viper-7.com/JSVWem)** 2009-11-18 | Try this
[strtotime function](http://php.net/manual/en/function.strtotime.php) |
9,201,161 | I spoke about this in a previous question, but I have since narrowed down the issue to make it possible to be answered. First, some background.
I have an ASP.net website that functions normally on the local server, but when it's on the live server and accessed externally, it has some session data issues that make occasionally throw errors. The first issue turned out to be an problem with IE9. The session variable just wouldn't persist after it reached the second page and hit the stored procedure. I fixed this by foring the page to run in IE7 mode with -
This still occurs on some browsers (specifically it occurs -once- with firefox) but I created a loop that forces it back to the menu page when the session variable is blank so it just appears as the page didn't load and the "open" button can be pressed again.
However, the new problem happens when I attempt to save the data on a form. It passes a few session variables in to the stored procedure interface (like staff ID and such) and what appears to happen is that it times out. However, all of the timeouts for the session set in webconfig and IIS are extremely high numbers (many hours) and the worker processes are set to never expire or recycle. Also, it happens even after a minute or two so it can't be the timeout hitting. It's just like it randomly loses the session values. The weird thing is that if you go back and save again - performing the same actions with the same data - it tends to work. Sometimes it takes a few iterations of this but ultimately it will work.
The strange thing is also that it tends to randomly lose pieces of the viewstate - such as field values - but that might be unrelated and have more to do with the fields that are filled automatically at load. But I thought I'd include that in case it offers and information as to why it might be doing this.
I'm considering a workaround by dumping the session variables in to viewstate variables as soon as the page loads, but I'd really like to address the problem directly so I don't have to deal with it in the future when I can't do something like that. Is there some poriton of IIS (It is IIS 6 by the way) that could be the culprit? Are session variables just known for dying when being thrown around a lot? I can't say I know a great deal about server set up but I've learned a lot from this situation and beating this will be a wonderful victory for my morale. Thank you for reading and sorry it' so long! | 2012/02/08 | [
"https://Stackoverflow.com/questions/9201161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812647/"
]
| Sure, use `mktime` and `date`:
```
$days = 322;
$year = 2009;
echo date('Y-m-d', mktime( 0, 0, 0, 1, $days, $year));
```
**[Output:](http://codepad.viper-7.com/JSVWem)** 2009-11-18 | The hard way ( and as a bonus, I parse the input example you gave :p ):
```
list($day, $foo, $year, $bar) = sscanf("322 days 2009 year", "%d %s %d %s");
$timestamp = mktime (0,0,0, 1, $day, $year);
echo date('Y-m-d', $timestamp);
``` |
9,201,161 | I spoke about this in a previous question, but I have since narrowed down the issue to make it possible to be answered. First, some background.
I have an ASP.net website that functions normally on the local server, but when it's on the live server and accessed externally, it has some session data issues that make occasionally throw errors. The first issue turned out to be an problem with IE9. The session variable just wouldn't persist after it reached the second page and hit the stored procedure. I fixed this by foring the page to run in IE7 mode with -
This still occurs on some browsers (specifically it occurs -once- with firefox) but I created a loop that forces it back to the menu page when the session variable is blank so it just appears as the page didn't load and the "open" button can be pressed again.
However, the new problem happens when I attempt to save the data on a form. It passes a few session variables in to the stored procedure interface (like staff ID and such) and what appears to happen is that it times out. However, all of the timeouts for the session set in webconfig and IIS are extremely high numbers (many hours) and the worker processes are set to never expire or recycle. Also, it happens even after a minute or two so it can't be the timeout hitting. It's just like it randomly loses the session values. The weird thing is that if you go back and save again - performing the same actions with the same data - it tends to work. Sometimes it takes a few iterations of this but ultimately it will work.
The strange thing is also that it tends to randomly lose pieces of the viewstate - such as field values - but that might be unrelated and have more to do with the fields that are filled automatically at load. But I thought I'd include that in case it offers and information as to why it might be doing this.
I'm considering a workaround by dumping the session variables in to viewstate variables as soon as the page loads, but I'd really like to address the problem directly so I don't have to deal with it in the future when I can't do something like that. Is there some poriton of IIS (It is IIS 6 by the way) that could be the culprit? Are session variables just known for dying when being thrown around a lot? I can't say I know a great deal about server set up but I've learned a lot from this situation and beating this will be a wonderful victory for my morale. Thank you for reading and sorry it' so long! | 2012/02/08 | [
"https://Stackoverflow.com/questions/9201161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/812647/"
]
| Sure, use `mktime` and `date`:
```
$days = 322;
$year = 2009;
echo date('Y-m-d', mktime( 0, 0, 0, 1, $days, $year));
```
**[Output:](http://codepad.viper-7.com/JSVWem)** 2009-11-18 | We do have [`strtotime()`](http://php.net/manual/en/function.strtotime.php) in php, which can easily pull timestamp from year:
```
echo $time = strtotime( '1.1.2009');
// 1230764400
```
And chain it with adding days:
```
echo $newTime = strtotime( '+322 days', $time);
// 1258585200
echo date( 'r', $newTime);
// Thu, 19 Nov 2009 00:00:00 +0100
echo date( 'Y-m-d', $newTime);
// 2009-11-19
// output will be 19 instead of 18 (due to how strtotime handles + days), you
// should use +321 days instead than
```
btw: I like Marc B's answer better .) |
1,055,574 | What is the reason to use g:textField in Grails if you're already familiar with standard HTML form tags?
If I understand correctly the following two markup alternatives are equivalent:
```
<input type="text" name="name" value="${params.name}" id="name" />
<g:textField name="name" value="${params.name}" />
```
Are there any circumstances under which using g:textField would add value? Am I missing something? | 2009/06/28 | [
"https://Stackoverflow.com/questions/1055574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58394/"
]
| The textField tag is provided as a convenience (slightly shorter than writing the HTML input) and is there to provide a full set of form tags. Personally I prefer to write as much plain HTML as possible in my Grails views and only tend to use the tags that really offer a benefit such as the form tag. I have not found an instance where using textField would have added any value outside of requiring a few less characters to type. | `<g:textField />` is not shorter as plain text field tag, except id attribute will be attached automatically.
However, I recommend you to use customized tags associating the bean values with input fields. That shortens the code a lot. For more information you can read <http://www.jtict.com/blog/shorter-grails-textfield/>
Also you can find useful stuff in Form Helper Plugin |
16,903,131 | This is a NSTableView with IB bindings to a NSArrayController, it displays all values correctly.
However it sorts the numbers only by their first char value e.g. it will put 115.31 below 2.5, and 23.9 below 4.71, etc.
It takes values from a retained NSMutableArray with Strings in it, I also tried by converting all strings to NSNumber/NSDecimalNumber, still no luck:
```
NSMutableArray *array1 = [[string1 componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
NSMutableArray *array1alt = [NSMutableArray array];
for(NSString *strNum in array1)
{
NSNumber *number = strNum;
[array1alt addObject:number];
}
```
Please help, thanks.
**EDIT:** This is how NSMutableArray(s) of my NSTableColumn(s) get filled:
```
NSMutableArray *rows = [NSMutableArray array];
for (NSUInteger i = 0; i < array1alt.count && i < array2.count && i < array3.count && i < array4.count; i++)
{
NSMutableDictionary *row = [NSMutableDictionary dictionary];
[row setObject:[array1alt objectAtIndex:i] forKey:@"Apples"];
[row setObject:[array2 objectAtIndex:i] forKey:@"Oranges"];
[row setObject:[array3 objectAtIndex:i] forKey:@"Peaches"];
[row setObject:[array4 objectAtIndex:i] forKey:@"Plums"];
[rows addObject:row];
}
[myArrayController2 setContent:rows2];
[aTableView reloadData];
``` | 2013/06/03 | [
"https://Stackoverflow.com/questions/16903131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351760/"
]
| I'm surprised that you aren't getting a compiler warning at:
```
NSNumber *number = strNum;
```
You probably want:
```
NSNumber *number = [NSNumber numberWithDouble:[strNum doubleValue]];
```
Or, more simply:
```
NSNumber *number = @([strNum doubleValue]);
```
---
If you don't want to deal with number conversions on the output, you could sort your original array of strings like so:
```
NSArray *array2 = [array1 sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
double num1 = [obj1 doubleValue];
double num2 = [obj2 doubleValue];
if (num1 < num2)
return NSOrderedAscending;
else if (num1 > num2)
return NSOrderedDescending;
else
return NSOrderedSame;
}];
```
---
If you want to use decimal numbers, you could probably do something like:
```
NSMutableArray *array2 = [NSMutableArray array];
for (NSString *strNum in array1)
{
[array2 addObject:[NSDecimalNumber decimalNumberWithString:strNum]];
}
[array2 sortUsingComparator:^NSComparisonResult(NSDecimalNumber *obj1, NSDecimalNumber *obj2) {
return [obj1 compare:obj2];
}];
``` | Without seeing more code this is what i think:
If i understood correctly, you have your NSArrayController as data source.
You need to sort your data before attaching it to your table.
You have [NSArrayController](https://developer.apple.com/library/mac/#documentation/cocoa/reference/ApplicationKit/Classes/NSArrayController_Class/Reference/Reference.html) methods:
`- (void)setSortDescriptors:(NSArray *)sortDescriptors`
and
`- (NSArray *)arrangeObjects:(NSArray *)objects`
With this you will get sorted array to use for your table.
Maybe you will need to call `reloadData` of your NSTableView.
I cant test these right now because i'm at my laptop right now which doesn't have MacOS :) |
5,385,885 | I was trying to use following code with GWT 2.2.0:
```
//in my UiBinderFile
<ui:style field="myStyle" src="MyCssFile.css"/>
.
.
<g:Label ui:field="aboutMainHeader" styleName="{myStyle.decorFont}"></g:Label>
```
and also in MyCssFile.css in same directory as UiBInder xml,
```
//entire MyCssFile.css
@font-face {
font-family: cool_font;
src: url('cool_font.ttf');
}
.decorFont{
font-family: cool_font; /* no .ttf */
}
```
When I try to compile this, I get some NPE in UiBinder parser, right afer call of method that does font face parsing. I don't know what is wrong. Has anyone tried face-fonts with GWT, and could you please post working example?
Thanks... | 2011/03/22 | [
"https://Stackoverflow.com/questions/5385885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126382/"
]
| See <http://code.google.com/p/google-web-toolkit/issues/detail?id=5247>
You'd have to put your `@font-face` declaration in an external (not-`CssResource`) stylesheet (could be inlined in you HTML host page for instance) | Because of the limitation [Thomas has noted](https://stackoverflow.com/a/5396034/9686) I've developed a small project to define font resources into GWT clientbundle's. It's still a beta but hopes you like it.
It's on <http://code.google.com/p/gwt-webfonts/> |
23,472 | Can I use a nonbasic land that taps and gives me either a red or white mana if I only have red mana in my deck? | 2015/03/19 | [
"https://boardgames.stackexchange.com/questions/23472",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/12155/"
]
| Yes, as long as you're not playing Commander
--------------------------------------------
In normal decks, you can use whatever (format legal) cards you want in any combination. You can play a Plains in an all Red deck if you really want to, though it's probably a bad idea.
If you're playing [Commander](http://mtgsalvation.gamepedia.com/Commander_%28format%29), there is an additional rule that says that cards must match the color identity of the commander. This means that your cards can't have any mana symbols anywhere on them that don't match one of your commander's colors. In this case, if your commander isn't at least partially white, then you can't use a land that could tap for white mana. | Quoting from the [basic rulebook](https://media.wizards.com/images/magic/resources/rules/EN_MTGM14_PrintedRulebook_LR.pdf), page 15 ("Building Your Own Deck"):
>
> You build [your deck] using whichever **Magic** cards you want. There are two rules: your deck must have at least 60 cards, and your deck can't have more than four copies of any single card (except for basic lands).
>
>
>
This only applies to "Constructed" games - the "Limited" format follows slightly different rules; also certain tournament formats may restrict cards to only come from certain sets, and may also ban or restrict specific cards, as per [the banned/restricted list](https://web.archive.org/web/20151004123057/http://archive.wizards.com:80/Magic/Magazine/Article.aspx?x=judge/resources/banned). However, outside of the Commander format there are no rules preventing you from including multi-colour lands unless they are specifically in one of those lists.
If you do include one of those lands, there are a few things to note:
1. It does exactly what it says on it - so if it says "T: Add W or R to your mana pool", then you may tap it to add *either* one white mana *or* one red mana to your mana pool. If your deck has no use for white mana, then you probably won't ever choose to do so, but there's nothing stopping you from doing so.
2. The land is not a basic land of any type (unless some card specifies otherwise). So even if it produces W/R mana, it is *not* a Plains *or* a Mountain (or an Island, Swamp or Forest).
3. As stated above, since it is not a basic land you can not have more than four copies in your deck, or more than one copy if it is on the restricted list for the format you are playing. |
2,488,677 | File `a.hpp`:
```
class a;
typedef boost::shared_ptr<a> aPtr
class a{
public:
static aPtr CreateImp();
virtual void Foo() = 0 ;
....
};
```
File `aImp.hpp`:
```
class aImp : public a{
virtual void Foo();
};
```
File `aImp.cpp`:
```
aPtr a::CreateImp()
{
return aPtr(new aImp());
}
void aImp::Foo(){}
```
The client must use `CreateImp` to get pointer to `a`, and can't use `a` other ways.
What do you think about this implementation?
What do you think about this kind of implementation? | 2010/03/21 | [
"https://Stackoverflow.com/questions/2488677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271362/"
]
| This looks like a normal implementation if the [Factory Method](http://en.wikipedia.org/wiki/Factory_method) design pattern. The return of `boost::shared_ptr` just makes life of the programmer using this API easier in terms of memory management and exception safety and guards against simple mistakes like calling the function and ignoring the return value.
### Edit:
If this is the only implementation of the base class, then it might be that the author was aiming for [pimpl idiom](http://en.wikipedia.org/wiki/Pimpl_idiom) to hide the implementation details and/or reduce compile-time dependencies. | Looks like good encapsulation, although I don't actually see anything preventing a from being used otherwise. (For example, private constructor and friend class aImp).
No compile unit using class a will have any knowledge of the implementation details except for aImp.cpp itself. So changes to aImp.hpp won't induce recompiles across the project. This both speeds recompilation and prevents coupling, it's helps maintainability a lot.
OTOH, anything implemented in aImp.hpp now can't be inlined, so run-time performance may suffer some, unless your compiler has something akin to Visual C++ "Link-Time Code Generation" (which pretty much undoes any gain to build speed from encapsulation).
As far as the smart pointer is concerned, this depends on project coding standards (whether boost pointers are used everywhere, etc). |
2,488,677 | File `a.hpp`:
```
class a;
typedef boost::shared_ptr<a> aPtr
class a{
public:
static aPtr CreateImp();
virtual void Foo() = 0 ;
....
};
```
File `aImp.hpp`:
```
class aImp : public a{
virtual void Foo();
};
```
File `aImp.cpp`:
```
aPtr a::CreateImp()
{
return aPtr(new aImp());
}
void aImp::Foo(){}
```
The client must use `CreateImp` to get pointer to `a`, and can't use `a` other ways.
What do you think about this implementation?
What do you think about this kind of implementation? | 2010/03/21 | [
"https://Stackoverflow.com/questions/2488677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271362/"
]
| This looks like a normal implementation if the [Factory Method](http://en.wikipedia.org/wiki/Factory_method) design pattern. The return of `boost::shared_ptr` just makes life of the programmer using this API easier in terms of memory management and exception safety and guards against simple mistakes like calling the function and ignoring the return value.
### Edit:
If this is the only implementation of the base class, then it might be that the author was aiming for [pimpl idiom](http://en.wikipedia.org/wiki/Pimpl_idiom) to hide the implementation details and/or reduce compile-time dependencies. | If the intention is using the PIMPL idiom, then it is not the most idiomatic way. Inheritance is the second strongest coupling relationship in C++ and should be avoided if other solutions are available (i.e. composition).
Now, there might be other requirements that force the use of dynamic allocation, and/or the use of an specific type of smart pointer, but with the information you have presented I would implement the PIMPL idiom in the common way:
```
// .h
class a {
public:
~a(); // implement it in .cpp where a::impl is defined
void op();
private:
class impl;
std::auto_ptr<impl> pimpl;
};
// .cpp
class a::impl {
public:
void op();
};
a::~a() {}
void a::op() { pimpl->op(); }
```
The only (dis)advantage of using inheritance is that the runtime dispatch mechanism will call the implementation method for you, and you will not be required to implement the forwarding calls (`a::op()` in the example). On the other hand, you are paying the cost of the virtual dispatch mechanism in each and every operation, and limiting the use of your class to the heap (you cannot create an instance of `a` in the stack, you must call the factory function to create the object dynamically).
On the use of `shared_ptr` in the interface, I would try to avoid it (leave freedom of choice to your users) if possible. In this particular case, it seems as if the object is not really *shared* (the creator function creates an instance and returns a pointer, forgetting about it), so it would be better to have a smart pointer that allows for transfer of ownership (either `std::auto_ptr`, or the newer `unique_ptr` could do the trick), since the use of `shared_ptr` imposes that decision to your users.
(NOTE: *removed it as the comment makes it useless*) |
2,488,677 | File `a.hpp`:
```
class a;
typedef boost::shared_ptr<a> aPtr
class a{
public:
static aPtr CreateImp();
virtual void Foo() = 0 ;
....
};
```
File `aImp.hpp`:
```
class aImp : public a{
virtual void Foo();
};
```
File `aImp.cpp`:
```
aPtr a::CreateImp()
{
return aPtr(new aImp());
}
void aImp::Foo(){}
```
The client must use `CreateImp` to get pointer to `a`, and can't use `a` other ways.
What do you think about this implementation?
What do you think about this kind of implementation? | 2010/03/21 | [
"https://Stackoverflow.com/questions/2488677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271362/"
]
| If the intention is using the PIMPL idiom, then it is not the most idiomatic way. Inheritance is the second strongest coupling relationship in C++ and should be avoided if other solutions are available (i.e. composition).
Now, there might be other requirements that force the use of dynamic allocation, and/or the use of an specific type of smart pointer, but with the information you have presented I would implement the PIMPL idiom in the common way:
```
// .h
class a {
public:
~a(); // implement it in .cpp where a::impl is defined
void op();
private:
class impl;
std::auto_ptr<impl> pimpl;
};
// .cpp
class a::impl {
public:
void op();
};
a::~a() {}
void a::op() { pimpl->op(); }
```
The only (dis)advantage of using inheritance is that the runtime dispatch mechanism will call the implementation method for you, and you will not be required to implement the forwarding calls (`a::op()` in the example). On the other hand, you are paying the cost of the virtual dispatch mechanism in each and every operation, and limiting the use of your class to the heap (you cannot create an instance of `a` in the stack, you must call the factory function to create the object dynamically).
On the use of `shared_ptr` in the interface, I would try to avoid it (leave freedom of choice to your users) if possible. In this particular case, it seems as if the object is not really *shared* (the creator function creates an instance and returns a pointer, forgetting about it), so it would be better to have a smart pointer that allows for transfer of ownership (either `std::auto_ptr`, or the newer `unique_ptr` could do the trick), since the use of `shared_ptr` imposes that decision to your users.
(NOTE: *removed it as the comment makes it useless*) | Looks like good encapsulation, although I don't actually see anything preventing a from being used otherwise. (For example, private constructor and friend class aImp).
No compile unit using class a will have any knowledge of the implementation details except for aImp.cpp itself. So changes to aImp.hpp won't induce recompiles across the project. This both speeds recompilation and prevents coupling, it's helps maintainability a lot.
OTOH, anything implemented in aImp.hpp now can't be inlined, so run-time performance may suffer some, unless your compiler has something akin to Visual C++ "Link-Time Code Generation" (which pretty much undoes any gain to build speed from encapsulation).
As far as the smart pointer is concerned, this depends on project coding standards (whether boost pointers are used everywhere, etc). |
2,799,405 | I'm trying to execute a stored procedure (against SQL Server 2005 through the ODBC driver) and I recieve the following error:
>
> Procedure or Function 'GetNodeID' expects parameter '@ID', which was not supplied.
>
>
>
@ID is the OUTPUT parameter for my procedure, there is an input @machine which is specified and is set to null in the stored procedure:
```
ALTER PROCEDURE [dbo].[GetNodeID]
@machine nvarchar(32) = null,
@ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM Nodes WHERE NodeName=@machine)
BEGIN
SELECT @ID = (SELECT NodeID FROM Nodes WHERE NodeName=@machine)
END
ELSE
BEGIN
INSERT INTO Nodes (NodeName) VALUES (@machine)
SELECT @ID = (SELECT NodeID FROM Nodes WHERE NodeName=@machine)
END
END
```
The following is the code I'm using to set the parameters and call the procedure:
```
OdbcCommand Cmd = new OdbcCommand("GetNodeID", _Connection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("@machine", OdbcType.NVarChar);
Cmd.Parameters["@machine"].Value = Environment.MachineName.ToLower();
Cmd.Parameters.Add("@ID", OdbcType.Int);
Cmd.Parameters["@ID"].Direction = ParameterDirection.Output;
Cmd.ExecuteNonQuery();
_NodeID = (int)Cmd.Parameters["@Count"].Value;
```
I've also tried using Cmd.ExecuteScalar with no success. If I break before I execute the command, I can see that @machine has a value.
If I execute the procedure directly from Management Studio, it works correctly.
Any thoughts? Thanks | 2010/05/09 | [
"https://Stackoverflow.com/questions/2799405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172871/"
]
| Try replacing :
```
OdbcCommand Cmd = new OdbcCommand("GetNodeID", _Connection);
Cmd.CommandType = CommandType.StoredProcedure;
```
With :
```
OdbcCommand Cmd = new OdbcCommand("{call GetNodeID(?,?)}", _Connection);
```
More info :
<http://support.microsoft.com/kb/310130> | I'm not exactly sure what you mean by
>
> there is an input @machine which is
> specified and is set to null in the
> stored procedure
>
>
>
In your proc's signature, this line:
```
@machine nvarchar(32) = null
```
doesn't mean that you're setting `@machine` to null inside the proc - it means you're assigning a default value to be used in case the parameter is missing (in this case, `null` is the value to be used for a missing param).
Getting the error about `@ID` being missing would happen if you were calling this stored procedure without passing any parameters at all (`@machine` would not be flagged as a problem since it has a default value defined). Your code example looks fine to me - are you sure the stored proc isn't being called from somewhere else in your program (somewhere where no parameters are being added)? |
2,799,405 | I'm trying to execute a stored procedure (against SQL Server 2005 through the ODBC driver) and I recieve the following error:
>
> Procedure or Function 'GetNodeID' expects parameter '@ID', which was not supplied.
>
>
>
@ID is the OUTPUT parameter for my procedure, there is an input @machine which is specified and is set to null in the stored procedure:
```
ALTER PROCEDURE [dbo].[GetNodeID]
@machine nvarchar(32) = null,
@ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM Nodes WHERE NodeName=@machine)
BEGIN
SELECT @ID = (SELECT NodeID FROM Nodes WHERE NodeName=@machine)
END
ELSE
BEGIN
INSERT INTO Nodes (NodeName) VALUES (@machine)
SELECT @ID = (SELECT NodeID FROM Nodes WHERE NodeName=@machine)
END
END
```
The following is the code I'm using to set the parameters and call the procedure:
```
OdbcCommand Cmd = new OdbcCommand("GetNodeID", _Connection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("@machine", OdbcType.NVarChar);
Cmd.Parameters["@machine"].Value = Environment.MachineName.ToLower();
Cmd.Parameters.Add("@ID", OdbcType.Int);
Cmd.Parameters["@ID"].Direction = ParameterDirection.Output;
Cmd.ExecuteNonQuery();
_NodeID = (int)Cmd.Parameters["@Count"].Value;
```
I've also tried using Cmd.ExecuteScalar with no success. If I break before I execute the command, I can see that @machine has a value.
If I execute the procedure directly from Management Studio, it works correctly.
Any thoughts? Thanks | 2010/05/09 | [
"https://Stackoverflow.com/questions/2799405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172871/"
]
| Try replacing :
```
OdbcCommand Cmd = new OdbcCommand("GetNodeID", _Connection);
Cmd.CommandType = CommandType.StoredProcedure;
```
With :
```
OdbcCommand Cmd = new OdbcCommand("{call GetNodeID(?,?)}", _Connection);
```
More info :
<http://support.microsoft.com/kb/310130> | **Stored procedure with input parameters and ODBC Connection:**
**create a stored procedure:**
>
> create procedure proc\_name @parm1 varchar(20), @parm2 varchar(10) as begin insert into table\_name values(@parm1,@parm2);end
>
>
>
---
This code works in `SQL Server.`
```
private void button1_Click(object sender, EventArgs e)
{
string name = txtname.Text;
string num = txtnum.Text;
OdbcConnection con = new OdbcConnection("dsn=naveenk_m5");
OdbcCommand cmd = new OdbcCommand("{call proc1(?,?)}",con);
cmd.Parameters.Add("@parm1", OdbcType.VarChar).Value=name;
cmd.Parameters.Add("@parm2", OdbcType.VarChar).Value = num;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("inserted a row");
}
``` |
16,024,161 | I'm trying to use <http://github.com/TheLevelUp/ZXingObjC> to create QR codes on my Mac app.
It works for every barcode types, but returns nil on QRcode! both 'result' and 'error' is empty. here's my code:
```
NSError* error = nil;
ZXMultiFormatWriter* writer = [[ZXMultiFormatWriter alloc] init];
ZXBitMatrix* result = [writer encode:@"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
format:kBarcodeFormatQRCode
width:1750
height:1750 hints:[[ZXEncodeHints alloc] init] error:&error];
if (result) {
CGImageRef image = [[ZXImage imageWithMatrix:result] cgimage];
self.image.image = [[NSImage alloc] initWithCGImage:image size:NSMakeSize(1750, 1750)];
} else {
NSLog(@"error: %@", error);
}
```
What's wrong on it? | 2013/04/15 | [
"https://Stackoverflow.com/questions/16024161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1151000/"
]
| I had the same issue. Here is workaround for this.
1. Open file `ZXingObjC\qrcode\encoder\ZXEncoder.m`
2. Find this row: `int minPenalty = NSIntegerMax;`. There must be a warning on it: **Implicit conversion from 'long' to 'int' changes 9223372036854775807 to -1**. That's the reason of the problem. `NSIntegerMax` returns `9223372036854775807` on my 64-bit Mac and `minPenalty` gets `-1` value (since `int` type cannot store such a big number).
3. Replace the `NSIntegerMax` by `INT_MAX`. It should return the correct value: `2147483647`. That's the number `NSIntegerMax` returns on 32-bit machines according to the answer to [this question](https://stackoverflow.com/questions/4800015/what-is-the-maximum-value-of-nsinteger).
4. Run the app and you'll get your QR code! | Try to use another method, not this with HINTS, use just:
`[writer encode:@"yourmeganumber" format:kBarcodeFormatQRCode width:xxxx height:xxxx error:&error];`
This works for me
Try and let me know |
68,788,047 | I am building a project just for fun and I want to turn it into an exe but it gives me the error
`PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_IPython required by hook for module c:\users\waddy\appdata\local\programs\python\python39\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py. Please check whether module __PyInstaller_hooks_0_IPython actually exists and whether the hook is compatible with your version of c:\users\waddy\appdata\local\programs\python\python39\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py:`
I'm working with python version `3.9.1` and pyinstaller `4.5.1`. I tried using the solution given [here](https://stackoverflow.com/questions/67815939/pyinstaller-failed-to-import-module-pyinstaller-hooks-0-pydoc) but it gives me another error `AttributeError: Module 'PyQt5' has no attribute '__version__'`
How could I fix this? | 2021/08/15 | [
"https://Stackoverflow.com/questions/68788047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14941611/"
]
| In my case this exception was caused by missing `text-unidecode` package.
It was resolved by
```
pip install text-unidecode
```
Look complete traceback of exception and see if there is any other package missing in your case. | Try to uninstall `pyinstaller` and re-install it using `pip`
And if it doesn't work for you, this may will:
<https://github.com/pyinstaller/pyinstaller/issues/2114> |
68,788,047 | I am building a project just for fun and I want to turn it into an exe but it gives me the error
`PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_IPython required by hook for module c:\users\waddy\appdata\local\programs\python\python39\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py. Please check whether module __PyInstaller_hooks_0_IPython actually exists and whether the hook is compatible with your version of c:\users\waddy\appdata\local\programs\python\python39\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py:`
I'm working with python version `3.9.1` and pyinstaller `4.5.1`. I tried using the solution given [here](https://stackoverflow.com/questions/67815939/pyinstaller-failed-to-import-module-pyinstaller-hooks-0-pydoc) but it gives me another error `AttributeError: Module 'PyQt5' has no attribute '__version__'`
How could I fix this? | 2021/08/15 | [
"https://Stackoverflow.com/questions/68788047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14941611/"
]
| In my case this exception was caused by missing `text-unidecode` package.
It was resolved by
```
pip install text-unidecode
```
Look complete traceback of exception and see if there is any other package missing in your case. | In my case the exception was caused by missing the numpy module. Resolved by
```
pip install numpy
``` |
55,797 | I'm trying to design a visual representation of a child's sleep schedule for a given week.
I was thinking of making a chart with the time of day on the y-axis and the days of the week on the x-axis and then blocking in the time intervals much like a calendar app would.
What are some alternate ways of representing this data that might result in a better user experience? Keep in mind that all 24 hours of the day have to be visible unlike most workday calendars because kids sleep at all hours.

**EDIT:** Another option, I suppose is a [bubble chart](http://www.highcharts.com/demo/bubble), with the bubble plotted at the midpoint of the sleep duration and the size of the bubble indicating the length of the sleep. | 2014/04/15 | [
"https://ux.stackexchange.com/questions/55797",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/23162/"
]
| I agree with [Charles](https://ux.stackexchange.com/users/19574/charles-wesley); the same chart but with the axes reversed makes more sense to me. I tend to think of time in terms of timelines, which your chart just isn't doing for me right now. I also think you want some way to indicate continuities within broken time chunks, so it's clear that the kid didn't wake up briefly at midnight.

[download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fdlXyG.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
It's also worth thinking about presentation in terms of how your users will find the data most useful. For instance, you might allow your users to set the time at which a 'day' begins so that they can get meaningful stats about how much their child slept on an average day. Ergo, if the child is always awake by 10am, you have the day start at 10am (and adjust the display accordingly) so that the night's sleep is all linked to a single day. | Another alternative - one that gets rid of the discontinuity at midnight (or 10am) - would be a spiral visualization, with one day per circuit.
Here's a picture of a spiral visualisation from [an earlier UX answer](https://ux.stackexchange.com/a/4113/376) of mine:

You could use 24 hours per circuit, and show history over 7 or 10 days easily. The same time of day always shows at the same angle, so patterns are immediately visible. I'd probably set things up with noon at the top and midnight at the bottom, giving 6am on the left and 9pm on the right.
*Disclosure:* I encountered these visualizations while working at a company founded by [Andrew Cardno](http://www.bis2.net/about_us/management); there may be IP issues if you are working on something commercial. |
6,097,074 | I have 8 uitextfields that are for a password. Each textfield contains one letter from password. When I type one letter and after that when I press the 2nd key then focus moves to next textfield. But I want that, as soon as I finished typing first character, the focus should move to the next text field without pressing other key or pressing tab key. How can I do that? Any tutorial of sample code for that? The code I have used is as below.
```
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
//nextTag += 1;
[nextResponder becomeFirstResponder];
if ([nextResponder tag] == 308) {
//[self performSelector:@selector(checkPassCode) withObject:nil afterDelay:0.0];
[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(checkPassCode) userInfo:nil repeats:NO];
lastResponder = nextResponder;
}
return YES;
} else {
[textField resignFirstResponder];
return NO;
}
}
-(void) keyPressed: (NSNotification*) notification
{
nextTag += 1;
[[NSNotificationCenter defaultCenter] removeObserver: self name:UITextFieldTextDidChangeNotification object: nil];
}
``` | 2011/05/23 | [
"https://Stackoverflow.com/questions/6097074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765979/"
]
| ```
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ( [finalString length] > 0 ) {
textField.text = string;
UIResponder* nextResponder = [textField.superview viewWithTag:(textField.tag + 1)];
if (nextResponder) {
[nextResponder becomeFirstResponder];
// Your code for checking it.
}
return NO;
}
return YES;
}
```
Hope this helps.
**Swift 3.2**
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let finalString: String? = (textField.text? as NSString).replacingCharacters(in: range, with: string)
if (finalString?.characters.count ?? 0) > 0 {
textField.text = string
let nextResponder: UIResponder? = textField.superview?.viewWithTag((textField.tag + 1))
if nextResponder != nil {
nextResponder?.becomeFirstResponder()
// Your code for checking it.
}
return false
}
return true
}
```
**Swift 4.1**
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let finalString: String? = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
if finalString?.count > 0 {
textField.text = string
let nextResponder: UIResponder? = textField.superview?.viewWithTag(textField.tag + 1)
if nextResponder != nil {
nextResponder?.becomeFirstResponder()
// Your code for checking it.
}
return false
}
return true
}
``` | Try this *add notification* in ViewDidLoad,
```
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(limitTextField:) name:@"UITextFieldTextDidChangeNotification" object:txtField1];
- (void)limitTextField:(NSNotification *)note {
if(txtField1.tag==1)
{
if ([[txtField1 text] length] > 1)
{
[txtField1 resignFirstResponder];
[txtField2 becomeFirstResponder];
}
}
}
``` |
6,097,074 | I have 8 uitextfields that are for a password. Each textfield contains one letter from password. When I type one letter and after that when I press the 2nd key then focus moves to next textfield. But I want that, as soon as I finished typing first character, the focus should move to the next text field without pressing other key or pressing tab key. How can I do that? Any tutorial of sample code for that? The code I have used is as below.
```
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(keyPressed:) name: UITextFieldTextDidChangeNotification object: nil];
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
//nextTag += 1;
[nextResponder becomeFirstResponder];
if ([nextResponder tag] == 308) {
//[self performSelector:@selector(checkPassCode) withObject:nil afterDelay:0.0];
[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(checkPassCode) userInfo:nil repeats:NO];
lastResponder = nextResponder;
}
return YES;
} else {
[textField resignFirstResponder];
return NO;
}
}
-(void) keyPressed: (NSNotification*) notification
{
nextTag += 1;
[[NSNotificationCenter defaultCenter] removeObserver: self name:UITextFieldTextDidChangeNotification object: nil];
}
``` | 2011/05/23 | [
"https://Stackoverflow.com/questions/6097074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765979/"
]
| ```
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
if ( [finalString length] > 0 ) {
textField.text = string;
UIResponder* nextResponder = [textField.superview viewWithTag:(textField.tag + 1)];
if (nextResponder) {
[nextResponder becomeFirstResponder];
// Your code for checking it.
}
return NO;
}
return YES;
}
```
Hope this helps.
**Swift 3.2**
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let finalString: String? = (textField.text? as NSString).replacingCharacters(in: range, with: string)
if (finalString?.characters.count ?? 0) > 0 {
textField.text = string
let nextResponder: UIResponder? = textField.superview?.viewWithTag((textField.tag + 1))
if nextResponder != nil {
nextResponder?.becomeFirstResponder()
// Your code for checking it.
}
return false
}
return true
}
```
**Swift 4.1**
```
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let finalString: String? = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
if finalString?.count > 0 {
textField.text = string
let nextResponder: UIResponder? = textField.superview?.viewWithTag(textField.tag + 1)
if nextResponder != nil {
nextResponder?.becomeFirstResponder()
// Your code for checking it.
}
return false
}
return true
}
``` | ```
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField ==firstTextField) {
[secondTextField becomeFirstResponder];
}else if ( textField == secondTextField){
[thirdTextField becomeFirstResponder];
}else if ( textField == thirdTextField){
[fourthTextField becomeFirstResponder];
}else{
[textField resignFirstResponder];
}
return YES;
}
``` |
558,583 | I am dealing with a really slow shell connection. It is in the cloud and I am very far from the server. My connection also breaks sometimes as it is over the internet and I may also be using shared Wifi or 3G. Is there a way to see what I type instantly? Trying to type commands and waiting for each character is atrocious. | 2013/12/02 | [
"https://serverfault.com/questions/558583",
"https://serverfault.com",
"https://serverfault.com/users/16322/"
]
| Try [Mosh](http://mosh.mit.edu/).
>
> **Mosh (mobile shell)**
>
> Remote terminal application that allows roaming, supports intermittent connectivity, and provides intelligent local echo and line editing of user keystrokes.
>
>
> Mosh is a replacement for SSH. It's more robust and responsive, especially over Wi-Fi, cellular, and long-distance links.
>
>
> Mosh is free software, available for GNU/Linux, FreeBSD, Solaris, Mac OS X, and Android.
>
>
> | an alternative (and also in addition) to dmourati answer: use `screen` or `tmux` or other things, to keep sessions alive when you are disconnected. (You simply re-attach to the session after you reconnect, and see the terminal as you left it, even with full screen programs [vi, etc]). It also have many other benefits (sharing sessions with co-workers, etc)
(as in Mosh own faq it states:
>
> Q: Why is my terminal's scrollback buffer incomplete?
>
>
> Mosh 1.2 synchronizes only the visible state of the terminal. Mosh
> 1.3 will have complete scrollback support; see this issue and the others which are linked from there. For now, the workaround is to use
> screen or tmux on the remote side.
>
>
>
And you should also use `rsync` to copy files, without having to re-send already sent parts over the network when the connection dies. |
558,583 | I am dealing with a really slow shell connection. It is in the cloud and I am very far from the server. My connection also breaks sometimes as it is over the internet and I may also be using shared Wifi or 3G. Is there a way to see what I type instantly? Trying to type commands and waiting for each character is atrocious. | 2013/12/02 | [
"https://serverfault.com/questions/558583",
"https://serverfault.com",
"https://serverfault.com/users/16322/"
]
| Try [Mosh](http://mosh.mit.edu/).
>
> **Mosh (mobile shell)**
>
> Remote terminal application that allows roaming, supports intermittent connectivity, and provides intelligent local echo and line editing of user keystrokes.
>
>
> Mosh is a replacement for SSH. It's more robust and responsive, especially over Wi-Fi, cellular, and long-distance links.
>
>
> Mosh is free software, available for GNU/Linux, FreeBSD, Solaris, Mac OS X, and Android.
>
>
> | You should see where the latency/bottleneck(s) are. You should try to get better access to infrastructure... either locally or at the provider's side. You wrap your important or critical sessions in `tmux` or `screen` multiplexers...
Please give us numbers. It takes a particularly-bad connection for simple SSH sessions to have problems... I've had to access systems on the other side of the world from an *airplane* over a VPN and still haven't had too much trouble. Is this a persistent issue? What does `traceroute` tell you? |
558,583 | I am dealing with a really slow shell connection. It is in the cloud and I am very far from the server. My connection also breaks sometimes as it is over the internet and I may also be using shared Wifi or 3G. Is there a way to see what I type instantly? Trying to type commands and waiting for each character is atrocious. | 2013/12/02 | [
"https://serverfault.com/questions/558583",
"https://serverfault.com",
"https://serverfault.com/users/16322/"
]
| Try [Mosh](http://mosh.mit.edu/).
>
> **Mosh (mobile shell)**
>
> Remote terminal application that allows roaming, supports intermittent connectivity, and provides intelligent local echo and line editing of user keystrokes.
>
>
> Mosh is a replacement for SSH. It's more robust and responsive, especially over Wi-Fi, cellular, and long-distance links.
>
>
> Mosh is free software, available for GNU/Linux, FreeBSD, Solaris, Mac OS X, and Android.
>
>
> | For future readers of this thread, @lowellheddings' tip in his [blog](https://www.howtogeek.com/howto/linux/keep-your-linux-ssh-session-from-disconnecting/), together with the use of [screen](https://linux.die.net/man/1/screen), could help overcome this issue:
You can configure the ssh client to automatically send a protocol no-op code code every number of seconds so that the server won’t disconnect you. This setting is sometimes referred to as Keep-Alive or Stop-Disconnecting-So-Much in other clients.
Add the following line to the /etc/ssh/ssh\_config file:
ServerAliveInterval 60
... |
558,583 | I am dealing with a really slow shell connection. It is in the cloud and I am very far from the server. My connection also breaks sometimes as it is over the internet and I may also be using shared Wifi or 3G. Is there a way to see what I type instantly? Trying to type commands and waiting for each character is atrocious. | 2013/12/02 | [
"https://serverfault.com/questions/558583",
"https://serverfault.com",
"https://serverfault.com/users/16322/"
]
| an alternative (and also in addition) to dmourati answer: use `screen` or `tmux` or other things, to keep sessions alive when you are disconnected. (You simply re-attach to the session after you reconnect, and see the terminal as you left it, even with full screen programs [vi, etc]). It also have many other benefits (sharing sessions with co-workers, etc)
(as in Mosh own faq it states:
>
> Q: Why is my terminal's scrollback buffer incomplete?
>
>
> Mosh 1.2 synchronizes only the visible state of the terminal. Mosh
> 1.3 will have complete scrollback support; see this issue and the others which are linked from there. For now, the workaround is to use
> screen or tmux on the remote side.
>
>
>
And you should also use `rsync` to copy files, without having to re-send already sent parts over the network when the connection dies. | You should see where the latency/bottleneck(s) are. You should try to get better access to infrastructure... either locally or at the provider's side. You wrap your important or critical sessions in `tmux` or `screen` multiplexers...
Please give us numbers. It takes a particularly-bad connection for simple SSH sessions to have problems... I've had to access systems on the other side of the world from an *airplane* over a VPN and still haven't had too much trouble. Is this a persistent issue? What does `traceroute` tell you? |
558,583 | I am dealing with a really slow shell connection. It is in the cloud and I am very far from the server. My connection also breaks sometimes as it is over the internet and I may also be using shared Wifi or 3G. Is there a way to see what I type instantly? Trying to type commands and waiting for each character is atrocious. | 2013/12/02 | [
"https://serverfault.com/questions/558583",
"https://serverfault.com",
"https://serverfault.com/users/16322/"
]
| an alternative (and also in addition) to dmourati answer: use `screen` or `tmux` or other things, to keep sessions alive when you are disconnected. (You simply re-attach to the session after you reconnect, and see the terminal as you left it, even with full screen programs [vi, etc]). It also have many other benefits (sharing sessions with co-workers, etc)
(as in Mosh own faq it states:
>
> Q: Why is my terminal's scrollback buffer incomplete?
>
>
> Mosh 1.2 synchronizes only the visible state of the terminal. Mosh
> 1.3 will have complete scrollback support; see this issue and the others which are linked from there. For now, the workaround is to use
> screen or tmux on the remote side.
>
>
>
And you should also use `rsync` to copy files, without having to re-send already sent parts over the network when the connection dies. | For future readers of this thread, @lowellheddings' tip in his [blog](https://www.howtogeek.com/howto/linux/keep-your-linux-ssh-session-from-disconnecting/), together with the use of [screen](https://linux.die.net/man/1/screen), could help overcome this issue:
You can configure the ssh client to automatically send a protocol no-op code code every number of seconds so that the server won’t disconnect you. This setting is sometimes referred to as Keep-Alive or Stop-Disconnecting-So-Much in other clients.
Add the following line to the /etc/ssh/ssh\_config file:
ServerAliveInterval 60
... |
1,898,804 | I have added HTML to my page using the .after() method using HTML that is retrieved from a .GET() 'Ajax' call.
I have a button in my retrieved HTML and an event that is set to be triggered when this button is clicked. However the method that handles the .click event is never triggered. When I put the same button into my 'normal' html however the method is triggered and the .click() works fine.
This happens in both Mozilla and Firefox. What can I do to get the retrieved button to be recognised by jQuery? I have all my code within the $(document).ready(function() { ... will this have any affect? | 2009/12/14 | [
"https://Stackoverflow.com/questions/1898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69803/"
]
| Use [.live('click', fn)](http://docs.jquery.com/Events/live) instead of .click(fn) to wire up your event handler. A regular .click(fn) wireup in $(document).ready() will only affect elements in the DOM during the initial page load. | Sounds like you need to check out the .live() function.
<http://docs.jquery.com/Events/live> |
1,898,804 | I have added HTML to my page using the .after() method using HTML that is retrieved from a .GET() 'Ajax' call.
I have a button in my retrieved HTML and an event that is set to be triggered when this button is clicked. However the method that handles the .click event is never triggered. When I put the same button into my 'normal' html however the method is triggered and the .click() works fine.
This happens in both Mozilla and Firefox. What can I do to get the retrieved button to be recognised by jQuery? I have all my code within the $(document).ready(function() { ... will this have any affect? | 2009/12/14 | [
"https://Stackoverflow.com/questions/1898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69803/"
]
| Sounds like you need to check out the .live() function.
<http://docs.jquery.com/Events/live> | Try `$("#btn").live("click", function(){...})` instead of `$("#btn").click(function(){...})` |
1,898,804 | I have added HTML to my page using the .after() method using HTML that is retrieved from a .GET() 'Ajax' call.
I have a button in my retrieved HTML and an event that is set to be triggered when this button is clicked. However the method that handles the .click event is never triggered. When I put the same button into my 'normal' html however the method is triggered and the .click() works fine.
This happens in both Mozilla and Firefox. What can I do to get the retrieved button to be recognised by jQuery? I have all my code within the $(document).ready(function() { ... will this have any affect? | 2009/12/14 | [
"https://Stackoverflow.com/questions/1898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69803/"
]
| Sounds like you need to check out the .live() function.
<http://docs.jquery.com/Events/live> | If you have `<script>` tags contained in your data that you retrieve with `.get()` they will not be executed when added to the page with `.after()`.
You can either attach the code after the fact:
```
$.get('/url', {key:value}, function(data){
$("#wrapper").after(data);
$("#new_id a").click(function(){ ... });
}, 'html');
```
Or you can parse the return data for `<script>` blocks and `eval()` them after you have used the `.after()` function. *Be very careful you trust the `<script>` blocks before you blindly `eval` them.* |
1,898,804 | I have added HTML to my page using the .after() method using HTML that is retrieved from a .GET() 'Ajax' call.
I have a button in my retrieved HTML and an event that is set to be triggered when this button is clicked. However the method that handles the .click event is never triggered. When I put the same button into my 'normal' html however the method is triggered and the .click() works fine.
This happens in both Mozilla and Firefox. What can I do to get the retrieved button to be recognised by jQuery? I have all my code within the $(document).ready(function() { ... will this have any affect? | 2009/12/14 | [
"https://Stackoverflow.com/questions/1898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69803/"
]
| Use [.live('click', fn)](http://docs.jquery.com/Events/live) instead of .click(fn) to wire up your event handler. A regular .click(fn) wireup in $(document).ready() will only affect elements in the DOM during the initial page load. | Try `$("#btn").live("click", function(){...})` instead of `$("#btn").click(function(){...})` |
1,898,804 | I have added HTML to my page using the .after() method using HTML that is retrieved from a .GET() 'Ajax' call.
I have a button in my retrieved HTML and an event that is set to be triggered when this button is clicked. However the method that handles the .click event is never triggered. When I put the same button into my 'normal' html however the method is triggered and the .click() works fine.
This happens in both Mozilla and Firefox. What can I do to get the retrieved button to be recognised by jQuery? I have all my code within the $(document).ready(function() { ... will this have any affect? | 2009/12/14 | [
"https://Stackoverflow.com/questions/1898804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69803/"
]
| Use [.live('click', fn)](http://docs.jquery.com/Events/live) instead of .click(fn) to wire up your event handler. A regular .click(fn) wireup in $(document).ready() will only affect elements in the DOM during the initial page load. | If you have `<script>` tags contained in your data that you retrieve with `.get()` they will not be executed when added to the page with `.after()`.
You can either attach the code after the fact:
```
$.get('/url', {key:value}, function(data){
$("#wrapper").after(data);
$("#new_id a").click(function(){ ... });
}, 'html');
```
Or you can parse the return data for `<script>` blocks and `eval()` them after you have used the `.after()` function. *Be very careful you trust the `<script>` blocks before you blindly `eval` them.* |
283,663 | I have a VPS and a domain name registered with the provider.
When I enter www.example.com my site is displayed correctly, but entering example.com does not work. I am able to ping www.example.com.
I added the following line to my apache2 default vhosts file:
```
ServerName example.com
ServerAlias www.example.com
```
But this did not work.
The VPS is a Debian5 OS.
Any ideas?
Note: There is no option via a provided control panel to add this, it's a basic package I purchased
I know this post answers it but there are no extra comments and I'd like to know if it's the best way:
[way to redirect page to www using virtual host configuration in sites-available for apache2?](https://serverfault.com/questions/276832/way-to-redirect-page-to-www-using-virtual-host-configuration-in-sites-available-f)
Thanks | 2011/06/23 | [
"https://serverfault.com/questions/283663",
"https://serverfault.com",
"https://serverfault.com/users/85543/"
]
| To get DNS resolution to work, you need to have an A record for 'example.com', not just 'www.example.com'. Once that's there, what you've done so far will probably work. This sounds like an DNS issue so far. | To answer the second part of your question. The answer you link to is indeed a good example of doing the redirect. The first RewriteCond may not be required if you're not using SSL, but it should not do any harm. |
22,769,480 | I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
```
import java.util.*;
public class nextLineArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
public static String bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
}
```
When I try to return the sorted array to the main method it gives me the following error on the return line:
```
Incompatible Types
```
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
```
[Ljava.lang.String;@6d782f7c
``` | 2014/03/31 | [
"https://Stackoverflow.com/questions/22769480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3385542/"
]
| Take a look at the method
```
public static String bubbleSortDesc(String[] names)
```
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck. | public static String bubbleSortDesc(String[] names)
should be
public static String[] bubbleSortDesc(String[] names)
and also declare descSort as String array.
Also you are just printing the array objects. This will not print the list for you. You have iterate over the array.
Include this in you code:
```
for (String name:names)
{
System.out.println(name);
}
```
Do the same for descSort too.... |
22,769,480 | I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
```
import java.util.*;
public class nextLineArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
public static String bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
}
```
When I try to return the sorted array to the main method it gives me the following error on the return line:
```
Incompatible Types
```
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
```
[Ljava.lang.String;@6d782f7c
``` | 2014/03/31 | [
"https://Stackoverflow.com/questions/22769480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3385542/"
]
| Take a look at the method
```
public static String bubbleSortDesc(String[] names)
```
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck. | There are 2 points to fix. First you should return String array
```
public static String[] bubbleSortDesc(String[] names)
```
and therefore you should define it like this:
```
String descSort[];
``` |
22,769,480 | I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
```
import java.util.*;
public class nextLineArray
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
public static String bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
}
```
When I try to return the sorted array to the main method it gives me the following error on the return line:
```
Incompatible Types
```
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
```
[Ljava.lang.String;@6d782f7c
``` | 2014/03/31 | [
"https://Stackoverflow.com/questions/22769480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3385542/"
]
| Take a look at the method
```
public static String bubbleSortDesc(String[] names)
```
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck. | You can fix your print command by changing it to the following:
```
System.out.println("Names listed sorted in descending order (via BubbleSort): "+ java.util.Arrays.deepToString(descSort));
```
If you want the nitty gritty, descSort is a String[]. In Java when you convert String[] into a String it gives you that crazy string representation. You have to instead converte each entry in the array to a String individually. Fortunately the deepToString method will do that for you. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| First and foremost, **you don't need to correct every mistake**. Focusing on his pronunciation is likely causing you to miss some of the message he is trying to communicate to you.
If your manager interacts with other English-speaking professionals, you would be doing him a favor by helping him learn to pronounce things correctly. Pronounce things correctly yourself, even if he just pronounced it incorrectly in the previous sentence. It will be subtle, but over time it might work. **Of course, you need to be absolutely sure your pronunciation is correct, too.**
If your boss thinks he's right and you're not, your response might be something along the lines of, *"Oh? I've always pronounced it this way. Let me go check it out and see if I've been doing it wrong."* Then you can double check and let him know what you found.
In the end, it's not the end of the world to mispronounce things, except when the mistake could lead to an entirely different understanding of the speaker's message. In that case, it's good to repeat back what you heard, so he knows you got his message. | It's less important how he pronounces it then it is that you understand him. Lots of people have lots of different accents. There is no reason I can think of for a person to mispronounce on purpose.
So I would just pronounce the word/s correctly as I know them. I live in a country where my accent is very different, over time my accent has changed a bit, but it wasn't a conscious change, just the natural one that comes from your environment. In any case it has never really impacted on my ability to communicate in English which is the norm for technical discussions.
If I tried to imitate their accents when talking to them, they would probably think I'm trying to be funny. As far as which pronunciation is correct, mine is in most places. But in their country theirs is, so it's relative to the situation. The important thing is we're mutually intelligible. The native language here does not have all the same sounds as English, so for them to pronounce my way would be very difficult for some. Much as I will always speak their language with an accent. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| As long as you are not gratuitously using the words, you should always aim at correct pronunciation. Knowingly imitating an incorrect pronunciation is dishonorable and groveling behavior. Correct behavior is to pronounce words correctly and ignore other people who may be pronouncing the word incorrectly.
The only thing to avoid would be unnecessarily using a word you know to be pronounced incorrectly by someone else. Repeatedly or unnecessarily speaking such a word could be construed as an attempt to humiliate the other person. Therefore, you should only use the word when absolutely necessary and avoid using such a word needlessly. | First and foremost, **you don't need to correct every mistake**. Focusing on his pronunciation is likely causing you to miss some of the message he is trying to communicate to you.
If your manager interacts with other English-speaking professionals, you would be doing him a favor by helping him learn to pronounce things correctly. Pronounce things correctly yourself, even if he just pronounced it incorrectly in the previous sentence. It will be subtle, but over time it might work. **Of course, you need to be absolutely sure your pronunciation is correct, too.**
If your boss thinks he's right and you're not, your response might be something along the lines of, *"Oh? I've always pronounced it this way. Let me go check it out and see if I've been doing it wrong."* Then you can double check and let him know what you found.
In the end, it's not the end of the world to mispronounce things, except when the mistake could lead to an entirely different understanding of the speaker's message. In that case, it's good to repeat back what you heard, so he knows you got his message. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| First and foremost, **you don't need to correct every mistake**. Focusing on his pronunciation is likely causing you to miss some of the message he is trying to communicate to you.
If your manager interacts with other English-speaking professionals, you would be doing him a favor by helping him learn to pronounce things correctly. Pronounce things correctly yourself, even if he just pronounced it incorrectly in the previous sentence. It will be subtle, but over time it might work. **Of course, you need to be absolutely sure your pronunciation is correct, too.**
If your boss thinks he's right and you're not, your response might be something along the lines of, *"Oh? I've always pronounced it this way. Let me go check it out and see if I've been doing it wrong."* Then you can double check and let him know what you found.
In the end, it's not the end of the world to mispronounce things, except when the mistake could lead to an entirely different understanding of the speaker's message. In that case, it's good to repeat back what you heard, so he knows you got his message. | This answer becomes trivial if you stop thinking of him pronouncing it **wrongly** and instead that he is pronouncing it **in his accent** which doesn't have to be the same as yours.
I have Australian friends who say "dahta" and "dahtabayse" while I say "dayta" and "daytabase". I don't adjust my pronunciation to match theirs. They don't take my pronunciation as a correction to them. And there are plenty of opinions about how to say GIF, SQL, etc -- tech terms don't always have single pronunciations.
You worry that if he says "do we have the dahta?" and you say "yes, we have tons of dayta" that he'll feel rebuked. Why should he? Different doesn't mean wrong. If you feel funny, take refuge in pronouns (eg it, them) or substitutes (the language, the framework, the platform, the library.) If it's been that recent since your boss said the word, it's available as an easy referent using these sorts of words.
The only reason to change your own pronunciation is if everyone on your team and in your area says it differently than you (and the inventors, and possibly the majority of the internet) and you are starting to feel bad, not as someone correcting others, but as someone who isn't acting according to the norms of your group. You haven't provided any examples so it's hard to know if that needs to happen in your case. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| First and foremost, **you don't need to correct every mistake**. Focusing on his pronunciation is likely causing you to miss some of the message he is trying to communicate to you.
If your manager interacts with other English-speaking professionals, you would be doing him a favor by helping him learn to pronounce things correctly. Pronounce things correctly yourself, even if he just pronounced it incorrectly in the previous sentence. It will be subtle, but over time it might work. **Of course, you need to be absolutely sure your pronunciation is correct, too.**
If your boss thinks he's right and you're not, your response might be something along the lines of, *"Oh? I've always pronounced it this way. Let me go check it out and see if I've been doing it wrong."* Then you can double check and let him know what you found.
In the end, it's not the end of the world to mispronounce things, except when the mistake could lead to an entirely different understanding of the speaker's message. In that case, it's good to repeat back what you heard, so he knows you got his message. | I'm going to answer this question as the person who mispronounces words. I'm a native English speaker but have started picking up French late in life. I can follow a conversation and speak short sentences. I slaughter the pronunciation of words; a native or fluent speaker can understand me though.
I personally prefer if native French speakers use proper pronunciation around me. **Foremost because I couldn't understand them if they used my own mispronunciation.** A secondary reason is maybe, through some odd osmosis or asking outright, I'll pick up the correct pronunciation over time. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| As long as you are not gratuitously using the words, you should always aim at correct pronunciation. Knowingly imitating an incorrect pronunciation is dishonorable and groveling behavior. Correct behavior is to pronounce words correctly and ignore other people who may be pronouncing the word incorrectly.
The only thing to avoid would be unnecessarily using a word you know to be pronounced incorrectly by someone else. Repeatedly or unnecessarily speaking such a word could be construed as an attempt to humiliate the other person. Therefore, you should only use the word when absolutely necessary and avoid using such a word needlessly. | It's less important how he pronounces it then it is that you understand him. Lots of people have lots of different accents. There is no reason I can think of for a person to mispronounce on purpose.
So I would just pronounce the word/s correctly as I know them. I live in a country where my accent is very different, over time my accent has changed a bit, but it wasn't a conscious change, just the natural one that comes from your environment. In any case it has never really impacted on my ability to communicate in English which is the norm for technical discussions.
If I tried to imitate their accents when talking to them, they would probably think I'm trying to be funny. As far as which pronunciation is correct, mine is in most places. But in their country theirs is, so it's relative to the situation. The important thing is we're mutually intelligible. The native language here does not have all the same sounds as English, so for them to pronounce my way would be very difficult for some. Much as I will always speak their language with an accent. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| It's less important how he pronounces it then it is that you understand him. Lots of people have lots of different accents. There is no reason I can think of for a person to mispronounce on purpose.
So I would just pronounce the word/s correctly as I know them. I live in a country where my accent is very different, over time my accent has changed a bit, but it wasn't a conscious change, just the natural one that comes from your environment. In any case it has never really impacted on my ability to communicate in English which is the norm for technical discussions.
If I tried to imitate their accents when talking to them, they would probably think I'm trying to be funny. As far as which pronunciation is correct, mine is in most places. But in their country theirs is, so it's relative to the situation. The important thing is we're mutually intelligible. The native language here does not have all the same sounds as English, so for them to pronounce my way would be very difficult for some. Much as I will always speak their language with an accent. | I'm going to answer this question as the person who mispronounces words. I'm a native English speaker but have started picking up French late in life. I can follow a conversation and speak short sentences. I slaughter the pronunciation of words; a native or fluent speaker can understand me though.
I personally prefer if native French speakers use proper pronunciation around me. **Foremost because I couldn't understand them if they used my own mispronunciation.** A secondary reason is maybe, through some odd osmosis or asking outright, I'll pick up the correct pronunciation over time. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| As long as you are not gratuitously using the words, you should always aim at correct pronunciation. Knowingly imitating an incorrect pronunciation is dishonorable and groveling behavior. Correct behavior is to pronounce words correctly and ignore other people who may be pronouncing the word incorrectly.
The only thing to avoid would be unnecessarily using a word you know to be pronounced incorrectly by someone else. Repeatedly or unnecessarily speaking such a word could be construed as an attempt to humiliate the other person. Therefore, you should only use the word when absolutely necessary and avoid using such a word needlessly. | This answer becomes trivial if you stop thinking of him pronouncing it **wrongly** and instead that he is pronouncing it **in his accent** which doesn't have to be the same as yours.
I have Australian friends who say "dahta" and "dahtabayse" while I say "dayta" and "daytabase". I don't adjust my pronunciation to match theirs. They don't take my pronunciation as a correction to them. And there are plenty of opinions about how to say GIF, SQL, etc -- tech terms don't always have single pronunciations.
You worry that if he says "do we have the dahta?" and you say "yes, we have tons of dayta" that he'll feel rebuked. Why should he? Different doesn't mean wrong. If you feel funny, take refuge in pronouns (eg it, them) or substitutes (the language, the framework, the platform, the library.) If it's been that recent since your boss said the word, it's available as an easy referent using these sorts of words.
The only reason to change your own pronunciation is if everyone on your team and in your area says it differently than you (and the inventors, and possibly the majority of the internet) and you are starting to feel bad, not as someone correcting others, but as someone who isn't acting according to the norms of your group. You haven't provided any examples so it's hard to know if that needs to happen in your case. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| As long as you are not gratuitously using the words, you should always aim at correct pronunciation. Knowingly imitating an incorrect pronunciation is dishonorable and groveling behavior. Correct behavior is to pronounce words correctly and ignore other people who may be pronouncing the word incorrectly.
The only thing to avoid would be unnecessarily using a word you know to be pronounced incorrectly by someone else. Repeatedly or unnecessarily speaking such a word could be construed as an attempt to humiliate the other person. Therefore, you should only use the word when absolutely necessary and avoid using such a word needlessly. | I'm going to answer this question as the person who mispronounces words. I'm a native English speaker but have started picking up French late in life. I can follow a conversation and speak short sentences. I slaughter the pronunciation of words; a native or fluent speaker can understand me though.
I personally prefer if native French speakers use proper pronunciation around me. **Foremost because I couldn't understand them if they used my own mispronunciation.** A secondary reason is maybe, through some odd osmosis or asking outright, I'll pick up the correct pronunciation over time. |
56,875 | Say you are working in an office where English is not a native language for people but some English terms are used very often (e.g. an IT department). And your boss always pronounces English terms incorrectly.
The question. Is it appropriate to pronounce the terms correctly when speaking to the boss or one should use his wrong pronunciation for any reasons.
It seems to me a bit uncomfortable to use the fixed pronunciation just after his incorrect wording (right in the next sentence). He may find this offensive I think. He may think that I'm either too dumb to remember how it's pronounced after one second after his saying or I'm trying to teach him.
P.S. Trying to tell him how it's pronounced correctly is not an option. Please avoid this advice. Thank you. | 2015/10/31 | [
"https://workplace.stackexchange.com/questions/56875",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/5415/"
]
| This answer becomes trivial if you stop thinking of him pronouncing it **wrongly** and instead that he is pronouncing it **in his accent** which doesn't have to be the same as yours.
I have Australian friends who say "dahta" and "dahtabayse" while I say "dayta" and "daytabase". I don't adjust my pronunciation to match theirs. They don't take my pronunciation as a correction to them. And there are plenty of opinions about how to say GIF, SQL, etc -- tech terms don't always have single pronunciations.
You worry that if he says "do we have the dahta?" and you say "yes, we have tons of dayta" that he'll feel rebuked. Why should he? Different doesn't mean wrong. If you feel funny, take refuge in pronouns (eg it, them) or substitutes (the language, the framework, the platform, the library.) If it's been that recent since your boss said the word, it's available as an easy referent using these sorts of words.
The only reason to change your own pronunciation is if everyone on your team and in your area says it differently than you (and the inventors, and possibly the majority of the internet) and you are starting to feel bad, not as someone correcting others, but as someone who isn't acting according to the norms of your group. You haven't provided any examples so it's hard to know if that needs to happen in your case. | I'm going to answer this question as the person who mispronounces words. I'm a native English speaker but have started picking up French late in life. I can follow a conversation and speak short sentences. I slaughter the pronunciation of words; a native or fluent speaker can understand me though.
I personally prefer if native French speakers use proper pronunciation around me. **Foremost because I couldn't understand them if they used my own mispronunciation.** A secondary reason is maybe, through some odd osmosis or asking outright, I'll pick up the correct pronunciation over time. |
16,926,578 | I'm trying to create a chat for a site and I'm wondering if the db solution is the best one in case of a large amount of users.
In case the db is an acceptable solution I would like to know which is the best way to design it:
1. Is one table enough to store all the messages from all the users? Do I have to store each message everytime a user send it (like a simple "hello" in one record)?
2. Do I have to create a separate tables for each chat?
Obviously assuming that the indexing and the partitioning are made.
I'm scared about the performance at this stage (db level). Then I can concentrate better to the middleware section and manage it there. | 2013/06/04 | [
"https://Stackoverflow.com/questions/16926578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453201/"
]
| MySQL is not ment for realtime
------------------------------
MySQL is clearly not the best solution for a chat: You have no reason to work on years of backlog to get the most current messages, nor do you want to fire a query per second for every active user. The overhead of a relational database is not to be ignored.
Check out redis
---------------
I would go with [redis](http://try.redis.io/): It is an advanced key-value storage with capabilities of realtime interaction (PUB/SUB), automatic expire, and it is definitely faster than MySQL when it comes to loads of simple data.
**Edit:** Yes, it has all it´s data in ram. A Gb of ram would be enough for about every book in every libary of the world. That said, MySql also uses ram caching (query caching). And redis is ACID. (Oversimplified: You can enable saving to disk.)
MySql hints, if you stick to it
-------------------------------
If you yet decide to go with MySQL, you will have to write every single line into the DB for others to be visible. More explicit, you need a commit on every message. Make sure that you have some sort of cleanup mechanism, e.g. a cronjob moving all messages older than a day into some archive-tables.
cache!
------
Imagine 100 users in your room, each checking every 3 seconds for new messages. 300 queries per second? (Ok, decent servers can handle this, but you asked for a good solution) Go another way: Have a memcached /redis-saved flag "Last message id". Change it every time someone writes something to the chat. Now make the client submit it´s last-known message id. If you´ve got a hit, exit immediately even without MySql starting up. If you are really good, you can make PHP even make to return the appropriate ETag.
Long polls
----------
As it comes to the frontend client: **Do not fire a reload or ajax request every n seconds!** Inform yourself about Websocket and **long polls**. That is a technique where the browser opens a site that will not immediately return a result, but will keep the connection open untill there is something to report (or timeout occurs)
Edit: OP´s comment asking what programming language to use
----------------------------------------------------------
That depends on your knowledge. I would go with PHP and redis, but that is because I know them well. If you prefer Java, use it. If you have no preference: Java is more versatile, php is easier to start learning. There is no objective one-size-fits-all-answer. | use NOSQL as it store data as a file it is good for large database |
16,926,578 | I'm trying to create a chat for a site and I'm wondering if the db solution is the best one in case of a large amount of users.
In case the db is an acceptable solution I would like to know which is the best way to design it:
1. Is one table enough to store all the messages from all the users? Do I have to store each message everytime a user send it (like a simple "hello" in one record)?
2. Do I have to create a separate tables for each chat?
Obviously assuming that the indexing and the partitioning are made.
I'm scared about the performance at this stage (db level). Then I can concentrate better to the middleware section and manage it there. | 2013/06/04 | [
"https://Stackoverflow.com/questions/16926578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453201/"
]
| MySQL is not ment for realtime
------------------------------
MySQL is clearly not the best solution for a chat: You have no reason to work on years of backlog to get the most current messages, nor do you want to fire a query per second for every active user. The overhead of a relational database is not to be ignored.
Check out redis
---------------
I would go with [redis](http://try.redis.io/): It is an advanced key-value storage with capabilities of realtime interaction (PUB/SUB), automatic expire, and it is definitely faster than MySQL when it comes to loads of simple data.
**Edit:** Yes, it has all it´s data in ram. A Gb of ram would be enough for about every book in every libary of the world. That said, MySql also uses ram caching (query caching). And redis is ACID. (Oversimplified: You can enable saving to disk.)
MySql hints, if you stick to it
-------------------------------
If you yet decide to go with MySQL, you will have to write every single line into the DB for others to be visible. More explicit, you need a commit on every message. Make sure that you have some sort of cleanup mechanism, e.g. a cronjob moving all messages older than a day into some archive-tables.
cache!
------
Imagine 100 users in your room, each checking every 3 seconds for new messages. 300 queries per second? (Ok, decent servers can handle this, but you asked for a good solution) Go another way: Have a memcached /redis-saved flag "Last message id". Change it every time someone writes something to the chat. Now make the client submit it´s last-known message id. If you´ve got a hit, exit immediately even without MySql starting up. If you are really good, you can make PHP even make to return the appropriate ETag.
Long polls
----------
As it comes to the frontend client: **Do not fire a reload or ajax request every n seconds!** Inform yourself about Websocket and **long polls**. That is a technique where the browser opens a site that will not immediately return a result, but will keep the connection open untill there is something to report (or timeout occurs)
Edit: OP´s comment asking what programming language to use
----------------------------------------------------------
That depends on your knowledge. I would go with PHP and redis, but that is because I know them well. If you prefer Java, use it. If you have no preference: Java is more versatile, php is easier to start learning. There is no objective one-size-fits-all-answer. | Determine what features you want. A few I can think of right off that might make a difference:
* Do you want to store the stream at all? (If not, then your DB needs are minimal.)
* How much of the stream do you want accessible to users? One day? A week? All of it? (You can offload messages periodically to maintain history for yourself, but also keep the publicly-accessible DB small.)
* How many messages per minute / hour / day can a user post? (Hint: not as many as they want)
* Do you want threading, or just one long stream that everyone can see? (Increases complexity)
* Do you want users to be able to send private messages? (Increases complexity)
* How often is the chat refreshed in the browser? (The more it's refreshed, the larger the load on the server) |
4,467 | We often hear that in practice, not enough data of sufficient quality, consistency, recency, etc. is available for feeding into mathematical optimization models. Example: my university wanted to plan/optimize their weekly timetable using an integer program, but they did not know the number of rooms (let alone capacities, availabilities, equipment, location, etc.), they did not know the preferences of professors, nor which courses they actually taught (the system listed them as "responsible" for a course which did not imply that they were actually teaching that course!); they didn't know the number of students to expect in a course. I could contribute a lot of such stories.
Now, many companies (truthfully) claim that they collect data. E.g., sensor data from production, temperatures, filling rates, number of faulty products per hour, web clicks, customer orders, energy prices, etc., etc. I can't really grasp what makes we reject such data as "suitable" for optimization, and I am looking for a definition of what "different kind of data" needs to be collected in order to feed a typical mathematical program for e.g., timetabling, production planning, facility layout, or designing tariff zones. I thought for a while that the notion I am looking for is "actionable", but this doesn't capture it. Ideally, I would like to contrast this "optimization data" to data that is typically fed into machine learning algorithms (which extrapolate, cluster, predict, find trends, anomalies, patterns, etc.).
How would you call the number of students in a course, the availabilities of teachers, the capacities of rooms, the data that a course belongs to a certain curriculum? | 2020/06/30 | [
"https://or.stackexchange.com/questions/4467",
"https://or.stackexchange.com",
"https://or.stackexchange.com/users/354/"
]
| I would call them decision-relevant data, because most optimization problems in practice help people do decisions better, which they already do in a heuristic fashion. This puts the focus on the decision and what is needed to effectively make this decision.
Alternatives would be system-describing data/system-boundary data, because the data defines the boundaries of the feasible states of the system/the boundaries of feasible decision.
On the other hand the data in machine learning i would call historical observational data, because you often have observable states of the system from the past.
I find it difficult to draw a line, that this data is for optimization and that data is for machine learning, because often data can be used for both.
In your example with the timetable for the university courses you could for example not have the capacity of each room, but instead the average number of students per room for each day in the last year. This data would at a first glance be rather machine learning data, but you could use it to derive an estimate for the capacity to feed it to your optimization model.
I agree that pure observable data is often useless for optimization problems, because you only observe feasible states, but have no data on how much you can deviate from these and what are the effects on the deviation and optimizing is basically putting the system in an unseen state than before. | I think, answers provided so far are great. When talking to professionals in the field, I second Nikos and call them "parameters" and cross my fingers they know the difference between a parameter and a variable (which is a bleeding wound between the OR profession in Industrial Engineering and OR profession in Business Administration). On the other hand, practitioners usually have a hugely different understanding of what "data" mean. They call every number or descriptive text gathered "data," which is hard to argue as they are right by the definition of *data* being like: "Come, come, whoever you are [Mevlana Jelaluddin Rumi]."
To kindly express the notion in my mind "I cannot do this so-called optimization stuff without you giving me the right data, dude!" I would just tell the practitioner: "I need the *problem data*" and define what I mean by it. Have I been successful so far? I don't know, I am only 30... I need to collect more data to answer whether this was a successful approach :) |
4,467 | We often hear that in practice, not enough data of sufficient quality, consistency, recency, etc. is available for feeding into mathematical optimization models. Example: my university wanted to plan/optimize their weekly timetable using an integer program, but they did not know the number of rooms (let alone capacities, availabilities, equipment, location, etc.), they did not know the preferences of professors, nor which courses they actually taught (the system listed them as "responsible" for a course which did not imply that they were actually teaching that course!); they didn't know the number of students to expect in a course. I could contribute a lot of such stories.
Now, many companies (truthfully) claim that they collect data. E.g., sensor data from production, temperatures, filling rates, number of faulty products per hour, web clicks, customer orders, energy prices, etc., etc. I can't really grasp what makes we reject such data as "suitable" for optimization, and I am looking for a definition of what "different kind of data" needs to be collected in order to feed a typical mathematical program for e.g., timetabling, production planning, facility layout, or designing tariff zones. I thought for a while that the notion I am looking for is "actionable", but this doesn't capture it. Ideally, I would like to contrast this "optimization data" to data that is typically fed into machine learning algorithms (which extrapolate, cluster, predict, find trends, anomalies, patterns, etc.).
How would you call the number of students in a course, the availabilities of teachers, the capacities of rooms, the data that a course belongs to a certain curriculum? | 2020/06/30 | [
"https://or.stackexchange.com/questions/4467",
"https://or.stackexchange.com",
"https://or.stackexchange.com/users/354/"
]
| I would just call it "planning data". I think it might be easier to convince an administrator that "planning data" needs to be recorded/captured than to sell them on "<insert techno-jargon phrase here> data". Administrators grasp what planning is (whether or not they are adept at doing it), and at some visceral level they probably realize that *not* planning is bad (which might make them a bit more inclined to make an effort to collect the data). If "planning data" does not do much to distinguish this sort of data from other sorts (salary data, student/faculty ratio, ...), perhaps that's a good thing. They already understand the relevance of the other data, and that it needs to be collected, so by association they might realize this data is also important. | I think, answers provided so far are great. When talking to professionals in the field, I second Nikos and call them "parameters" and cross my fingers they know the difference between a parameter and a variable (which is a bleeding wound between the OR profession in Industrial Engineering and OR profession in Business Administration). On the other hand, practitioners usually have a hugely different understanding of what "data" mean. They call every number or descriptive text gathered "data," which is hard to argue as they are right by the definition of *data* being like: "Come, come, whoever you are [Mevlana Jelaluddin Rumi]."
To kindly express the notion in my mind "I cannot do this so-called optimization stuff without you giving me the right data, dude!" I would just tell the practitioner: "I need the *problem data*" and define what I mean by it. Have I been successful so far? I don't know, I am only 30... I need to collect more data to answer whether this was a successful approach :) |
4,467 | We often hear that in practice, not enough data of sufficient quality, consistency, recency, etc. is available for feeding into mathematical optimization models. Example: my university wanted to plan/optimize their weekly timetable using an integer program, but they did not know the number of rooms (let alone capacities, availabilities, equipment, location, etc.), they did not know the preferences of professors, nor which courses they actually taught (the system listed them as "responsible" for a course which did not imply that they were actually teaching that course!); they didn't know the number of students to expect in a course. I could contribute a lot of such stories.
Now, many companies (truthfully) claim that they collect data. E.g., sensor data from production, temperatures, filling rates, number of faulty products per hour, web clicks, customer orders, energy prices, etc., etc. I can't really grasp what makes we reject such data as "suitable" for optimization, and I am looking for a definition of what "different kind of data" needs to be collected in order to feed a typical mathematical program for e.g., timetabling, production planning, facility layout, or designing tariff zones. I thought for a while that the notion I am looking for is "actionable", but this doesn't capture it. Ideally, I would like to contrast this "optimization data" to data that is typically fed into machine learning algorithms (which extrapolate, cluster, predict, find trends, anomalies, patterns, etc.).
How would you call the number of students in a course, the availabilities of teachers, the capacities of rooms, the data that a course belongs to a certain curriculum? | 2020/06/30 | [
"https://or.stackexchange.com/questions/4467",
"https://or.stackexchange.com",
"https://or.stackexchange.com/users/354/"
]
| Adhering to the rules of encapsulation, I would simply call it "parameters". If we're thinking of an optimisation model and, as you said, what changes is the number of things (number of students, number of classrooms, a table with the teachers' schedule, etc.), that's what we call usually parameters in optimisation modelling so I don't see a reason to use a different term.
If we wanted to make the name more descriptive, I would attach a problem-specific prefix there, e.g., "planning parameters".
I like this term because it indicates that the math would be the same (assuming that's the case here) even if those numbers change.
I would avoid the word "data" because it's too broad - we also use "data" to formulate the math. | I think, answers provided so far are great. When talking to professionals in the field, I second Nikos and call them "parameters" and cross my fingers they know the difference between a parameter and a variable (which is a bleeding wound between the OR profession in Industrial Engineering and OR profession in Business Administration). On the other hand, practitioners usually have a hugely different understanding of what "data" mean. They call every number or descriptive text gathered "data," which is hard to argue as they are right by the definition of *data* being like: "Come, come, whoever you are [Mevlana Jelaluddin Rumi]."
To kindly express the notion in my mind "I cannot do this so-called optimization stuff without you giving me the right data, dude!" I would just tell the practitioner: "I need the *problem data*" and define what I mean by it. Have I been successful so far? I don't know, I am only 30... I need to collect more data to answer whether this was a successful approach :) |
20,438,072 | I want to takeout the keyboard when the user clicks on the background or any other item on the view.
I found out that the following code will take it off. But where should i add it.
```
[self.view endEditing:YES];
```
All my UI components are created programatically. | 2013/12/07 | [
"https://Stackoverflow.com/questions/20438072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1377826/"
]
| It's super simple, you only need to implement this code in your .m file:
```
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
```
This will do. | Use below code
```
UITapGestureRecognizer *recognizer;
recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:nil];
recognizer.numberOfTouchesRequired=1;
[self.view addGestureRecognizer:recognizer];
recognizer.delegate = self;
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
[userName resignFirstResponder];
[passWord resignFirstResponder];
return NO;
}
``` |
61,077,570 | I have a github account with say a username 'abc'. If I create a repository in it and clone it on my system as
`git clone https://github.com/abc/demo.git` it gets cloned.
If I login into my another github account with username say 'xyz' and create a repository in it and if I try to clone the repository on my same system as
`git clone https://github.com/xyz/demo.git` it gives fatal error such as
```
Cloning into 'demo'...
remote: Repository not found.
fatal: repository 'https://github.com/instructor-git/demo.git/' not found
```
I am new to git and not able to diagnose the problem what wrong I am doing. Please help. | 2020/04/07 | [
"https://Stackoverflow.com/questions/61077570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3588025/"
]
| `/xyz/` in the url is not enough to tell which user is cloning. you need to be explicit about it: `xyz@`:
```
$ git clone https://[email protected]/xyz/demo.git
``` | There are solutions using ssh.
I faced the same problem and the only solution I found is:
1. to generate an access token with the right 'repo'
2. Use it in the clone url
`git clone https://[email protected]/xyz/demo.git` |
6,276,346 | I want to print the array index for some purpose. Can anybody tell me about this ? | 2011/06/08 | [
"https://Stackoverflow.com/questions/6276346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/762267/"
]
| Get the first index of an elemnt:
```
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
echo $key;
```
For all elemnts
```
foreach($array as $key => $value){
echo "{$key} => {$value}\n";
}
```
will output
```
0 => blue
1 => red
2 => green
3 => red
```
All keys:
```
echo implode(', ',array_keys($array));
```
will output
```
0, 1, 2, 3
``` | not sure what you mean with this question but you could try
```
echo "<pre>";
print_r ($arr);
echo "</pre>";
```
that way you'll see your entire array including all the indexes |
6,276,346 | I want to print the array index for some purpose. Can anybody tell me about this ? | 2011/06/08 | [
"https://Stackoverflow.com/questions/6276346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/762267/"
]
| Get the first index of an elemnt:
```
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
echo $key;
```
For all elemnts
```
foreach($array as $key => $value){
echo "{$key} => {$value}\n";
}
```
will output
```
0 => blue
1 => red
2 => green
3 => red
```
All keys:
```
echo implode(', ',array_keys($array));
```
will output
```
0, 1, 2, 3
``` | if you mean the keys of the array:
```
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
//result
Array
(
[0] => 0
[1] => color
)
```
This will provide an array of the keys |
23,411,896 | I would like to put an arrow image (png) centered under my active item menu instead of having my actual blue border-line. I tried to modified my css with no luck, the image doesn't appear. do you know what I doing wrong ?
**My CSS** :
```
#cssmenu ul {
margin: 0;
padding: 0;
font-size: 12pt;
font-weight: bold;
background: #94adc1;
font-family: Arial, Helvetica, sans-serif;
border-bottom: 1px solid #f2f1f2;
zoom: 1;
text-align:center;
}
#cssmenu ul:before {
content: '';
display: block;
}
#cssmenu ul:after {
content: '';
display: table;
clear: both;
}
#cssmenu li {
float: left;
margin: 0 auto;
padding: 0 4px;
list-style: none;
}
#cssmenu li a {
display: block;
float: left;
color: #123b59;
text-decoration: none;
font-weight: bold;
padding: 10px 20px 7px 20px;
border-bottom: 3px solid transparent;
}
#cssmenu li a:hover {
content: url("images/arrowmenunav.png");
/*color: #6c8cb5;
border-bottom: 3px solid #00b8fd;*/
}
#cssmenu li.active a {
/*display: inline;
border-bottom: 3px solid #00b8fd;
float: left;
margin: 0;*/
content: url("images/arrowmenunav.png");
}
#cssmenu {
width: 100%;
position: fixed;
height:94px;
}
```
**My menu in HTML** :
```
<div id="cssmenu">
<ul id="list">
<li><a href="#home" >home</a></li>
<li><a href="#home2">home2</a></li>
<li><a href="#newsletter">newsletter</a></li>
</ul>
</div>
``` | 2014/05/01 | [
"https://Stackoverflow.com/questions/23411896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979974/"
]
| The first thing I can see is this line
```
#cssmenu li.active a {
content: url("images/arrowmenunav.png");
}
```
Should be this:
```
#cssmenu li.active a:after {
content: url("images/arrowmenunav.png");
}
```
**I've setup this jsfiddle to show it in a bit more detail** <http://jsfiddle.net/e3WEs/2/>
In this I've used a 20px by 20px placeholder image. The negative margin should be half of your image width (10px in this case) to centre align it to the parent element.
**Here is a version that will work in older browsers too (IE7 and below)**
<http://jsfiddle.net/e3WEs/3/> | Another option if you don't want to use :after. :after is pretty much not supported by old browsers if that concerns you.
<http://jsfiddle.net/f3SQx/>
Mark-up
```
<li><a href="#home">home</a>
<div class="active"></div>
</li>
```
CSS
```
.active {
position:absolute;
width:30px;
height:30px;
top:100%;
margin-left:32%;
content: url("images/arrowmenunav.png");
}
``` |
23,411,896 | I would like to put an arrow image (png) centered under my active item menu instead of having my actual blue border-line. I tried to modified my css with no luck, the image doesn't appear. do you know what I doing wrong ?
**My CSS** :
```
#cssmenu ul {
margin: 0;
padding: 0;
font-size: 12pt;
font-weight: bold;
background: #94adc1;
font-family: Arial, Helvetica, sans-serif;
border-bottom: 1px solid #f2f1f2;
zoom: 1;
text-align:center;
}
#cssmenu ul:before {
content: '';
display: block;
}
#cssmenu ul:after {
content: '';
display: table;
clear: both;
}
#cssmenu li {
float: left;
margin: 0 auto;
padding: 0 4px;
list-style: none;
}
#cssmenu li a {
display: block;
float: left;
color: #123b59;
text-decoration: none;
font-weight: bold;
padding: 10px 20px 7px 20px;
border-bottom: 3px solid transparent;
}
#cssmenu li a:hover {
content: url("images/arrowmenunav.png");
/*color: #6c8cb5;
border-bottom: 3px solid #00b8fd;*/
}
#cssmenu li.active a {
/*display: inline;
border-bottom: 3px solid #00b8fd;
float: left;
margin: 0;*/
content: url("images/arrowmenunav.png");
}
#cssmenu {
width: 100%;
position: fixed;
height:94px;
}
```
**My menu in HTML** :
```
<div id="cssmenu">
<ul id="list">
<li><a href="#home" >home</a></li>
<li><a href="#home2">home2</a></li>
<li><a href="#newsletter">newsletter</a></li>
</ul>
</div>
``` | 2014/05/01 | [
"https://Stackoverflow.com/questions/23411896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979974/"
]
| The first thing I can see is this line
```
#cssmenu li.active a {
content: url("images/arrowmenunav.png");
}
```
Should be this:
```
#cssmenu li.active a:after {
content: url("images/arrowmenunav.png");
}
```
**I've setup this jsfiddle to show it in a bit more detail** <http://jsfiddle.net/e3WEs/2/>
In this I've used a 20px by 20px placeholder image. The negative margin should be half of your image width (10px in this case) to centre align it to the parent element.
**Here is a version that will work in older browsers too (IE7 and below)**
<http://jsfiddle.net/e3WEs/3/> | >
> Please add **z-index** values to **`#cssmenu li a`**
>
>
> hope this helped you
>
>
> |
38,613,452 | I need to pass both FormData and JSON object in an ajax call, but I get a 400 Bad Request error.
```
[artifact:mvn] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
[artifact:mvn] at [Source: java.io.PushbackInputStream@3c0d58f6; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
[artifact:mvn] at [Source: java.io.PushbackInputStream@3c0d58f6; line: 1, column: 3]
```
JS:
```
var formData = new FormData(form[0]);
//form JSON object
var jsonData = JSON.stringify(jcArray);
$.ajax({
type: "POST",
url: postDataUrl,
data: { formData:formData,jsonData:jsonData },
processData: false,
contentType: false,
async: false,
cache: false,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(data, textStatus, jqXHR) {
}
});
```
Controller:
```
@RequestMapping(value="/processSaveItem",method = RequestMethod.POST")
public @ResponseBody Map<String,String> processSaveItem(
@RequestBody XYZClass result[])
}
```
There is similar question, [jquery sending form data and a json object in an ajax call](https://stackoverflow.com/q/5938544/1793718) and I'm trying the same way.
How can I send both FormData and JSON object in a single ajax request? | 2016/07/27 | [
"https://Stackoverflow.com/questions/38613452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793718/"
]
| Java 6 usage is precisely what causes the issue. It seems that one of the required libraries supports Java 7/8 at minimum - there's no workaround, you might have to migrate to a newer Java version. | The error is caused by a dependency which has been compiled with Java 7, so it can't work with Java 6.
Having said that, reading from [Spring Boot's documentation](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#getting-started-system-requirements) about system requirements, it seems that Java 6 is supported provided that you perform some additional configuration.
About embedded servlet containers compatibility, in section [79.9 How to use Java 6](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-use-java-6) you should use Tomcat 7 or Jetty 8 and this is the gradle configuration:
>
> You can change the Tomcat version by setting the `tomcat.version`
> property:
>
>
>
> ```
> ext['tomcat.version'] = '7.0.59'
> dependencies {
> compile 'org.springframework.boot:spring-boot-starter-web'
> }
>
> ```
>
>
Obviously, if you can, you'd better to upgrade to newer JVM versions. |
38,613,452 | I need to pass both FormData and JSON object in an ajax call, but I get a 400 Bad Request error.
```
[artifact:mvn] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
[artifact:mvn] at [Source: java.io.PushbackInputStream@3c0d58f6; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
[artifact:mvn] at [Source: java.io.PushbackInputStream@3c0d58f6; line: 1, column: 3]
```
JS:
```
var formData = new FormData(form[0]);
//form JSON object
var jsonData = JSON.stringify(jcArray);
$.ajax({
type: "POST",
url: postDataUrl,
data: { formData:formData,jsonData:jsonData },
processData: false,
contentType: false,
async: false,
cache: false,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(data, textStatus, jqXHR) {
}
});
```
Controller:
```
@RequestMapping(value="/processSaveItem",method = RequestMethod.POST")
public @ResponseBody Map<String,String> processSaveItem(
@RequestBody XYZClass result[])
}
```
There is similar question, [jquery sending form data and a json object in an ajax call](https://stackoverflow.com/q/5938544/1793718) and I'm trying the same way.
How can I send both FormData and JSON object in a single ajax request? | 2016/07/27 | [
"https://Stackoverflow.com/questions/38613452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793718/"
]
| Java 6 usage is precisely what causes the issue. It seems that one of the required libraries supports Java 7/8 at minimum - there's no workaround, you might have to migrate to a newer Java version. | The dependency management plugin that Spring Boot's Gradle plugin uses requires Java 7. This means that you'll have to build your application with Java 7 (or later), but you'll still be able to run it using Java 6. |
38,613,452 | I need to pass both FormData and JSON object in an ajax call, but I get a 400 Bad Request error.
```
[artifact:mvn] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
[artifact:mvn] at [Source: java.io.PushbackInputStream@3c0d58f6; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
[artifact:mvn] at [Source: java.io.PushbackInputStream@3c0d58f6; line: 1, column: 3]
```
JS:
```
var formData = new FormData(form[0]);
//form JSON object
var jsonData = JSON.stringify(jcArray);
$.ajax({
type: "POST",
url: postDataUrl,
data: { formData:formData,jsonData:jsonData },
processData: false,
contentType: false,
async: false,
cache: false,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(data, textStatus, jqXHR) {
}
});
```
Controller:
```
@RequestMapping(value="/processSaveItem",method = RequestMethod.POST")
public @ResponseBody Map<String,String> processSaveItem(
@RequestBody XYZClass result[])
}
```
There is similar question, [jquery sending form data and a json object in an ajax call](https://stackoverflow.com/q/5938544/1793718) and I'm trying the same way.
How can I send both FormData and JSON object in a single ajax request? | 2016/07/27 | [
"https://Stackoverflow.com/questions/38613452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793718/"
]
| The error is caused by a dependency which has been compiled with Java 7, so it can't work with Java 6.
Having said that, reading from [Spring Boot's documentation](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#getting-started-system-requirements) about system requirements, it seems that Java 6 is supported provided that you perform some additional configuration.
About embedded servlet containers compatibility, in section [79.9 How to use Java 6](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-use-java-6) you should use Tomcat 7 or Jetty 8 and this is the gradle configuration:
>
> You can change the Tomcat version by setting the `tomcat.version`
> property:
>
>
>
> ```
> ext['tomcat.version'] = '7.0.59'
> dependencies {
> compile 'org.springframework.boot:spring-boot-starter-web'
> }
>
> ```
>
>
Obviously, if you can, you'd better to upgrade to newer JVM versions. | The dependency management plugin that Spring Boot's Gradle plugin uses requires Java 7. This means that you'll have to build your application with Java 7 (or later), but you'll still be able to run it using Java 6. |
8,756 | I am having problems in accessing the address of a new contract generated within another contract acting as Factory.
My code:
```
contract Object {
string name;
function Object(String _name) {
name = _name
}
}
contract ObjectFactory {
function createObject(string name) returns (address objectAddress) {
return address(new Object(name));
}
}
```
when I compile and execute the method `createObject('')`, I expect to be returned the address of the new contract.
Instead, I receive the hash of the transaction.
I use Web3 to execute the function:
```
var address = web3.eth.contract(objectFactoryAbi)
.at(contractFactoryAddress)
.createObject("object", { gas: price, from: accountAddress });
```
I tried also to modify the function to store the address in an array, returning the length of the array, and then retrieve it at a later time, with the same results: always the transaction hash is returned.
Any light on this is welcome. | 2016/09/20 | [
"https://ethereum.stackexchange.com/questions/8756",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/4366/"
]
| Super high-level answer: all nodes, on the road from the changed node to the root, change. | Actually, the merkle tree in ethereum `reorg` the tree while `update` method called. And the subcall of `update` method is `insert` function.
That's to say, when we want to update a tree node's value, a new node will be created and insert to the `appropriate` position with specific key and the old node will be reserved to represent a historical state.
Here is a [Link](https://blog.ethereum.org/2015/11/15/merkling-in-ethereum/), which described the detail. |
34,484,845 | I have a spinning gear on my website displayed with this code:
```html
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<i class = "fa fa-cog fa-5x fa-spin"></i>
```
Personally, I think that the speed of the gear is too fast. Can I modify it with CSS? | 2015/12/27 | [
"https://Stackoverflow.com/questions/34484845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5661019/"
]
| Short answer
------------
Yes, you can. Replace the `.fa-spin` class on the icon with a new class using your own animation rule:
```css
.slow-spin {
-webkit-animation: fa-spin 6s infinite linear;
animation: fa-spin 6s infinite linear;
}
```
```html
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<i class = "fa fa-cog fa-5x slow-spin"></i>
```
Longer answer
-------------
If you look at the [`Font Awesome CSS file`](https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css), you'll see this rule for spinning animation:
```
.fa-spin {
-webkit-animation: fa-spin 2s infinite linear;
animation: fa-spin 2s infinite linear;
}
```
The rule for the `.fa-spin` class refers to the `fa-spin` keyframes:
```
@keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
```
You can use the same keyframes in a different class. For example, you can write the following rule for a class called `.slow-spin`:
```
.slow-spin {
-webkit-animation: fa-spin 6s infinite linear;
animation: fa-spin 6s infinite linear;
}
```
Now you can rotate HTML elements at the speed of your choosing. Instead of applying the class `.fa-spin` to an element, apply the `.slow-spin` class:
```
<i class = "fa fa-cog fa-5x slow-spin"></i>
``` | Similar to the Michael Laszlo's answer. This is what I use to make it faster for fa-refresh as the fa-spin by default is very slow.
```
.fa-spin {
-webkit-animation: fa-spin 0.75s infinite linear !important;
animation: fa-spin 0.75s infinite linear !important;
}
```
I use !important so that I control the specificity :) |
34,484,845 | I have a spinning gear on my website displayed with this code:
```html
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<i class = "fa fa-cog fa-5x fa-spin"></i>
```
Personally, I think that the speed of the gear is too fast. Can I modify it with CSS? | 2015/12/27 | [
"https://Stackoverflow.com/questions/34484845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5661019/"
]
| Short answer
------------
Yes, you can. Replace the `.fa-spin` class on the icon with a new class using your own animation rule:
```css
.slow-spin {
-webkit-animation: fa-spin 6s infinite linear;
animation: fa-spin 6s infinite linear;
}
```
```html
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<i class = "fa fa-cog fa-5x slow-spin"></i>
```
Longer answer
-------------
If you look at the [`Font Awesome CSS file`](https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css), you'll see this rule for spinning animation:
```
.fa-spin {
-webkit-animation: fa-spin 2s infinite linear;
animation: fa-spin 2s infinite linear;
}
```
The rule for the `.fa-spin` class refers to the `fa-spin` keyframes:
```
@keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
```
You can use the same keyframes in a different class. For example, you can write the following rule for a class called `.slow-spin`:
```
.slow-spin {
-webkit-animation: fa-spin 6s infinite linear;
animation: fa-spin 6s infinite linear;
}
```
Now you can rotate HTML elements at the speed of your choosing. Instead of applying the class `.fa-spin` to an element, apply the `.slow-spin` class:
```
<i class = "fa fa-cog fa-5x slow-spin"></i>
``` | Not necessary to use an own animation or class definition. The speed of any css animation can control by the [animation-duration](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-duration) css property. Simply use:
```
.fa-spin {
animation-duration: 3s; // or something else
}
```
As higher the value the lower the animation speed. |
34,484,845 | I have a spinning gear on my website displayed with this code:
```html
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<i class = "fa fa-cog fa-5x fa-spin"></i>
```
Personally, I think that the speed of the gear is too fast. Can I modify it with CSS? | 2015/12/27 | [
"https://Stackoverflow.com/questions/34484845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5661019/"
]
| Not necessary to use an own animation or class definition. The speed of any css animation can control by the [animation-duration](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-duration) css property. Simply use:
```
.fa-spin {
animation-duration: 3s; // or something else
}
```
As higher the value the lower the animation speed. | Similar to the Michael Laszlo's answer. This is what I use to make it faster for fa-refresh as the fa-spin by default is very slow.
```
.fa-spin {
-webkit-animation: fa-spin 0.75s infinite linear !important;
animation: fa-spin 0.75s infinite linear !important;
}
```
I use !important so that I control the specificity :) |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| You could use `\hphantom` for taking the required space for alignment:
```
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{enumerate}
\item $1 + 1 = 2$
\item $\hphantom{1+1}\mathllap{1} = 2 - 1$
\end{enumerate}
\end{document}
``` | I tried once (and was surprised that it actually work) to use `\item` inside `\intertext` of the nested `align` environment:
```
\begin{enumerate}
\item First point, blah
\begin{align}
a &= b+2 \\ %% not sure about whether those \\ are needed or not
\intertext{\item Second point, blah}
b &= c+3
\end{align}
\end{enumerate}
``` |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| ```
\documentclass[leqno]{report}
\usepackage{amsmath}
\begin{document}
\begin{flalign}
1 + 1 &= 2 &\\
1 &= 2 - 1
\end{flalign}
\end{document}
```
 | ```
\documentclass{article}
\usepackage[fleqn]{amsmath}
\begin{document}
\begin{flalign} % Displays all equation #'s in environment.
1 + 1 &= 2 \\
1 &= 2 - 1 &
\end{flalign}
------------------------------
\begin{flalign*}% Add the * if you want no equation #'s displayed.
1 + 1 &= 2 \\
1 &= 2 - 1 &
\end{flalign*}
------------------------------
\begin{flalign}
1 + 1 &= 2 \notag \\% \notag used if you want to specify equation #'s
% only for certain equations.
1 &= 2 - 1 \\
3 + 4 &= 7 \notag \\
4 &= 7 - 3 &
\end{flalign}
\end{document}
```
Results below:
 |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| ```
\usepackage{array}
\newenvironment{enumalign}
{\par\addvspace{\topsep}\setcounter{enumi}{0}
\noindent$\begin{array}{@{}r@{\hspace{\labelsep}}r@{}>{{}}l@{}}}
{\end{array}$\par\addvspace{\topsep}}
\newcommand{\eitem}{\stepcounter{enumi}\makebox[\labelwidth][r]{\theenumi.}&}
\begin{document}
\begin{enumalign}
\eitem 1+1&=2\\
\eitem 1&=2-1
\end{enumalign}
```
Remember to end the rows with `\\` | ```
\documentclass{article}
\usepackage[fleqn]{amsmath}
\begin{document}
\begin{flalign} % Displays all equation #'s in environment.
1 + 1 &= 2 \\
1 &= 2 - 1 &
\end{flalign}
------------------------------
\begin{flalign*}% Add the * if you want no equation #'s displayed.
1 + 1 &= 2 \\
1 &= 2 - 1 &
\end{flalign*}
------------------------------
\begin{flalign}
1 + 1 &= 2 \notag \\% \notag used if you want to specify equation #'s
% only for certain equations.
1 &= 2 - 1 \\
3 + 4 &= 7 \notag \\
4 &= 7 - 3 &
\end{flalign}
\end{document}
```
Results below:
 |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| You could use `\hphantom` for taking the required space for alignment:
```
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{enumerate}
\item $1 + 1 = 2$
\item $\hphantom{1+1}\mathllap{1} = 2 - 1$
\end{enumerate}
\end{document}
``` | ```
\documentclass{article}
\usepackage[fleqn]{amsmath}
\begin{document}
\begin{flalign} % Displays all equation #'s in environment.
1 + 1 &= 2 \\
1 &= 2 - 1 &
\end{flalign}
------------------------------
\begin{flalign*}% Add the * if you want no equation #'s displayed.
1 + 1 &= 2 \\
1 &= 2 - 1 &
\end{flalign*}
------------------------------
\begin{flalign}
1 + 1 &= 2 \notag \\% \notag used if you want to specify equation #'s
% only for certain equations.
1 &= 2 - 1 \\
3 + 4 &= 7 \notag \\
4 &= 7 - 3 &
\end{flalign}
\end{document}
```
Results below:
 |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| ```
\documentclass[leqno]{report}
\usepackage{amsmath}
\begin{document}
\begin{flalign}
1 + 1 &= 2 &\\
1 &= 2 - 1
\end{flalign}
\end{document}
```
 | I tried once (and was surprised that it actually work) to use `\item` inside `\intertext` of the nested `align` environment:
```
\begin{enumerate}
\item First point, blah
\begin{align}
a &= b+2 \\ %% not sure about whether those \\ are needed or not
\intertext{\item Second point, blah}
b &= c+3
\end{align}
\end{enumerate}
``` |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| Note: This is based very heavily on Stefan Kottwitz's answer; I've just used some macros to make it a little bit more flexible.
```
\documentclass{article}
\usepackage{mathtools}
\newcommand{\leftsidelength}{}
\newcommand{\leftside}[1]{\hphantom{\leftsidelength}\mathllap{#1}}
\begin{document}
\begin{enumerate}
\renewcommand{\leftsidelength}{1+1}
\item $\leftside{\leftsidelength} = 2$
\item $\leftside{1} = 2 - 1$
\end{enumerate}
\end{document}
```
Someone who knows what they're talking about may tell me that there's a much better way to do this, but it seems to work. More importantly, if there is more than one line, it eliminates typing redundancy for the "phantomized" longest line, which makes for a more robust setup.
The only missing component would be an automatic way to determine which left side is longest. | I tried once (and was surprised that it actually work) to use `\item` inside `\intertext` of the nested `align` environment:
```
\begin{enumerate}
\item First point, blah
\begin{align}
a &= b+2 \\ %% not sure about whether those \\ are needed or not
\intertext{\item Second point, blah}
b &= c+3
\end{align}
\end{enumerate}
``` |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| Note: This is based very heavily on Stefan Kottwitz's answer; I've just used some macros to make it a little bit more flexible.
```
\documentclass{article}
\usepackage{mathtools}
\newcommand{\leftsidelength}{}
\newcommand{\leftside}[1]{\hphantom{\leftsidelength}\mathllap{#1}}
\begin{document}
\begin{enumerate}
\renewcommand{\leftsidelength}{1+1}
\item $\leftside{\leftsidelength} = 2$
\item $\leftside{1} = 2 - 1$
\end{enumerate}
\end{document}
```
Someone who knows what they're talking about may tell me that there's a much better way to do this, but it seems to work. More importantly, if there is more than one line, it eliminates typing redundancy for the "phantomized" longest line, which makes for a more robust setup.
The only missing component would be an automatic way to determine which left side is longest. | ```
\documentclass{article}
\usepackage[fleqn]{amsmath}
\begin{document}
\begin{flalign} % Displays all equation #'s in environment.
1 + 1 &= 2 \\
1 &= 2 - 1 &
\end{flalign}
------------------------------
\begin{flalign*}% Add the * if you want no equation #'s displayed.
1 + 1 &= 2 \\
1 &= 2 - 1 &
\end{flalign*}
------------------------------
\begin{flalign}
1 + 1 &= 2 \notag \\% \notag used if you want to specify equation #'s
% only for certain equations.
1 &= 2 - 1 \\
3 + 4 &= 7 \notag \\
4 &= 7 - 3 &
\end{flalign}
\end{document}
```
Results below:
 |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| ```
\documentclass[leqno]{report}
\usepackage{amsmath}
\begin{document}
\begin{flalign}
1 + 1 &= 2 &\\
1 &= 2 - 1
\end{flalign}
\end{document}
```
 | You could use `\hphantom` for taking the required space for alignment:
```
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{enumerate}
\item $1 + 1 = 2$
\item $\hphantom{1+1}\mathllap{1} = 2 - 1$
\end{enumerate}
\end{document}
``` |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| You could use `\hphantom` for taking the required space for alignment:
```
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{enumerate}
\item $1 + 1 = 2$
\item $\hphantom{1+1}\mathllap{1} = 2 - 1$
\end{enumerate}
\end{document}
``` | Note: This is based very heavily on Stefan Kottwitz's answer; I've just used some macros to make it a little bit more flexible.
```
\documentclass{article}
\usepackage{mathtools}
\newcommand{\leftsidelength}{}
\newcommand{\leftside}[1]{\hphantom{\leftsidelength}\mathllap{#1}}
\begin{document}
\begin{enumerate}
\renewcommand{\leftsidelength}{1+1}
\item $\leftside{\leftsidelength} = 2$
\item $\leftside{1} = 2 - 1$
\end{enumerate}
\end{document}
```
Someone who knows what they're talking about may tell me that there's a much better way to do this, but it seems to work. More importantly, if there is more than one line, it eliminates typing redundancy for the "phantomized" longest line, which makes for a more robust setup.
The only missing component would be an automatic way to determine which left side is longest. |
31,048 | How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
``` | 2011/10/09 | [
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
]
| ```
\usepackage{array}
\newenvironment{enumalign}
{\par\addvspace{\topsep}\setcounter{enumi}{0}
\noindent$\begin{array}{@{}r@{\hspace{\labelsep}}r@{}>{{}}l@{}}}
{\end{array}$\par\addvspace{\topsep}}
\newcommand{\eitem}{\stepcounter{enumi}\makebox[\labelwidth][r]{\theenumi.}&}
\begin{document}
\begin{enumalign}
\eitem 1+1&=2\\
\eitem 1&=2-1
\end{enumalign}
```
Remember to end the rows with `\\` | You could use `\hphantom` for taking the required space for alignment:
```
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{enumerate}
\item $1 + 1 = 2$
\item $\hphantom{1+1}\mathllap{1} = 2 - 1$
\end{enumerate}
\end{document}
``` |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| Try `Environment.Exit(exitCode)`. | I have went though this situation in many cases I use Thread.CurrentThread.Abort()
and the process is closed. It seems that Application.Exit isn't hooking up properly with current thread. |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| This is an article which expands on the same train of thought you are going through: <http://www.dev102.com/2008/06/24/how-do-you-exit-your-net-application/>
Basically:
>
> * Environment.Exit - From MSDN: Terminates this process and gives the
> underlying operating system the
> specified exit code. This is the code
> to call when you are using console
> application.
> * Application.Exit - From MSDN: Informs all message pumps that they
> must terminate, and then closes all
> application windows after the messages
> have been processed. This is the code
> to use if you are have called
> Application.Run (WinForms
> applications), this method stops all
> running message loops on all threads
> and closes all windows of the
> application. There are some more
> issues about this method, read about
> it in the MSDN page.
>
>
>
Another discussion of this: [Link](https://web.archive.org/web/20201029173358/http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx)
This article points out a good tip:
You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
```
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are a WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Use this since we are a console app
System.Environment.Exit(1);
}
``` | Also ensure any threads running in your application have the IsBackground property set to true. Non-background threads will easily block the application from exiting. |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| Having had this problem recently (that Application.Exit was failing to correctly terminate message pumps for win-forms with Application.Run(new Form())), I discovered that if you are spawning new threads or starting background workers within the constructor, this will prevent Application.Exit from running.
Move all 'RunWorkerAsync' calls from the constructor to a form Load method:
```
public Form()
{
this.Worker.RunWorkerAsync();
}
```
Move to:
```
public void Form_Load(object sender, EventArgs e)
{
this.Worker.RunWorkerAsync();
}
``` | I have went though this situation in many cases I use Thread.CurrentThread.Abort()
and the process is closed. It seems that Application.Exit isn't hooking up properly with current thread. |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| I have went though this situation in many cases I use Thread.CurrentThread.Abort()
and the process is closed. It seems that Application.Exit isn't hooking up properly with current thread. | Is this application run (in the `Main` method) using `Application.Run()`? Otherwise, `Application.Exit()` won't work.
If you wrote your own `Main` method and you want to stop the application, you can only stop by returning from the `Main` method (or killing the process). |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| This is an article which expands on the same train of thought you are going through: <http://www.dev102.com/2008/06/24/how-do-you-exit-your-net-application/>
Basically:
>
> * Environment.Exit - From MSDN: Terminates this process and gives the
> underlying operating system the
> specified exit code. This is the code
> to call when you are using console
> application.
> * Application.Exit - From MSDN: Informs all message pumps that they
> must terminate, and then closes all
> application windows after the messages
> have been processed. This is the code
> to use if you are have called
> Application.Run (WinForms
> applications), this method stops all
> running message loops on all threads
> and closes all windows of the
> application. There are some more
> issues about this method, read about
> it in the MSDN page.
>
>
>
Another discussion of this: [Link](https://web.archive.org/web/20201029173358/http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx)
This article points out a good tip:
You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
```
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are a WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Use this since we are a console app
System.Environment.Exit(1);
}
``` | Try this :
in Program.cs file :
after **Application.Run(new form());**
add **Application.Exit();** |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| I have went though this situation in many cases I use Thread.CurrentThread.Abort()
and the process is closed. It seems that Application.Exit isn't hooking up properly with current thread. | ```
private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
Environment.Exit(0);
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
}
``` |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| Having had this problem recently (that Application.Exit was failing to correctly terminate message pumps for win-forms with Application.Run(new Form())), I discovered that if you are spawning new threads or starting background workers within the constructor, this will prevent Application.Exit from running.
Move all 'RunWorkerAsync' calls from the constructor to a form Load method:
```
public Form()
{
this.Worker.RunWorkerAsync();
}
```
Move to:
```
public void Form_Load(object sender, EventArgs e)
{
this.Worker.RunWorkerAsync();
}
``` | Is this application run (in the `Main` method) using `Application.Run()`? Otherwise, `Application.Exit()` won't work.
If you wrote your own `Main` method and you want to stop the application, you can only stop by returning from the `Main` method (or killing the process). |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| This is an article which expands on the same train of thought you are going through: <http://www.dev102.com/2008/06/24/how-do-you-exit-your-net-application/>
Basically:
>
> * Environment.Exit - From MSDN: Terminates this process and gives the
> underlying operating system the
> specified exit code. This is the code
> to call when you are using console
> application.
> * Application.Exit - From MSDN: Informs all message pumps that they
> must terminate, and then closes all
> application windows after the messages
> have been processed. This is the code
> to use if you are have called
> Application.Run (WinForms
> applications), this method stops all
> running message loops on all threads
> and closes all windows of the
> application. There are some more
> issues about this method, read about
> it in the MSDN page.
>
>
>
Another discussion of this: [Link](https://web.archive.org/web/20201029173358/http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx)
This article points out a good tip:
You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
```
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are a WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Use this since we are a console app
System.Environment.Exit(1);
}
``` | I have went though this situation in many cases I use Thread.CurrentThread.Abort()
and the process is closed. It seems that Application.Exit isn't hooking up properly with current thread. |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| I have went though this situation in many cases I use Thread.CurrentThread.Abort()
and the process is closed. It seems that Application.Exit isn't hooking up properly with current thread. | Try this :
in Program.cs file :
after **Application.Run(new form());**
add **Application.Exit();** |
554,408 | I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application. | 2009/02/16 | [
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
]
| Having had this problem recently (that Application.Exit was failing to correctly terminate message pumps for win-forms with Application.Run(new Form())), I discovered that if you are spawning new threads or starting background workers within the constructor, this will prevent Application.Exit from running.
Move all 'RunWorkerAsync' calls from the constructor to a form Load method:
```
public Form()
{
this.Worker.RunWorkerAsync();
}
```
Move to:
```
public void Form_Load(object sender, EventArgs e)
{
this.Worker.RunWorkerAsync();
}
``` | Make sure you have no Console.ReadLine(); in your app and Environment.Exit(1); will work and close your app. |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| Have you tried passing a filtered array to the ForEach. Something like this:
```swift
ForEach(userData.bookList.filter { return !$0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) { BookRow(book: book) }
}
```
**Update**
----------
As it turns out, it is indeed an ugly, ugly bug:
Instead of filtering the array, I just remove the ForEach all together when the switch is flipped, and replace it by a simple `Text("Nothing")` view. The result is the same, it takes 30 secs to do so!
```swift
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if self.userData.showWantsOnly {
Text("Nothing")
} else {
ForEach(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
}.navigationBarTitle(Text("Books"))
}
}
```
**Workaround**
--------------
I did find a workaround that works fast, but it requires some code refactoring. The "magic" happens by encapsulation. The workaround forces SwiftUI to discard the List completely, instead of removing one row at a time. It does so by using two separate lists in two separate encapsualted views: `Filtered` and `NotFiltered`. Below is a full demo with 3000 rows.
```swift
import SwiftUI
class UserData: ObservableObject {
@Published var showWantsOnly = false
@Published var bookList: [Book] = []
init() {
for _ in 0..<3001 {
bookList.append(Book())
}
}
}
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
VStack {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if userData.showWantsOnly {
Filtered()
} else {
NotFiltered()
}
}
}.navigationBarTitle(Text("Books"))
}
}
struct Filtered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList.filter { $0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct NotFiltered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct Book: Identifiable {
let id = UUID()
let own = Bool.random()
}
struct BookRow: View {
let book: Book
var body: some View {
Text("\(String(book.own)) \(book.id)")
}
}
struct BookDetail: View {
let book: Book
var body: some View {
Text("Detail for \(book.id)")
}
}
``` | I think we have to wait until SwiftUI List performance improves in subsequent beta releases. I’ve experienced the same lag when lists are filtered from a very large array (500+) down to very small ones. I created a simple test app to time the layout for a simple array with integer IDs and strings with Buttons to simply change which array is being rendered - same lag. |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| Have you tried passing a filtered array to the ForEach. Something like this:
```swift
ForEach(userData.bookList.filter { return !$0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) { BookRow(book: book) }
}
```
**Update**
----------
As it turns out, it is indeed an ugly, ugly bug:
Instead of filtering the array, I just remove the ForEach all together when the switch is flipped, and replace it by a simple `Text("Nothing")` view. The result is the same, it takes 30 secs to do so!
```swift
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if self.userData.showWantsOnly {
Text("Nothing")
} else {
ForEach(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
}.navigationBarTitle(Text("Books"))
}
}
```
**Workaround**
--------------
I did find a workaround that works fast, but it requires some code refactoring. The "magic" happens by encapsulation. The workaround forces SwiftUI to discard the List completely, instead of removing one row at a time. It does so by using two separate lists in two separate encapsualted views: `Filtered` and `NotFiltered`. Below is a full demo with 3000 rows.
```swift
import SwiftUI
class UserData: ObservableObject {
@Published var showWantsOnly = false
@Published var bookList: [Book] = []
init() {
for _ in 0..<3001 {
bookList.append(Book())
}
}
}
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
VStack {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if userData.showWantsOnly {
Filtered()
} else {
NotFiltered()
}
}
}.navigationBarTitle(Text("Books"))
}
}
struct Filtered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList.filter { $0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct NotFiltered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct Book: Identifiable {
let id = UUID()
let own = Bool.random()
}
struct BookRow: View {
let book: Book
var body: some View {
Text("\(String(book.own)) \(book.id)")
}
}
struct BookDetail: View {
let book: Book
var body: some View {
Text("Detail for \(book.id)")
}
}
``` | This code will work correctly provided that you initialize your class in the 'SceneDelegate' file as follows:
```
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var userData = UserData()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
contentView
.environmentObject(userData)
)
self.window = window
window.makeKeyAndVisible()
}
}
``` |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| Have you tried passing a filtered array to the ForEach. Something like this:
```swift
ForEach(userData.bookList.filter { return !$0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) { BookRow(book: book) }
}
```
**Update**
----------
As it turns out, it is indeed an ugly, ugly bug:
Instead of filtering the array, I just remove the ForEach all together when the switch is flipped, and replace it by a simple `Text("Nothing")` view. The result is the same, it takes 30 secs to do so!
```swift
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if self.userData.showWantsOnly {
Text("Nothing")
} else {
ForEach(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
}.navigationBarTitle(Text("Books"))
}
}
```
**Workaround**
--------------
I did find a workaround that works fast, but it requires some code refactoring. The "magic" happens by encapsulation. The workaround forces SwiftUI to discard the List completely, instead of removing one row at a time. It does so by using two separate lists in two separate encapsualted views: `Filtered` and `NotFiltered`. Below is a full demo with 3000 rows.
```swift
import SwiftUI
class UserData: ObservableObject {
@Published var showWantsOnly = false
@Published var bookList: [Book] = []
init() {
for _ in 0..<3001 {
bookList.append(Book())
}
}
}
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
VStack {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if userData.showWantsOnly {
Filtered()
} else {
NotFiltered()
}
}
}.navigationBarTitle(Text("Books"))
}
}
struct Filtered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList.filter { $0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct NotFiltered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct Book: Identifiable {
let id = UUID()
let own = Bool.random()
}
struct BookRow: View {
let book: Book
var body: some View {
Text("\(String(book.own)) \(book.id)")
}
}
struct BookDetail: View {
let book: Book
var body: some View {
Text("Detail for \(book.id)")
}
}
``` | Instead of a complicated workaround, just empty the List array and then set the new filters array. It may be necessary to introduce a delay so that emptying the listArray won't be omitted by the followed write.
```
List(listArray){item in
...
}
```
```
self.listArray = []
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
self.listArray = newList
}
``` |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| Have you tried passing a filtered array to the ForEach. Something like this:
```swift
ForEach(userData.bookList.filter { return !$0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) { BookRow(book: book) }
}
```
**Update**
----------
As it turns out, it is indeed an ugly, ugly bug:
Instead of filtering the array, I just remove the ForEach all together when the switch is flipped, and replace it by a simple `Text("Nothing")` view. The result is the same, it takes 30 secs to do so!
```swift
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if self.userData.showWantsOnly {
Text("Nothing")
} else {
ForEach(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
}.navigationBarTitle(Text("Books"))
}
}
```
**Workaround**
--------------
I did find a workaround that works fast, but it requires some code refactoring. The "magic" happens by encapsulation. The workaround forces SwiftUI to discard the List completely, instead of removing one row at a time. It does so by using two separate lists in two separate encapsualted views: `Filtered` and `NotFiltered`. Below is a full demo with 3000 rows.
```swift
import SwiftUI
class UserData: ObservableObject {
@Published var showWantsOnly = false
@Published var bookList: [Book] = []
init() {
for _ in 0..<3001 {
bookList.append(Book())
}
}
}
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
VStack {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if userData.showWantsOnly {
Filtered()
} else {
NotFiltered()
}
}
}.navigationBarTitle(Text("Books"))
}
}
struct Filtered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList.filter { $0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct NotFiltered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct Book: Identifiable {
let id = UUID()
let own = Bool.random()
}
struct BookRow: View {
let book: Book
var body: some View {
Text("\(String(book.own)) \(book.id)")
}
}
struct BookDetail: View {
let book: Book
var body: some View {
Text("Detail for \(book.id)")
}
}
``` | Check this article <https://www.hackingwithswift.com/articles/210/how-to-fix-slow-list-updates-in-swiftui>
In short the solution proposed in this article is to add **.id(UUID())** to the list:
```swift
List(items, id: \.self) {
Text("Item \($0)")
}
.id(UUID())
```
"Now, there is a downside to using id() like this: you won't get your update animated. Remember, we're effectively telling SwiftUI the old list has gone away and there's a new list now, which means it won't try to move rows around in an animated way." |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| Have you tried passing a filtered array to the ForEach. Something like this:
```swift
ForEach(userData.bookList.filter { return !$0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) { BookRow(book: book) }
}
```
**Update**
----------
As it turns out, it is indeed an ugly, ugly bug:
Instead of filtering the array, I just remove the ForEach all together when the switch is flipped, and replace it by a simple `Text("Nothing")` view. The result is the same, it takes 30 secs to do so!
```swift
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if self.userData.showWantsOnly {
Text("Nothing")
} else {
ForEach(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
}.navigationBarTitle(Text("Books"))
}
}
```
**Workaround**
--------------
I did find a workaround that works fast, but it requires some code refactoring. The "magic" happens by encapsulation. The workaround forces SwiftUI to discard the List completely, instead of removing one row at a time. It does so by using two separate lists in two separate encapsualted views: `Filtered` and `NotFiltered`. Below is a full demo with 3000 rows.
```swift
import SwiftUI
class UserData: ObservableObject {
@Published var showWantsOnly = false
@Published var bookList: [Book] = []
init() {
for _ in 0..<3001 {
bookList.append(Book())
}
}
}
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
VStack {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if userData.showWantsOnly {
Filtered()
} else {
NotFiltered()
}
}
}.navigationBarTitle(Text("Books"))
}
}
struct Filtered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList.filter { $0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct NotFiltered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct Book: Identifiable {
let id = UUID()
let own = Bool.random()
}
struct BookRow: View {
let book: Book
var body: some View {
Text("\(String(book.own)) \(book.id)")
}
}
struct BookDetail: View {
let book: Book
var body: some View {
Text("Detail for \(book.id)")
}
}
``` | Looking for how to adapt Seitenwerk's response to my solution, I found a Binding extension that helped me a lot. Here is the code:
```
struct ContactsView: View {
@State var stext : String = ""
@State var users : [MockUser] = []
@State var filtered : [MockUser] = []
var body: some View {
Form{
SearchBar(text: $stext.didSet(execute: { (response) in
if response != "" {
self.filtered = []
self.filtered = self.users.filter{$0.name.lowercased().hasPrefix(response.lowercased()) || response == ""}
}
else {
self.filtered = self.users
}
}), placeholder: "Buscar Contactos")
List{
ForEach(filtered, id: \.id){ user in
NavigationLink(destination: LazyView( DetailView(user: user) )) {
ContactCell(user: user)
}
}
}
}
.onAppear {
self.users = LoadUserData()
self.filtered = self.users
}
}
}
```
This is the Binding extension:
```
extension Binding {
/// Execute block when value is changed.
///
/// Example:
///
/// Slider(value: $amount.didSet { print($0) }, in: 0...10)
func didSet(execute: @escaping (Value) ->Void) -> Binding {
return Binding(
get: {
return self.wrappedValue
},
set: {
execute($0)
self.wrappedValue = $0
}
)
}
}
```
The LazyView is optional, but I took the trouble to show it, as it helps a lot in the performance of the list, and prevents swiftUI from creating the NavigationLink target content of the whole list.
```
struct LazyView<Content: View>: View {
let build: () -> Content
init(_ build: @autoclosure @escaping () -> Content) {
self.build = build
}
var body: Content {
build()
}
}
``` |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| I think we have to wait until SwiftUI List performance improves in subsequent beta releases. I’ve experienced the same lag when lists are filtered from a very large array (500+) down to very small ones. I created a simple test app to time the layout for a simple array with integer IDs and strings with Buttons to simply change which array is being rendered - same lag. | This code will work correctly provided that you initialize your class in the 'SceneDelegate' file as follows:
```
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var userData = UserData()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
contentView
.environmentObject(userData)
)
self.window = window
window.makeKeyAndVisible()
}
}
``` |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| Instead of a complicated workaround, just empty the List array and then set the new filters array. It may be necessary to introduce a delay so that emptying the listArray won't be omitted by the followed write.
```
List(listArray){item in
...
}
```
```
self.listArray = []
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
self.listArray = newList
}
``` | This code will work correctly provided that you initialize your class in the 'SceneDelegate' file as follows:
```
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var userData = UserData()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
contentView
.environmentObject(userData)
)
self.window = window
window.makeKeyAndVisible()
}
}
``` |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| Check this article <https://www.hackingwithswift.com/articles/210/how-to-fix-slow-list-updates-in-swiftui>
In short the solution proposed in this article is to add **.id(UUID())** to the list:
```swift
List(items, id: \.self) {
Text("Item \($0)")
}
.id(UUID())
```
"Now, there is a downside to using id() like this: you won't get your update animated. Remember, we're effectively telling SwiftUI the old list has gone away and there's a new list now, which means it won't try to move rows around in an animated way." | This code will work correctly provided that you initialize your class in the 'SceneDelegate' file as follows:
```
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var userData = UserData()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
contentView
.environmentObject(userData)
)
self.window = window
window.makeKeyAndVisible()
}
}
``` |
57,637,466 | Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
``` | 2019/08/24 | [
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
]
| Looking for how to adapt Seitenwerk's response to my solution, I found a Binding extension that helped me a lot. Here is the code:
```
struct ContactsView: View {
@State var stext : String = ""
@State var users : [MockUser] = []
@State var filtered : [MockUser] = []
var body: some View {
Form{
SearchBar(text: $stext.didSet(execute: { (response) in
if response != "" {
self.filtered = []
self.filtered = self.users.filter{$0.name.lowercased().hasPrefix(response.lowercased()) || response == ""}
}
else {
self.filtered = self.users
}
}), placeholder: "Buscar Contactos")
List{
ForEach(filtered, id: \.id){ user in
NavigationLink(destination: LazyView( DetailView(user: user) )) {
ContactCell(user: user)
}
}
}
}
.onAppear {
self.users = LoadUserData()
self.filtered = self.users
}
}
}
```
This is the Binding extension:
```
extension Binding {
/// Execute block when value is changed.
///
/// Example:
///
/// Slider(value: $amount.didSet { print($0) }, in: 0...10)
func didSet(execute: @escaping (Value) ->Void) -> Binding {
return Binding(
get: {
return self.wrappedValue
},
set: {
execute($0)
self.wrappedValue = $0
}
)
}
}
```
The LazyView is optional, but I took the trouble to show it, as it helps a lot in the performance of the list, and prevents swiftUI from creating the NavigationLink target content of the whole list.
```
struct LazyView<Content: View>: View {
let build: () -> Content
init(_ build: @autoclosure @escaping () -> Content) {
self.build = build
}
var body: Content {
build()
}
}
``` | This code will work correctly provided that you initialize your class in the 'SceneDelegate' file as follows:
```
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var userData = UserData()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
contentView
.environmentObject(userData)
)
self.window = window
window.makeKeyAndVisible()
}
}
``` |
58,206,306 | Suppose I have a local file called "contacts.json" . I want to insert it in react component and create a table . I'll be so glad if anybody can help me .Thanks .
```
{
"contacts": [
{
"id": 1,
"firstName": "hamid",
"lastName": "mohamadi",
"contactType": "Friend",
"birthDate": "2010.10.10",
"phoneNumber": [
"09011019011",
"09120658719"
],
"email": [
"[email protected]",
"[email protected]"
]
}
```
} | 2019/10/02 | [
"https://Stackoverflow.com/questions/58206306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11749690/"
]
| After some digging, I found that the `InputProps` also have the `className` property. The following worked for me:
```
<TextField
{...props}
inputProps={{
readOnly,
}}
InputProps={{
className: (readOnly) ? 'Mui-disabled' : undefined,
}}
/>
```
To see all the properties you can look [here](https://material-ui.com/api/text-field/). | You need to use classes on TextField
```
<TextField
{...props}
classes={readOnly ? { root: 'Mui-disabled' } : {}}
/>
```
Hope it helps |
58,206,306 | Suppose I have a local file called "contacts.json" . I want to insert it in react component and create a table . I'll be so glad if anybody can help me .Thanks .
```
{
"contacts": [
{
"id": 1,
"firstName": "hamid",
"lastName": "mohamadi",
"contactType": "Friend",
"birthDate": "2010.10.10",
"phoneNumber": [
"09011019011",
"09120658719"
],
"email": [
"[email protected]",
"[email protected]"
]
}
```
} | 2019/10/02 | [
"https://Stackoverflow.com/questions/58206306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11749690/"
]
| When you use the `disabled` property, Material-UI places the `Mui-disabled` class on many different elements. To get the equivalent look, you need to add it to all the same elements.
Below is an example of how to do this. In addition to adding the `Mui-disabled` class, it is also necessary to override the ["focused" styling](https://github.com/mui-org/material-ui/blob/v4.5.0/packages/material-ui/src/Input/Input.js#L30) of the underline (handled via the `:after` pseudo-class).
```
import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
const disabledClassNameProps = { className: "Mui-disabled" };
const useStyles = makeStyles(theme => {
const light = theme.palette.type === "light";
const bottomLineColor = light
? "rgba(0, 0, 0, 0.42)"
: "rgba(255, 255, 255, 0.7)";
return {
underline: {
"&.Mui-disabled:after": {
borderBottom: `1px dotted ${bottomLineColor}`,
transform: "scaleX(0)"
}
}
};
});
function App() {
const classes = useStyles();
return (
<div className="App">
<TextField
{...disabledClassNameProps}
inputProps={{ readOnly: true }}
InputProps={{ ...disabledClassNameProps, classes }}
InputLabelProps={disabledClassNameProps}
FormHelperTextProps={disabledClassNameProps}
label="Test Disabled Look"
defaultValue="Some Text"
helperText="Helper Text"
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
```
[](https://codesandbox.io/s/textfield-readonly-looking-disabled-gsktd?fontsize=14)
Related answers:
* [Altering multiple component roots for MUI Textfield](https://stackoverflow.com/questions/57917743/altering-multiple-component-roots-for-mui-textfield/57926379#57926379)
* [How can I remove the underline of TextField from Material-UI?](https://stackoverflow.com/questions/57914368/how-can-i-remove-the-underline-of-textfield-from-material-ui/57915357#57915357)
* [How do I custom style the underline of Material-UI without using theme?](https://stackoverflow.com/questions/56023814/how-do-i-custom-style-the-underline-of-material-ui-without-using-theme/56026253#56026253) | You need to use classes on TextField
```
<TextField
{...props}
classes={readOnly ? { root: 'Mui-disabled' } : {}}
/>
```
Hope it helps |
58,206,306 | Suppose I have a local file called "contacts.json" . I want to insert it in react component and create a table . I'll be so glad if anybody can help me .Thanks .
```
{
"contacts": [
{
"id": 1,
"firstName": "hamid",
"lastName": "mohamadi",
"contactType": "Friend",
"birthDate": "2010.10.10",
"phoneNumber": [
"09011019011",
"09120658719"
],
"email": [
"[email protected]",
"[email protected]"
]
}
```
} | 2019/10/02 | [
"https://Stackoverflow.com/questions/58206306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11749690/"
]
| When you use the `disabled` property, Material-UI places the `Mui-disabled` class on many different elements. To get the equivalent look, you need to add it to all the same elements.
Below is an example of how to do this. In addition to adding the `Mui-disabled` class, it is also necessary to override the ["focused" styling](https://github.com/mui-org/material-ui/blob/v4.5.0/packages/material-ui/src/Input/Input.js#L30) of the underline (handled via the `:after` pseudo-class).
```
import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
const disabledClassNameProps = { className: "Mui-disabled" };
const useStyles = makeStyles(theme => {
const light = theme.palette.type === "light";
const bottomLineColor = light
? "rgba(0, 0, 0, 0.42)"
: "rgba(255, 255, 255, 0.7)";
return {
underline: {
"&.Mui-disabled:after": {
borderBottom: `1px dotted ${bottomLineColor}`,
transform: "scaleX(0)"
}
}
};
});
function App() {
const classes = useStyles();
return (
<div className="App">
<TextField
{...disabledClassNameProps}
inputProps={{ readOnly: true }}
InputProps={{ ...disabledClassNameProps, classes }}
InputLabelProps={disabledClassNameProps}
FormHelperTextProps={disabledClassNameProps}
label="Test Disabled Look"
defaultValue="Some Text"
helperText="Helper Text"
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
```
[](https://codesandbox.io/s/textfield-readonly-looking-disabled-gsktd?fontsize=14)
Related answers:
* [Altering multiple component roots for MUI Textfield](https://stackoverflow.com/questions/57917743/altering-multiple-component-roots-for-mui-textfield/57926379#57926379)
* [How can I remove the underline of TextField from Material-UI?](https://stackoverflow.com/questions/57914368/how-can-i-remove-the-underline-of-textfield-from-material-ui/57915357#57915357)
* [How do I custom style the underline of Material-UI without using theme?](https://stackoverflow.com/questions/56023814/how-do-i-custom-style-the-underline-of-material-ui-without-using-theme/56026253#56026253) | After some digging, I found that the `InputProps` also have the `className` property. The following worked for me:
```
<TextField
{...props}
inputProps={{
readOnly,
}}
InputProps={{
className: (readOnly) ? 'Mui-disabled' : undefined,
}}
/>
```
To see all the properties you can look [here](https://material-ui.com/api/text-field/). |
20,810,210 | Consider the following class:
```
public class MyClass
{
private MyObject obj;
public MyClass()
{
obj = new MyObject();
}
public void methodCalledByOtherThreads()
{
obj.doStuff();
}
}
```
Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference?
Edit:
For clarity, I think my main question is:
Can other threads see that obj has been initialized by some main thread or could obj be stale (null)? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605245/"
]
| For the `methodCalledByOtherThreads` to be called by another thread and cause problems, that thread would have to get a reference to a `MyClass` object whose `obj` field is not initialized, ie. where the constructor has not yet returned.
This would be possible if you leaked the `this` reference from the constructor. For example
```
public MyClass()
{
SomeClass.leak(this);
obj = new MyObject();
}
```
If the `SomeClass.leak()` method starts a separate thread that calls `methodCalledByOtherThreads()` on the `this` reference, then you would have problems, but this is true regardless of the `volatile`.
Since you don't have what I'm describing above, your code is fine. | This code is fine because the reference to the instance of `MyClass` can't be visible to any other threads before the constructor returns.
Specifically, the [happens-before relation](http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5) requires that the visible effects of actions occur in the same order as they're listed in the program code, so that in the thread where the `MyClass` is constructed, `obj` must be definitely assigned before the constructor returns, and the instantiating thread goes directly from the state of not having a reference to the `MyClass` object to having a reference to a fully-constructed `MyClass` object.
That thread can then pass a reference to that object to another thread, but all of the construction will have transitively happened-before the second thread can call any methods on it. This might happen through the constructing thread's launching the second thread, a `synchronized` method, a `volatile` field, or the other concurrency mechanisms, but all of them will ensure that all of the actions that took place in the instantiating thread are finished before the memory barrier is passed.
Note that if a reference to `this` gets passed out of the class inside the constructor somewhere, that reference might go floating around and get used before the constructor is finished. That's what's known as *unsafe publishing* of the object, but code such as yours that doesn't call non-`final` methods from the constructor (or directly pass out references to `this`) is fine. |
20,810,210 | Consider the following class:
```
public class MyClass
{
private MyObject obj;
public MyClass()
{
obj = new MyObject();
}
public void methodCalledByOtherThreads()
{
obj.doStuff();
}
}
```
Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference?
Edit:
For clarity, I think my main question is:
Can other threads see that obj has been initialized by some main thread or could obj be stale (null)? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605245/"
]
| For the `methodCalledByOtherThreads` to be called by another thread and cause problems, that thread would have to get a reference to a `MyClass` object whose `obj` field is not initialized, ie. where the constructor has not yet returned.
This would be possible if you leaked the `this` reference from the constructor. For example
```
public MyClass()
{
SomeClass.leak(this);
obj = new MyObject();
}
```
If the `SomeClass.leak()` method starts a separate thread that calls `methodCalledByOtherThreads()` on the `this` reference, then you would have problems, but this is true regardless of the `volatile`.
Since you don't have what I'm describing above, your code is fine. | The originally picked answer by @Sotirios Delimanolis is wrong. @ZhongYu 's answer is correct.
There is the visibility issue of the concern here. So if MyClass is published unsafely, anything could happen.
Someone in the comment asked for evidence - one can check Listing 3.15 in the book *Java Concurrency in Practice*:
```
public class Holder {
private int n;
// Initialize in thread A
public Holder(int n) { this.n = n; }
// Called in thread B
public void assertSanity() {
if (n != n) throw new AssertionError("This statement is false.");
}
}
```
Someone comes up an example to verify this piece of code:
[coding a proof for potential concurrency issue](https://stackoverflow.com/questions/17728710/coding-a-proof-for-potential-concurrency-issue)
As to the specific example of this post:
```
public class MyClass{
private MyObject obj;
// Initialize in thread A
public MyClass(){
obj = new MyObject();
}
// Called in thread B
public void methodCalledByOtherThreads(){
obj.doStuff();
}
}
```
If MyClass is initialized in Thread A, there is no guarantee that thread B will see this initialization (because the change might stay in the cache of the CPU that Thread A runs on and has not propagated into main memory).
Just as @ZhongYu has pointed out, because the write and read happens at 2 independent threads, so there is no `happens-before(write, read)` relation.
To fix this, as the original author has mentioned, we can declare private MyObject obj as volatile, which will ensure that the reference itself will be visible to other threads in timely manner
(<https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/volatile-ref-object.html>) . |
20,810,210 | Consider the following class:
```
public class MyClass
{
private MyObject obj;
public MyClass()
{
obj = new MyObject();
}
public void methodCalledByOtherThreads()
{
obj.doStuff();
}
}
```
Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference?
Edit:
For clarity, I think my main question is:
Can other threads see that obj has been initialized by some main thread or could obj be stale (null)? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605245/"
]
| For the `methodCalledByOtherThreads` to be called by another thread and cause problems, that thread would have to get a reference to a `MyClass` object whose `obj` field is not initialized, ie. where the constructor has not yet returned.
This would be possible if you leaked the `this` reference from the constructor. For example
```
public MyClass()
{
SomeClass.leak(this);
obj = new MyObject();
}
```
If the `SomeClass.leak()` method starts a separate thread that calls `methodCalledByOtherThreads()` on the `this` reference, then you would have problems, but this is true regardless of the `volatile`.
Since you don't have what I'm describing above, your code is fine. | Your other thread **could** see a null object. A volatile object could possibly help, but an explicit lock mechanism (or a Builder) would likely be a better solution.
Have a look at [Java Concurrency in Practice - Sample 14.12](https://stackoverflow.com/questions/10528572/java-concurrency-in-practice-sample-14-12) |
20,810,210 | Consider the following class:
```
public class MyClass
{
private MyObject obj;
public MyClass()
{
obj = new MyObject();
}
public void methodCalledByOtherThreads()
{
obj.doStuff();
}
}
```
Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference?
Edit:
For clarity, I think my main question is:
Can other threads see that obj has been initialized by some main thread or could obj be stale (null)? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605245/"
]
| It depends on whether the reference is published "unsafely". A reference is "published" by being written to a shared variable; another thread reads the variable to get the reference. If there is no relationship of `happens-before(write, read)`, the publication is called unsafe. An example of unsafe publication is through a non-volatile static field.
@chrylis 's interpretation of "unsafe publication" is not accurate. Leaking `this` before constructor exit is orthogonal to the concept of unsafe publication.
Through unsafe publication, another thread may observe the object in an uncertain state (hence the name); in your case, field `obj` may appear to be null to another thread. Unless, `obj` is `final`, then it cannot appear to be null even if the host object is published unsafely.
This is all too technical and it requires further readings to understand. The good news is, you don't need to master "unsafe publication", because it is a discouraged practice anyway. The best practice is simply: never do unsafe publication; *i.e.* never do data race; *i.e.* always read/write shared data through proper synchronization, by using `synchronized, volatile` or `java.util.concurrent`.
If we always avoid unsafe publication, do we still *need* `final` fields? The answer is no. Then why are some objects (e.g. `String`) designed to be "thread safe immutable" by using final fields? Because it's assumed that they can be used in malicious code that tries to create uncertain state through deliberate unsafe publication. I think this is an overblown concern. It doesn't make much sense in server environments - if an application embeds malicious code, the server is compromised, period. It probably makes a bit of sense in Applet environment where JVM runs untrusted codes from unknown sources - even then, this is an improbable attack vector; there's no precedence of this kind of attack; there are a lot of other more easily exploitable security holes, apparently. | This code is fine because the reference to the instance of `MyClass` can't be visible to any other threads before the constructor returns.
Specifically, the [happens-before relation](http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5) requires that the visible effects of actions occur in the same order as they're listed in the program code, so that in the thread where the `MyClass` is constructed, `obj` must be definitely assigned before the constructor returns, and the instantiating thread goes directly from the state of not having a reference to the `MyClass` object to having a reference to a fully-constructed `MyClass` object.
That thread can then pass a reference to that object to another thread, but all of the construction will have transitively happened-before the second thread can call any methods on it. This might happen through the constructing thread's launching the second thread, a `synchronized` method, a `volatile` field, or the other concurrency mechanisms, but all of them will ensure that all of the actions that took place in the instantiating thread are finished before the memory barrier is passed.
Note that if a reference to `this` gets passed out of the class inside the constructor somewhere, that reference might go floating around and get used before the constructor is finished. That's what's known as *unsafe publishing* of the object, but code such as yours that doesn't call non-`final` methods from the constructor (or directly pass out references to `this`) is fine. |
20,810,210 | Consider the following class:
```
public class MyClass
{
private MyObject obj;
public MyClass()
{
obj = new MyObject();
}
public void methodCalledByOtherThreads()
{
obj.doStuff();
}
}
```
Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference?
Edit:
For clarity, I think my main question is:
Can other threads see that obj has been initialized by some main thread or could obj be stale (null)? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605245/"
]
| It depends on whether the reference is published "unsafely". A reference is "published" by being written to a shared variable; another thread reads the variable to get the reference. If there is no relationship of `happens-before(write, read)`, the publication is called unsafe. An example of unsafe publication is through a non-volatile static field.
@chrylis 's interpretation of "unsafe publication" is not accurate. Leaking `this` before constructor exit is orthogonal to the concept of unsafe publication.
Through unsafe publication, another thread may observe the object in an uncertain state (hence the name); in your case, field `obj` may appear to be null to another thread. Unless, `obj` is `final`, then it cannot appear to be null even if the host object is published unsafely.
This is all too technical and it requires further readings to understand. The good news is, you don't need to master "unsafe publication", because it is a discouraged practice anyway. The best practice is simply: never do unsafe publication; *i.e.* never do data race; *i.e.* always read/write shared data through proper synchronization, by using `synchronized, volatile` or `java.util.concurrent`.
If we always avoid unsafe publication, do we still *need* `final` fields? The answer is no. Then why are some objects (e.g. `String`) designed to be "thread safe immutable" by using final fields? Because it's assumed that they can be used in malicious code that tries to create uncertain state through deliberate unsafe publication. I think this is an overblown concern. It doesn't make much sense in server environments - if an application embeds malicious code, the server is compromised, period. It probably makes a bit of sense in Applet environment where JVM runs untrusted codes from unknown sources - even then, this is an improbable attack vector; there's no precedence of this kind of attack; there are a lot of other more easily exploitable security holes, apparently. | The originally picked answer by @Sotirios Delimanolis is wrong. @ZhongYu 's answer is correct.
There is the visibility issue of the concern here. So if MyClass is published unsafely, anything could happen.
Someone in the comment asked for evidence - one can check Listing 3.15 in the book *Java Concurrency in Practice*:
```
public class Holder {
private int n;
// Initialize in thread A
public Holder(int n) { this.n = n; }
// Called in thread B
public void assertSanity() {
if (n != n) throw new AssertionError("This statement is false.");
}
}
```
Someone comes up an example to verify this piece of code:
[coding a proof for potential concurrency issue](https://stackoverflow.com/questions/17728710/coding-a-proof-for-potential-concurrency-issue)
As to the specific example of this post:
```
public class MyClass{
private MyObject obj;
// Initialize in thread A
public MyClass(){
obj = new MyObject();
}
// Called in thread B
public void methodCalledByOtherThreads(){
obj.doStuff();
}
}
```
If MyClass is initialized in Thread A, there is no guarantee that thread B will see this initialization (because the change might stay in the cache of the CPU that Thread A runs on and has not propagated into main memory).
Just as @ZhongYu has pointed out, because the write and read happens at 2 independent threads, so there is no `happens-before(write, read)` relation.
To fix this, as the original author has mentioned, we can declare private MyObject obj as volatile, which will ensure that the reference itself will be visible to other threads in timely manner
(<https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/volatile-ref-object.html>) . |
20,810,210 | Consider the following class:
```
public class MyClass
{
private MyObject obj;
public MyClass()
{
obj = new MyObject();
}
public void methodCalledByOtherThreads()
{
obj.doStuff();
}
}
```
Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference?
Edit:
For clarity, I think my main question is:
Can other threads see that obj has been initialized by some main thread or could obj be stale (null)? | 2013/12/28 | [
"https://Stackoverflow.com/questions/20810210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605245/"
]
| This class (if taken as is) is NOT thread safe. In two words: there is reordering of instructions in java ([Instruction reordering & happens-before relationship in java](https://stackoverflow.com/questions/16213443/instruction-reordering-happens-before-relationship-in-java)) and when in your code you're instantiating MyClass, under some circumstances you may get following set of instructions:
* Allocate memory for new instance of MyClass;
* Return link to this block of memory;
* Link to this not fully initialized MyClass is available for other threads, they can call "methodCalledByOtherThreads()" and get NullPointerException;
* Initialize internals of MyClass.
In order to prevent this and make your MyClass really thread safe - you either have to add "final" or "volatile" to the "obj" field. In this case Java's memory model (starting from Java 5 on) will guarantee that during initialization of MyClass, reference to alocated for it block of memory will be returned only when all internals are initialized.
For more details I would strictly recommend you to read nice book "Java Concurrency in Practice". Exactly your case is described on the pages 50-51 (section 3.5.1). I would even say - you just can write correct multithreaded code without reading that book! :) | The originally picked answer by @Sotirios Delimanolis is wrong. @ZhongYu 's answer is correct.
There is the visibility issue of the concern here. So if MyClass is published unsafely, anything could happen.
Someone in the comment asked for evidence - one can check Listing 3.15 in the book *Java Concurrency in Practice*:
```
public class Holder {
private int n;
// Initialize in thread A
public Holder(int n) { this.n = n; }
// Called in thread B
public void assertSanity() {
if (n != n) throw new AssertionError("This statement is false.");
}
}
```
Someone comes up an example to verify this piece of code:
[coding a proof for potential concurrency issue](https://stackoverflow.com/questions/17728710/coding-a-proof-for-potential-concurrency-issue)
As to the specific example of this post:
```
public class MyClass{
private MyObject obj;
// Initialize in thread A
public MyClass(){
obj = new MyObject();
}
// Called in thread B
public void methodCalledByOtherThreads(){
obj.doStuff();
}
}
```
If MyClass is initialized in Thread A, there is no guarantee that thread B will see this initialization (because the change might stay in the cache of the CPU that Thread A runs on and has not propagated into main memory).
Just as @ZhongYu has pointed out, because the write and read happens at 2 independent threads, so there is no `happens-before(write, read)` relation.
To fix this, as the original author has mentioned, we can declare private MyObject obj as volatile, which will ensure that the reference itself will be visible to other threads in timely manner
(<https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/volatile-ref-object.html>) . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.