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
382,659
Turns out, everything i put inside any folder in my mac, is being uploaded to the cloud, showing me the cloud icon, and files are not available when i need them.(which by itself is a strange UX) To stop this, i went into iCloud Drive ->options->, and uncheck the **Documents and Desktop Folders**. Then i get a mesage saying that *all my files in Desktop/Documents folder will **disappear** from my mac, and will be available in iCloud if i uncheck this box.* I want back my files **on my mac**. I don't want to go and look for them in iCloud now, but keep my folders structure as it is, with my files ***not in icloud***, but right where i put them in first place. (download all of them) How to cancel this hostage UX, and get my files where they belong, **without** removing them from my mac first(as the massage says) ?
2020/02/20
[ "https://apple.stackexchange.com/questions/382659", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/349012/" ]
> > .. and files are not available when i need them .. > > > macOS < 10.15: System Preferences → iCloud → iCloud Drive options → Uncheck Optimise Storage. macOS 10.15+: System Preferences → Apple ID → iCloud Drive options → Uncheck Optimise Storage. All files will be found locally, always, as well as on iCloud. * [Can I safely uncheck the Optimise Mac Storage check box on the Apple ID - iCloud page?](https://apple.stackexchange.com/questions/380434/can-i-safely-uncheck-the-optimise-mac-storage-check-box-on-the-apple-id-icloud/380488#380488) * <https://support.apple.com/guide/mac-help/mchle5a61431/mac> For the second part, > > What may seem counterintuitive is that your files are still stored in the iCloud ( which is perhaps why you thought you lost them). > > > To retrieve your files, you should open Finder and navigate to iCloud Drive, and then to the Documents folder within iCloud Drive. You should then manually transfer or copy the files from that directory to the local Documents directory on your computer. You should then do that same with your Desktop folder. > > > * [How to separate iCloud Drive from Desktop & Documents](https://apple.stackexchange.com/questions/315349/how-to-separate-icloud-drive-from-desktop-documents/315351#315351)
You should uncheck the Optimize Storage button and wait for your files to finish downloading. Restart your computer if you don't see any progress right away. When they've downloaded, you'll be able to move them instantly.
382,659
Turns out, everything i put inside any folder in my mac, is being uploaded to the cloud, showing me the cloud icon, and files are not available when i need them.(which by itself is a strange UX) To stop this, i went into iCloud Drive ->options->, and uncheck the **Documents and Desktop Folders**. Then i get a mesage saying that *all my files in Desktop/Documents folder will **disappear** from my mac, and will be available in iCloud if i uncheck this box.* I want back my files **on my mac**. I don't want to go and look for them in iCloud now, but keep my folders structure as it is, with my files ***not in icloud***, but right where i put them in first place. (download all of them) How to cancel this hostage UX, and get my files where they belong, **without** removing them from my mac first(as the massage says) ?
2020/02/20
[ "https://apple.stackexchange.com/questions/382659", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/349012/" ]
> > .. and files are not available when i need them .. > > > macOS < 10.15: System Preferences → iCloud → iCloud Drive options → Uncheck Optimise Storage. macOS 10.15+: System Preferences → Apple ID → iCloud Drive options → Uncheck Optimise Storage. All files will be found locally, always, as well as on iCloud. * [Can I safely uncheck the Optimise Mac Storage check box on the Apple ID - iCloud page?](https://apple.stackexchange.com/questions/380434/can-i-safely-uncheck-the-optimise-mac-storage-check-box-on-the-apple-id-icloud/380488#380488) * <https://support.apple.com/guide/mac-help/mchle5a61431/mac> For the second part, > > What may seem counterintuitive is that your files are still stored in the iCloud ( which is perhaps why you thought you lost them). > > > To retrieve your files, you should open Finder and navigate to iCloud Drive, and then to the Documents folder within iCloud Drive. You should then manually transfer or copy the files from that directory to the local Documents directory on your computer. You should then do that same with your Desktop folder. > > > * [How to separate iCloud Drive from Desktop & Documents](https://apple.stackexchange.com/questions/315349/how-to-separate-icloud-drive-from-desktop-documents/315351#315351)
I made a same mistake I turned on iCloud and then turn it off. I thought my files are gone because they were not visible in recovery software. Then I put the name of file to finder search and it was in iCloud version of Documents folder completely fine. But for some reason I did not see that folder in finder or my user documents.
382,659
Turns out, everything i put inside any folder in my mac, is being uploaded to the cloud, showing me the cloud icon, and files are not available when i need them.(which by itself is a strange UX) To stop this, i went into iCloud Drive ->options->, and uncheck the **Documents and Desktop Folders**. Then i get a mesage saying that *all my files in Desktop/Documents folder will **disappear** from my mac, and will be available in iCloud if i uncheck this box.* I want back my files **on my mac**. I don't want to go and look for them in iCloud now, but keep my folders structure as it is, with my files ***not in icloud***, but right where i put them in first place. (download all of them) How to cancel this hostage UX, and get my files where they belong, **without** removing them from my mac first(as the massage says) ?
2020/02/20
[ "https://apple.stackexchange.com/questions/382659", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/349012/" ]
You should uncheck the Optimize Storage button and wait for your files to finish downloading. Restart your computer if you don't see any progress right away. When they've downloaded, you'll be able to move them instantly.
I made a same mistake I turned on iCloud and then turn it off. I thought my files are gone because they were not visible in recovery software. Then I put the name of file to finder search and it was in iCloud version of Documents folder completely fine. But for some reason I did not see that folder in finder or my user documents.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
Very old games used a technique where only those parts of a frame are redrawn that changed on that frame. What I can remember, the game "Little Big Adventure" uses this technique (1994). But you can see that the game has for most of the time a static camera. only when you move out of the visible area the scene is redrawn. If you play the game you would also notice a tiny lag on that frame. On modern GPUs with modern game engines, things have changed. Everything is redrawn on each frame. Depending on the rendering technique, things might even be rendered several times. The computing power of a GPU is just incredibly high when you use it correctly. But reuse is happening. For example an engine could decide to update the shadow map only every 5th frame. Or the lighting is not updated as long as there is no change in the light sources.
No. === At least if you include old games from the 70s which used vector displays. For example, the widely known game Asteroids, which was originally developed for vector displays which are a fundamentally different way of rendering graphics to a screen. > > Vector monitors were also used by some late-1970s to mid-1980s arcade games such as Asteroids, Tempest, and Star Wars. Atariused the term Quadrascan to describe the technology when used in their video game arcades. > > > <https://en.wikipedia.org/wiki/Vector_monitor> Modern day graphics are pretty much 100% made for rasterizaton, which by definition writes the contents of a graphics buffer to the display every frame.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
Very old games used a technique where only those parts of a frame are redrawn that changed on that frame. What I can remember, the game "Little Big Adventure" uses this technique (1994). But you can see that the game has for most of the time a static camera. only when you move out of the visible area the scene is redrawn. If you play the game you would also notice a tiny lag on that frame. On modern GPUs with modern game engines, things have changed. Everything is redrawn on each frame. Depending on the rendering technique, things might even be rendered several times. The computing power of a GPU is just incredibly high when you use it correctly. But reuse is happening. For example an engine could decide to update the shadow map only every 5th frame. Or the lighting is not updated as long as there is no change in the light sources.
Short answer: No. Long story: When I learned some game programming in school, we were taught to do the following: Decide what fps rate we wanted in the game (30 for example). Write some code that adds 1 to a counter for each interval (33 msec for 30 fps). This code runs concurrently with the game loop. Then the game loop that does the calculations for the game (game state update) will reduce the same counter by 1 for each frame. But the graphics calculations and drawing to screen will only be done if the counter is at zero. The outcome is that the graphical frame rate will adjust depending on how well the cpu handles the calculations in game. When not too much is happening in the game, calculations are easy and the graphics frame rate will be higher than the actual game state update (basically wasting cycles since we draw the same game state more than once on screen). But then a lot is happening in game, the cpu will have more work to do and game state updates will be prioritised over drawing to screen. Most of the time, the game will keep updating at the intended rate, but will appear "laggy" since you won't see each update on screen. This may be preferrable to the whole game slowing down because you force it do draw each update on the screen. This was all done with C++ and no game engine, nor graphics card. Everything ran on a single core cpu. We used some libraries for 2d graphics.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
No. === At least if you include old games from the 70s which used vector displays. For example, the widely known game Asteroids, which was originally developed for vector displays which are a fundamentally different way of rendering graphics to a screen. > > Vector monitors were also used by some late-1970s to mid-1980s arcade games such as Asteroids, Tempest, and Star Wars. Atariused the term Quadrascan to describe the technology when used in their video game arcades. > > > <https://en.wikipedia.org/wiki/Vector_monitor> Modern day graphics are pretty much 100% made for rasterizaton, which by definition writes the contents of a graphics buffer to the display every frame.
Before one can say whether video games "draw" the display every frame, it's first necessary to define what is meant by "draw". There are certainly many video games certainly do not all draw every frame by assembling a bitmap from scratch; indeed, many gaming platforms never assemble full bitmaps *at all*. There are a few approaches video games can take to generating a display. A very small number have the CPU turn the electron beam on and off or for every pixel or, for vector-scan games, set the XY coordinate of every dot to be plotted. Most games that do this do so largely for the purpose of demonstrating that the CPU is fast enough. More commonly games will have hardware which, in the absence of CPU involvement, would output some pattern of pixels or vectors to the display repeatedly. This pattern may be produced by reading data sequentially from a region of memory and interpreting each bit or group of bits as a pixel color (this is called a bit-map display). In some cases, hardware may read a byte of memory for each 8x8, 16x16, or other size region of the display and then use that byte to select a range of memory to read for pixel data (this is often called a character-map display). Some hardware platforms can overlay multiple bitmap displays with configurable positions. These are referred to as sprites. Some platforms do not allow the display pattern to be changed while it is being sent to the screen, but instead require that all updates occur after the beam has finished drawing one frame but before it has started drawing the next. On such platforms, everything that is going to appear on a frame needs to be loaded into the display hardware before the start of that frame, and the display will be limited to showing a pattern that can be set up all at once. If the CPU were to stop running while the frame is being shown, that same frame would keep being shown indefinitely. Other platforms do allow the pattern to be changed or reconfigured while it is being drawn to the screen. This makes it possible to show a screen which is much more complicated than the video circuitry could handle by itself. This may make it possible for a hardware platform which has eight sprites to show a larger number of movable objects by setting the positions of the top eight objects on the screen, waiting for the beam has reached a point somewhere between the bottom of the first object and the top of the ninth, setting the position of the ninth object, waiting for the beam to get between the bottom of the second object and top of the tenth (if it isn't already there), setting the position of the tenth object, etc. Note that this approach would require CPU involvement during every generated frame of video, even if none of the objects visibly move, but the CPU would not be involved with "drawing" each object. Most personal computer games use hardware configured to draw a single bitmap screen, and then draw onto that screen anything that needs to be different from what's already there. Sometimes it may be easier to draw things without regard for whether it is actually necessary in a particular case, but if code can easily tell that there's no reason for part of the screen to change, performance may be improved by skipping that part. Today's platforms are often fast enough that they could draw the entire screen many times over during the course of a frame, but historically that was not the case. The fastest possible code to write all the pixels on the Apple II computer's high resolution screen, for example, would take more than two frames, and the fastest possible code to copy all of the pixels on the Apple II computer's high resolution screen from another buffer would take twice that. Getting good performance required that games only update things that were actually changing, and that is what good games generally did.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
Short answer: No. Long story: When I learned some game programming in school, we were taught to do the following: Decide what fps rate we wanted in the game (30 for example). Write some code that adds 1 to a counter for each interval (33 msec for 30 fps). This code runs concurrently with the game loop. Then the game loop that does the calculations for the game (game state update) will reduce the same counter by 1 for each frame. But the graphics calculations and drawing to screen will only be done if the counter is at zero. The outcome is that the graphical frame rate will adjust depending on how well the cpu handles the calculations in game. When not too much is happening in the game, calculations are easy and the graphics frame rate will be higher than the actual game state update (basically wasting cycles since we draw the same game state more than once on screen). But then a lot is happening in game, the cpu will have more work to do and game state updates will be prioritised over drawing to screen. Most of the time, the game will keep updating at the intended rate, but will appear "laggy" since you won't see each update on screen. This may be preferrable to the whole game slowing down because you force it do draw each update on the screen. This was all done with C++ and no game engine, nor graphics card. Everything ran on a single core cpu. We used some libraries for 2d graphics.
Before one can say whether video games "draw" the display every frame, it's first necessary to define what is meant by "draw". There are certainly many video games certainly do not all draw every frame by assembling a bitmap from scratch; indeed, many gaming platforms never assemble full bitmaps *at all*. There are a few approaches video games can take to generating a display. A very small number have the CPU turn the electron beam on and off or for every pixel or, for vector-scan games, set the XY coordinate of every dot to be plotted. Most games that do this do so largely for the purpose of demonstrating that the CPU is fast enough. More commonly games will have hardware which, in the absence of CPU involvement, would output some pattern of pixels or vectors to the display repeatedly. This pattern may be produced by reading data sequentially from a region of memory and interpreting each bit or group of bits as a pixel color (this is called a bit-map display). In some cases, hardware may read a byte of memory for each 8x8, 16x16, or other size region of the display and then use that byte to select a range of memory to read for pixel data (this is often called a character-map display). Some hardware platforms can overlay multiple bitmap displays with configurable positions. These are referred to as sprites. Some platforms do not allow the display pattern to be changed while it is being sent to the screen, but instead require that all updates occur after the beam has finished drawing one frame but before it has started drawing the next. On such platforms, everything that is going to appear on a frame needs to be loaded into the display hardware before the start of that frame, and the display will be limited to showing a pattern that can be set up all at once. If the CPU were to stop running while the frame is being shown, that same frame would keep being shown indefinitely. Other platforms do allow the pattern to be changed or reconfigured while it is being drawn to the screen. This makes it possible to show a screen which is much more complicated than the video circuitry could handle by itself. This may make it possible for a hardware platform which has eight sprites to show a larger number of movable objects by setting the positions of the top eight objects on the screen, waiting for the beam has reached a point somewhere between the bottom of the first object and the top of the ninth, setting the position of the ninth object, waiting for the beam to get between the bottom of the second object and top of the tenth (if it isn't already there), setting the position of the tenth object, etc. Note that this approach would require CPU involvement during every generated frame of video, even if none of the objects visibly move, but the CPU would not be involved with "drawing" each object. Most personal computer games use hardware configured to draw a single bitmap screen, and then draw onto that screen anything that needs to be different from what's already there. Sometimes it may be easier to draw things without regard for whether it is actually necessary in a particular case, but if code can easily tell that there's no reason for part of the screen to change, performance may be improved by skipping that part. Today's platforms are often fast enough that they could draw the entire screen many times over during the course of a frame, but historically that was not the case. The fastest possible code to write all the pixels on the Apple II computer's high resolution screen, for example, would take more than two frames, and the fastest possible code to copy all of the pixels on the Apple II computer's high resolution screen from another buffer would take twice that. Getting good performance required that games only update things that were actually changing, and that is what good games generally did.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
Short answer: No. Long story: When I learned some game programming in school, we were taught to do the following: Decide what fps rate we wanted in the game (30 for example). Write some code that adds 1 to a counter for each interval (33 msec for 30 fps). This code runs concurrently with the game loop. Then the game loop that does the calculations for the game (game state update) will reduce the same counter by 1 for each frame. But the graphics calculations and drawing to screen will only be done if the counter is at zero. The outcome is that the graphical frame rate will adjust depending on how well the cpu handles the calculations in game. When not too much is happening in the game, calculations are easy and the graphics frame rate will be higher than the actual game state update (basically wasting cycles since we draw the same game state more than once on screen). But then a lot is happening in game, the cpu will have more work to do and game state updates will be prioritised over drawing to screen. Most of the time, the game will keep updating at the intended rate, but will appear "laggy" since you won't see each update on screen. This may be preferrable to the whole game slowing down because you force it do draw each update on the screen. This was all done with C++ and no game engine, nor graphics card. Everything ran on a single core cpu. We used some libraries for 2d graphics.
To put it briefly, I would say not all frames are drawn but just the ones required to present your story or theme of game or game-play are. Plus the timing of the things you would want to happen at certain instances would matter.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
On the lowest level, the graphics processor on your machine will indeed compute each frame from the ground up and send it to your screen. You will only be exposed to this, however, if you manage this low-level stuff yourself [1] Any graphics (and with that, game-) engine however, will handle these things for you, and you are free to express the scene in terms of many entities that you could modify between frames, but will be persistent. > > ... how this method would work for 3d games ... > > > The elements in 3D space are persistant, the graphics engine would, again, recompute the image on your screen for any changes that happened (camera movement etc.) [1] ... for example if you write your own engine [2] with something like OpenGL. Even in that case you would likely store persistent things between frames. [2] Which is *not* an option at your current skill level.
Before one can say whether video games "draw" the display every frame, it's first necessary to define what is meant by "draw". There are certainly many video games certainly do not all draw every frame by assembling a bitmap from scratch; indeed, many gaming platforms never assemble full bitmaps *at all*. There are a few approaches video games can take to generating a display. A very small number have the CPU turn the electron beam on and off or for every pixel or, for vector-scan games, set the XY coordinate of every dot to be plotted. Most games that do this do so largely for the purpose of demonstrating that the CPU is fast enough. More commonly games will have hardware which, in the absence of CPU involvement, would output some pattern of pixels or vectors to the display repeatedly. This pattern may be produced by reading data sequentially from a region of memory and interpreting each bit or group of bits as a pixel color (this is called a bit-map display). In some cases, hardware may read a byte of memory for each 8x8, 16x16, or other size region of the display and then use that byte to select a range of memory to read for pixel data (this is often called a character-map display). Some hardware platforms can overlay multiple bitmap displays with configurable positions. These are referred to as sprites. Some platforms do not allow the display pattern to be changed while it is being sent to the screen, but instead require that all updates occur after the beam has finished drawing one frame but before it has started drawing the next. On such platforms, everything that is going to appear on a frame needs to be loaded into the display hardware before the start of that frame, and the display will be limited to showing a pattern that can be set up all at once. If the CPU were to stop running while the frame is being shown, that same frame would keep being shown indefinitely. Other platforms do allow the pattern to be changed or reconfigured while it is being drawn to the screen. This makes it possible to show a screen which is much more complicated than the video circuitry could handle by itself. This may make it possible for a hardware platform which has eight sprites to show a larger number of movable objects by setting the positions of the top eight objects on the screen, waiting for the beam has reached a point somewhere between the bottom of the first object and the top of the ninth, setting the position of the ninth object, waiting for the beam to get between the bottom of the second object and top of the tenth (if it isn't already there), setting the position of the tenth object, etc. Note that this approach would require CPU involvement during every generated frame of video, even if none of the objects visibly move, but the CPU would not be involved with "drawing" each object. Most personal computer games use hardware configured to draw a single bitmap screen, and then draw onto that screen anything that needs to be different from what's already there. Sometimes it may be easier to draw things without regard for whether it is actually necessary in a particular case, but if code can easily tell that there's no reason for part of the screen to change, performance may be improved by skipping that part. Today's platforms are often fast enough that they could draw the entire screen many times over during the course of a frame, but historically that was not the case. The fastest possible code to write all the pixels on the Apple II computer's high resolution screen, for example, would take more than two frames, and the fastest possible code to copy all of the pixels on the Apple II computer's high resolution screen from another buffer would take twice that. Getting good performance required that games only update things that were actually changing, and that is what good games generally did.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
Very old games used a technique where only those parts of a frame are redrawn that changed on that frame. What I can remember, the game "Little Big Adventure" uses this technique (1994). But you can see that the game has for most of the time a static camera. only when you move out of the visible area the scene is redrawn. If you play the game you would also notice a tiny lag on that frame. On modern GPUs with modern game engines, things have changed. Everything is redrawn on each frame. Depending on the rendering technique, things might even be rendered several times. The computing power of a GPU is just incredibly high when you use it correctly. But reuse is happening. For example an engine could decide to update the shadow map only every 5th frame. Or the lighting is not updated as long as there is no change in the light sources.
On the lowest level, the graphics processor on your machine will indeed compute each frame from the ground up and send it to your screen. You will only be exposed to this, however, if you manage this low-level stuff yourself [1] Any graphics (and with that, game-) engine however, will handle these things for you, and you are free to express the scene in terms of many entities that you could modify between frames, but will be persistent. > > ... how this method would work for 3d games ... > > > The elements in 3D space are persistant, the graphics engine would, again, recompute the image on your screen for any changes that happened (camera movement etc.) [1] ... for example if you write your own engine [2] with something like OpenGL. Even in that case you would likely store persistent things between frames. [2] Which is *not* an option at your current skill level.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
No. === At least if you include old games from the 70s which used vector displays. For example, the widely known game Asteroids, which was originally developed for vector displays which are a fundamentally different way of rendering graphics to a screen. > > Vector monitors were also used by some late-1970s to mid-1980s arcade games such as Asteroids, Tempest, and Star Wars. Atariused the term Quadrascan to describe the technology when used in their video game arcades. > > > <https://en.wikipedia.org/wiki/Vector_monitor> Modern day graphics are pretty much 100% made for rasterizaton, which by definition writes the contents of a graphics buffer to the display every frame.
Short answer: No. Long story: When I learned some game programming in school, we were taught to do the following: Decide what fps rate we wanted in the game (30 for example). Write some code that adds 1 to a counter for each interval (33 msec for 30 fps). This code runs concurrently with the game loop. Then the game loop that does the calculations for the game (game state update) will reduce the same counter by 1 for each frame. But the graphics calculations and drawing to screen will only be done if the counter is at zero. The outcome is that the graphical frame rate will adjust depending on how well the cpu handles the calculations in game. When not too much is happening in the game, calculations are easy and the graphics frame rate will be higher than the actual game state update (basically wasting cycles since we draw the same game state more than once on screen). But then a lot is happening in game, the cpu will have more work to do and game state updates will be prioritised over drawing to screen. Most of the time, the game will keep updating at the intended rate, but will appear "laggy" since you won't see each update on screen. This may be preferrable to the whole game slowing down because you force it do draw each update on the screen. This was all done with C++ and no game engine, nor graphics card. Everything ran on a single core cpu. We used some libraries for 2d graphics.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
On the lowest level, the graphics processor on your machine will indeed compute each frame from the ground up and send it to your screen. You will only be exposed to this, however, if you manage this low-level stuff yourself [1] Any graphics (and with that, game-) engine however, will handle these things for you, and you are free to express the scene in terms of many entities that you could modify between frames, but will be persistent. > > ... how this method would work for 3d games ... > > > The elements in 3D space are persistant, the graphics engine would, again, recompute the image on your screen for any changes that happened (camera movement etc.) [1] ... for example if you write your own engine [2] with something like OpenGL. Even in that case you would likely store persistent things between frames. [2] Which is *not* an option at your current skill level.
To put it briefly, I would say not all frames are drawn but just the ones required to present your story or theme of game or game-play are. Plus the timing of the things you would want to happen at certain instances would matter.
154,981
I am a beginner learning about computer animation(for games). So far, the only method that I have come across is drawing each frame, every frame update. So at the start of every frame, the entire frame is erased, and then the things for that are needed that frame are redrawn. My question is whether or not this method is the only one that is used for making animations and games. It seems like it is a bit inefficient. I also don't quite understand how this method would work for ***3d*** games. Could someone please explain this in more detail?
2018/03/04
[ "https://gamedev.stackexchange.com/questions/154981", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/113139/" ]
Very old games used a technique where only those parts of a frame are redrawn that changed on that frame. What I can remember, the game "Little Big Adventure" uses this technique (1994). But you can see that the game has for most of the time a static camera. only when you move out of the visible area the scene is redrawn. If you play the game you would also notice a tiny lag on that frame. On modern GPUs with modern game engines, things have changed. Everything is redrawn on each frame. Depending on the rendering technique, things might even be rendered several times. The computing power of a GPU is just incredibly high when you use it correctly. But reuse is happening. For example an engine could decide to update the shadow map only every 5th frame. Or the lighting is not updated as long as there is no change in the light sources.
Before one can say whether video games "draw" the display every frame, it's first necessary to define what is meant by "draw". There are certainly many video games certainly do not all draw every frame by assembling a bitmap from scratch; indeed, many gaming platforms never assemble full bitmaps *at all*. There are a few approaches video games can take to generating a display. A very small number have the CPU turn the electron beam on and off or for every pixel or, for vector-scan games, set the XY coordinate of every dot to be plotted. Most games that do this do so largely for the purpose of demonstrating that the CPU is fast enough. More commonly games will have hardware which, in the absence of CPU involvement, would output some pattern of pixels or vectors to the display repeatedly. This pattern may be produced by reading data sequentially from a region of memory and interpreting each bit or group of bits as a pixel color (this is called a bit-map display). In some cases, hardware may read a byte of memory for each 8x8, 16x16, or other size region of the display and then use that byte to select a range of memory to read for pixel data (this is often called a character-map display). Some hardware platforms can overlay multiple bitmap displays with configurable positions. These are referred to as sprites. Some platforms do not allow the display pattern to be changed while it is being sent to the screen, but instead require that all updates occur after the beam has finished drawing one frame but before it has started drawing the next. On such platforms, everything that is going to appear on a frame needs to be loaded into the display hardware before the start of that frame, and the display will be limited to showing a pattern that can be set up all at once. If the CPU were to stop running while the frame is being shown, that same frame would keep being shown indefinitely. Other platforms do allow the pattern to be changed or reconfigured while it is being drawn to the screen. This makes it possible to show a screen which is much more complicated than the video circuitry could handle by itself. This may make it possible for a hardware platform which has eight sprites to show a larger number of movable objects by setting the positions of the top eight objects on the screen, waiting for the beam has reached a point somewhere between the bottom of the first object and the top of the ninth, setting the position of the ninth object, waiting for the beam to get between the bottom of the second object and top of the tenth (if it isn't already there), setting the position of the tenth object, etc. Note that this approach would require CPU involvement during every generated frame of video, even if none of the objects visibly move, but the CPU would not be involved with "drawing" each object. Most personal computer games use hardware configured to draw a single bitmap screen, and then draw onto that screen anything that needs to be different from what's already there. Sometimes it may be easier to draw things without regard for whether it is actually necessary in a particular case, but if code can easily tell that there's no reason for part of the screen to change, performance may be improved by skipping that part. Today's platforms are often fast enough that they could draw the entire screen many times over during the course of a frame, but historically that was not the case. The fastest possible code to write all the pixels on the Apple II computer's high resolution screen, for example, would take more than two frames, and the fastest possible code to copy all of the pixels on the Apple II computer's high resolution screen from another buffer would take twice that. Getting good performance required that games only update things that were actually changing, and that is what good games generally did.
265,617
I am using gnome on wayland on arch. I used to start my keyboards leds with xset led 3. How can this be accomplished while using wayland?
2016/02/25
[ "https://unix.stackexchange.com/questions/265617", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/148018/" ]
I also struggled with this and finally came up with a solution: <https://gist.github.com/ps1dr3x/b15c62eafb388ddf8bb7d3896d1a1cee> Basically you can turn on/off the keyboard backlight by changing the brightness value in /sys/class/leds/`input`/brightness e.g. ``` sudo sh -c 'echo 1 > /sys/class/leds/input0::scrolllock/brightness' ``` **P.s. `input` might be different**
Here is a suggested script to switch the keyboard lights on and off under Wayland. It finds the proper path then uses it with the command provided by @Michele above. ``` #!/bin/bash pathbeginswith=$(find /sys/class/leds -iname "*scrolllock") completepath="$pathbeginswith/brightness" if test "$(id -u)" -ne 0 ; then sudo "$0" "$1" exit $? fi value=`sudo cat $completepath` if [ $value -eq 0 ] then sudo echo '1' > $completepath else sudo echo '0' > $completepath fi ``` Please note I only have one keyboard with backlight connected, this could need tweaking if there are more than one, etc. This script requires sudo. I called it "kbdwaylandleds" and stored it in /usr/local/bin. Appending the following line to /etc/sudoers enables its usage without a sudo password: usernameXXX ALL = NOPASSWD:/usr/local/bin/kbdwaylandleds That way it can be added to gnome as a user script on session start for usernameXXX, and/or assigned to a keyboard shortcut.
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Use the [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) method: ```css @import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap'); ``` Obviously, "Open Sans" (`Open+Sans`) is the font that is imported. So replace it with yours. If the font's name has multiple words, URL-encode it by adding a `+` sign between each word, as I did. Make sure to place the `@import` at the very top of your CSS, before any rules. Google Fonts can automatically generate the `@import` directive for you. Once you have chosen a font, click the `(+)` icon next to it. In bottom-left corner, a container titled "1 Family Selected" will appear. Click it, and it will expand. Use the "Customize" tab to select options, and then switch back to "Embed" and click "@import" under "Embed Font". Copy the CSS between the `<style>` tags into your stylesheet. [![](https://i.stack.imgur.com/2rmPS.png)](https://i.stack.imgur.com/2rmPS.png)
Along with the above answers, do also consider this site; <https://google-webfonts-helper.herokuapp.com/fonts> Main Advantage: * **allows you to *self-host* those google fonts for better response times** Other Advantages : * choose your font(s) * choose your character set * choose your font styles/weight * choose your target browsers ( modern preferred ) * and u get the CSS snippets ( to add to your css stylesheet ) plus a zip of the font files to include in your project folder ( say css\_fonts ) In file **'your\_css\_theme.css'** add ``` /* open-sans-regular - latin - modern browsers */ @font-face { font-family: 'Open Sans'; font-style: normal; font-weight: 400; src: local(''), url('css_fonts/open-sans-v18-latin-regular.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url('css_fonts/open-sans-v18-latin-regular.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } body { font-family: 'Open Sans',sans-serif; } ```
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
``` <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&amp;lang=en" /> ``` Better to not use `@import`. Just use the `link` element, as shown above, in your layout's head.
1. Just go to <https://fonts.google.com/> 2. Add font by clicking **+** 3. Go to selected font > Embed > @IMPORT > copy url and paste in your .css file above body tag. 4. It's done.
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Use the [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) method: ```css @import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap'); ``` Obviously, "Open Sans" (`Open+Sans`) is the font that is imported. So replace it with yours. If the font's name has multiple words, URL-encode it by adding a `+` sign between each word, as I did. Make sure to place the `@import` at the very top of your CSS, before any rules. Google Fonts can automatically generate the `@import` directive for you. Once you have chosen a font, click the `(+)` icon next to it. In bottom-left corner, a container titled "1 Family Selected" will appear. Click it, and it will expand. Use the "Customize" tab to select options, and then switch back to "Embed" and click "@import" under "Embed Font". Copy the CSS between the `<style>` tags into your stylesheet. [![](https://i.stack.imgur.com/2rmPS.png)](https://i.stack.imgur.com/2rmPS.png)
``` <link href="https://fonts.googleapis.com/css?family=(any font of your choice)" rel="stylesheet" type="text/css"> ``` To choose the font you can visit the link : **<https://fonts.google.com>** *Write the font name of your choice from the website excluding the brackets.* **For example** you chose Lobster as a font of your choice then, ``` <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"> ``` *Then you can use this normally as a font-family in your whole HTML/CSS file.* **For example** ``` <h2 style="Lobster">Please Like This Answer</h2> ```
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Use the tag @import ``` @import url('http://fonts.googleapis.com/css?family=Kavoon'); ```
You can also use @font-face to link to the URLs. <http://www.css3.info/preview/web-fonts-with-font-face/> Does the CMS support iframes? You might be able to throw an iframe into the top of your content, too. This would probably be slower - better to include it in your CSS.
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Add the Below code in your CSS File to import Google Web Fonts. ``` @import url(https://fonts.googleapis.com/css?family=Open+Sans); ``` Replace the **Open+Sans** parameter value with your Font name. Your CSS file should look like: ``` @import url(https://fonts.googleapis.com/css?family=Open+Sans); body{ font-family: 'Open Sans',serif; } ```
You can also use @font-face to link to the URLs. <http://www.css3.info/preview/web-fonts-with-font-face/> Does the CMS support iframes? You might be able to throw an iframe into the top of your content, too. This would probably be slower - better to include it in your CSS.
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Use the tag @import ``` @import url('http://fonts.googleapis.com/css?family=Kavoon'); ```
We can easily do that in css3. We have to simply use @import statement. The following video easily describes the way how to do that. so go ahead and watch it out. <https://www.youtube.com/watch?v=wlPr6EF6GAo>
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Use the tag @import ``` @import url('http://fonts.googleapis.com/css?family=Kavoon'); ```
``` <link href="https://fonts.googleapis.com/css?family=(any font of your choice)" rel="stylesheet" type="text/css"> ``` To choose the font you can visit the link : **<https://fonts.google.com>** *Write the font name of your choice from the website excluding the brackets.* **For example** you chose Lobster as a font of your choice then, ``` <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"> ``` *Then you can use this normally as a font-family in your whole HTML/CSS file.* **For example** ``` <h2 style="Lobster">Please Like This Answer</h2> ```
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Add the Below code in your CSS File to import Google Web Fonts. ``` @import url(https://fonts.googleapis.com/css?family=Open+Sans); ``` Replace the **Open+Sans** parameter value with your Font name. Your CSS file should look like: ``` @import url(https://fonts.googleapis.com/css?family=Open+Sans); body{ font-family: 'Open Sans',serif; } ```
1. Go to <https://fonts.google.com/> and select your desired font family (you can search by name): [![Step 1: selecting a font](https://i.stack.imgur.com/8VBL5.jpg)](https://i.stack.imgur.com/8VBL5.jpg) 2. Select the desired variations (weight, italics, etc.): [![Step 2: selecting the variations](https://i.stack.imgur.com/9aK2C.jpg)](https://i.stack.imgur.com/9aK2C.jpg) 3. Click on *View selected families* button on the top right corner: [![Step 3: clicking on the view font family button](https://i.stack.imgur.com/ZOgeZ.jpg)](https://i.stack.imgur.com/ZOgeZ.jpg) 4. Select *@import* on the right panel to get the code: [![Step 4: getting the code](https://i.stack.imgur.com/u8RVy.png)](https://i.stack.imgur.com/u8RVy.png)
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Add the Below code in your CSS File to import Google Web Fonts. ``` @import url(https://fonts.googleapis.com/css?family=Open+Sans); ``` Replace the **Open+Sans** parameter value with your Font name. Your CSS file should look like: ``` @import url(https://fonts.googleapis.com/css?family=Open+Sans); body{ font-family: 'Open Sans',serif; } ```
Jus go through the link <https://developers.google.com/fonts/docs/getting_started> To import it to stylesheet use ``` @import url('https://fonts.googleapis.com/css?family=Open+Sans'); ```
14,676,613
I'm working with a CMS which I only have access to the CSS file. So, I can't include anything in the `<head>` of the document. I was wondering if there was a way to import the web font from within the CSS file?
2013/02/03
[ "https://Stackoverflow.com/questions/14676613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/579049/" ]
Along with the above answers, do also consider this site; <https://google-webfonts-helper.herokuapp.com/fonts> Main Advantage: * **allows you to *self-host* those google fonts for better response times** Other Advantages : * choose your font(s) * choose your character set * choose your font styles/weight * choose your target browsers ( modern preferred ) * and u get the CSS snippets ( to add to your css stylesheet ) plus a zip of the font files to include in your project folder ( say css\_fonts ) In file **'your\_css\_theme.css'** add ``` /* open-sans-regular - latin - modern browsers */ @font-face { font-family: 'Open Sans'; font-style: normal; font-weight: 400; src: local(''), url('css_fonts/open-sans-v18-latin-regular.woff2') format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url('css_fonts/open-sans-v18-latin-regular.woff') format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } body { font-family: 'Open Sans',sans-serif; } ```
1. Go to <https://fonts.google.com/> and select your desired font family (you can search by name): [![Step 1: selecting a font](https://i.stack.imgur.com/8VBL5.jpg)](https://i.stack.imgur.com/8VBL5.jpg) 2. Select the desired variations (weight, italics, etc.): [![Step 2: selecting the variations](https://i.stack.imgur.com/9aK2C.jpg)](https://i.stack.imgur.com/9aK2C.jpg) 3. Click on *View selected families* button on the top right corner: [![Step 3: clicking on the view font family button](https://i.stack.imgur.com/ZOgeZ.jpg)](https://i.stack.imgur.com/ZOgeZ.jpg) 4. Select *@import* on the right panel to get the code: [![Step 4: getting the code](https://i.stack.imgur.com/u8RVy.png)](https://i.stack.imgur.com/u8RVy.png)
50,356,897
I created a cloud dataproc cluster and in my initialization script I try to install libopencv-dev but I keep getting unmet dependencies error: ``` sudo apt-get install libopencv-dev Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: libopencv-dev : Depends: libopencv-objdetect-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libopencv-highgui-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libopencv-legacy-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libopencv-contrib-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libopencv-videostab-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libopencv-superres-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libopencv-ocl-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libcv-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libhighgui-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed Depends: libcvaux-dev (= 2.4.9.1+dfsg-1+deb8u1) but it is not going to be installed E: Unable to correct problems, you have held broken packages. ``` I don't know what is wrong, I tried to create a compute engine with debian 8 and ran the same command on it and it works correctly but not on the machines created for the dataproc cluster, does anyone know what is the issue?
2018/05/15
[ "https://Stackoverflow.com/questions/50356897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1356645/" ]
It seems they use backports so to install libopencv-dev I had to install it from the backports repo with this command: ``` sudo apt-get -t jessie-backports install libopencv-dev ```
Try installing with aptitude Run the following sudo apt install aptitude -y sudo aptitude install libopencv-dev
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
using cell2struct is by far the fastest method I could figure out. Just check the following code to make a comparison: ``` clear; N = 10000; cel2s=0; repm=0; for i=1:100 a=0.0; b=0.0; tic; a = cell2struct(cell(1,N), {'x'}, 1 ); cel2s = cel2s + toc; tic; b = repmat(struct('x',1), N, 1 ); repm = repm + toc; end disp(['cell2struct preallocation: ', num2str(cel2s/100)]); disp(['repmat preallocation : ', num2str(repm/100)]); disp(['speedup : ', num2str(fix( repm/cel2s ) ) , ' X']); ``` Typical results show a mean speedup around **19 times!** wrt repmat method: ``` cell2struct preallocation: 1.4636e-05 repmat preallocation : 0.00028794 speedup : 19 X ```
According to [this answer](https://stackoverflow.com/a/13336106/311834), there's also another way to do it: ``` [a.x] = deal(val); ``` where `val` is the value you want to assign to *every* element of the struct. The effect of this command is different from those of the others, as every `x` field of every structure `a` will be assigned the `val` value.
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
The way this is supposed to be done, and the simplest is ``` a=struct('x',cell(1,N)); ``` If you fix the missing "tic" and add this method to the benchmarking code presented by jerad, the method I propose above is a bit slower than repmat but much simpler to implement, here is the output: ``` No preallocation: 0.10137 Preallocate Indexing: 0.07615 Preallocate with repmat: 0.01458 Preallocate with struct: 0.07588 ``` The reason that repmat is faster is because a value to each 'x' field is assigned during the pre-allocation, instead of leaving it empty. If the above pre-allocation technique is changed so we start with all the x fields with a value (one) assigned, like this: ``` a=cell(1,N); a(:)={1}; d=struct('x',a); ``` Then, the benchmarking improves a lot, been very close or some time faster than repmat. The difference is so small that every time I run it it changes which one is faster. Here an output example: ``` No preallocation: 0.0962 Preallocate Indexing: 0.0745 Preallocate with repmat: 0.0259 Preallocate with struct: 0.0184 ``` Conversely, if the repmat pre-allocation is changed to set the field empty, like this ``` b = repmat( struct( 'x', {} ), N, 1 ); ``` All the speed advantage is lost
Instead of pre-allocating the array of structs it may be easier to reverse the loop. In this way the array is allocated in the first iteration and the rest of the iterations are used to fill the structs. ``` a = [] for i = 100:-1:1 a(i).x = i; end ```
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
There's a bunch of ways you can initialize a structure. For example, you can use the `struct` command: ``` a(1:100) = struct('x',[]); ``` which sets all fields `x` to empty. You can also use `deal` to create and fill the structure if you know what data should go in there ``` xx = num2cell(1:100); [a(1:100).x]=deal(xx{:}); a(99).x ans = 99 ``` Or you can use `struct` again (note that if a field of the structure should be a cell array, the cell needs to be enclosed in curly brackets!) ``` a = struct('x',xx) ```
The way this is supposed to be done, and the simplest is ``` a=struct('x',cell(1,N)); ``` If you fix the missing "tic" and add this method to the benchmarking code presented by jerad, the method I propose above is a bit slower than repmat but much simpler to implement, here is the output: ``` No preallocation: 0.10137 Preallocate Indexing: 0.07615 Preallocate with repmat: 0.01458 Preallocate with struct: 0.07588 ``` The reason that repmat is faster is because a value to each 'x' field is assigned during the pre-allocation, instead of leaving it empty. If the above pre-allocation technique is changed so we start with all the x fields with a value (one) assigned, like this: ``` a=cell(1,N); a(:)={1}; d=struct('x',a); ``` Then, the benchmarking improves a lot, been very close or some time faster than repmat. The difference is so small that every time I run it it changes which one is faster. Here an output example: ``` No preallocation: 0.0962 Preallocate Indexing: 0.0745 Preallocate with repmat: 0.0259 Preallocate with struct: 0.0184 ``` Conversely, if the repmat pre-allocation is changed to set the field empty, like this ``` b = repmat( struct( 'x', {} ), N, 1 ); ``` All the speed advantage is lost
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
Using `repmat` is by far the most efficient way to preallocate structs : ``` N = 10000; b = repmat(struct('x',1), N, 1 ); ``` This is **~10x faster** using Matlab 2011a than preallocating via indexing, as in ``` N = 10000; b(N).x = 1 ``` The indexing method is only marginally faster than not preallocating. ``` No preallocation: 0.075524 Preallocate Using indexing: 0.063774 Preallocate with repmat: 0.005234 ``` --- --- Code below in case you want to verify. ``` clear; N = 10000; %1) GROWING A STRUCT tic; for ii=1:N a(ii).x(1)=1; end noPreAll = toc; %2)PREALLOCATING A STRUCT tic; b = repmat( struct( 'x', 1 ), N, 1 ); for ii=1:N b(ii).x(1)=1; end; repmatBased=toc; %3)Index to preallocate tic; c(N).x = 1; for ii=1:N c(ii).x(1)=1; end; preIndex=toc; disp(['No preallocation: ' num2str(noPreAll)]) disp(['Preallocate Indexing: ' num2str(preIndex)]) disp(['Preallocate with repmat: ' num2str(repmatBased)]) ``` Results in command window: ``` No preallocation: 0.075524 Preallocate Indexing: 0.063774 Preallocate with repmat: 0.0052338 >> ``` **P.S.** I'd be interested to know why this is true, if anyone can explain it.
using cell2struct is by far the fastest method I could figure out. Just check the following code to make a comparison: ``` clear; N = 10000; cel2s=0; repm=0; for i=1:100 a=0.0; b=0.0; tic; a = cell2struct(cell(1,N), {'x'}, 1 ); cel2s = cel2s + toc; tic; b = repmat(struct('x',1), N, 1 ); repm = repm + toc; end disp(['cell2struct preallocation: ', num2str(cel2s/100)]); disp(['repmat preallocation : ', num2str(repm/100)]); disp(['speedup : ', num2str(fix( repm/cel2s ) ) , ' X']); ``` Typical results show a mean speedup around **19 times!** wrt repmat method: ``` cell2struct preallocation: 1.4636e-05 repmat preallocation : 0.00028794 speedup : 19 X ```
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
There's a nice discussion about this in [Loren on the Art of MATLAB](http://blogs.mathworks.com/loren/2008/02/01/structure-initialization/) blog. If I understand you correctly, here's a ways to initialize the struct you want: ``` a(100).x = 100; ``` With this method, we can see that elements are filled in with empty arrays.
Instead of pre-allocating the array of structs it may be easier to reverse the loop. In this way the array is allocated in the first iteration and the rest of the iterations are used to fill the structs. ``` a = [] for i = 100:-1:1 a(i).x = i; end ```
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
The way this is supposed to be done, and the simplest is ``` a=struct('x',cell(1,N)); ``` If you fix the missing "tic" and add this method to the benchmarking code presented by jerad, the method I propose above is a bit slower than repmat but much simpler to implement, here is the output: ``` No preallocation: 0.10137 Preallocate Indexing: 0.07615 Preallocate with repmat: 0.01458 Preallocate with struct: 0.07588 ``` The reason that repmat is faster is because a value to each 'x' field is assigned during the pre-allocation, instead of leaving it empty. If the above pre-allocation technique is changed so we start with all the x fields with a value (one) assigned, like this: ``` a=cell(1,N); a(:)={1}; d=struct('x',a); ``` Then, the benchmarking improves a lot, been very close or some time faster than repmat. The difference is so small that every time I run it it changes which one is faster. Here an output example: ``` No preallocation: 0.0962 Preallocate Indexing: 0.0745 Preallocate with repmat: 0.0259 Preallocate with struct: 0.0184 ``` Conversely, if the repmat pre-allocation is changed to set the field empty, like this ``` b = repmat( struct( 'x', {} ), N, 1 ); ``` All the speed advantage is lost
According to [this answer](https://stackoverflow.com/a/13336106/311834), there's also another way to do it: ``` [a.x] = deal(val); ``` where `val` is the value you want to assign to *every* element of the struct. The effect of this command is different from those of the others, as every `x` field of every structure `a` will be assigned the `val` value.
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
Using `repmat` is by far the most efficient way to preallocate structs : ``` N = 10000; b = repmat(struct('x',1), N, 1 ); ``` This is **~10x faster** using Matlab 2011a than preallocating via indexing, as in ``` N = 10000; b(N).x = 1 ``` The indexing method is only marginally faster than not preallocating. ``` No preallocation: 0.075524 Preallocate Using indexing: 0.063774 Preallocate with repmat: 0.005234 ``` --- --- Code below in case you want to verify. ``` clear; N = 10000; %1) GROWING A STRUCT tic; for ii=1:N a(ii).x(1)=1; end noPreAll = toc; %2)PREALLOCATING A STRUCT tic; b = repmat( struct( 'x', 1 ), N, 1 ); for ii=1:N b(ii).x(1)=1; end; repmatBased=toc; %3)Index to preallocate tic; c(N).x = 1; for ii=1:N c(ii).x(1)=1; end; preIndex=toc; disp(['No preallocation: ' num2str(noPreAll)]) disp(['Preallocate Indexing: ' num2str(preIndex)]) disp(['Preallocate with repmat: ' num2str(repmatBased)]) ``` Results in command window: ``` No preallocation: 0.075524 Preallocate Indexing: 0.063774 Preallocate with repmat: 0.0052338 >> ``` **P.S.** I'd be interested to know why this is true, if anyone can explain it.
There's a bunch of ways you can initialize a structure. For example, you can use the `struct` command: ``` a(1:100) = struct('x',[]); ``` which sets all fields `x` to empty. You can also use `deal` to create and fill the structure if you know what data should go in there ``` xx = num2cell(1:100); [a(1:100).x]=deal(xx{:}); a(99).x ans = 99 ``` Or you can use `struct` again (note that if a field of the structure should be a cell array, the cell needs to be enclosed in curly brackets!) ``` a = struct('x',xx) ```
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
using cell2struct is by far the fastest method I could figure out. Just check the following code to make a comparison: ``` clear; N = 10000; cel2s=0; repm=0; for i=1:100 a=0.0; b=0.0; tic; a = cell2struct(cell(1,N), {'x'}, 1 ); cel2s = cel2s + toc; tic; b = repmat(struct('x',1), N, 1 ); repm = repm + toc; end disp(['cell2struct preallocation: ', num2str(cel2s/100)]); disp(['repmat preallocation : ', num2str(repm/100)]); disp(['speedup : ', num2str(fix( repm/cel2s ) ) , ' X']); ``` Typical results show a mean speedup around **19 times!** wrt repmat method: ``` cell2struct preallocation: 1.4636e-05 repmat preallocation : 0.00028794 speedup : 19 X ```
Instead of pre-allocating the array of structs it may be easier to reverse the loop. In this way the array is allocated in the first iteration and the rest of the iterations are used to fill the structs. ``` a = [] for i = 100:-1:1 a(i).x = i; end ```
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
There's a nice discussion about this in [Loren on the Art of MATLAB](http://blogs.mathworks.com/loren/2008/02/01/structure-initialization/) blog. If I understand you correctly, here's a ways to initialize the struct you want: ``` a(100).x = 100; ``` With this method, we can see that elements are filled in with empty arrays.
According to [this answer](https://stackoverflow.com/a/13336106/311834), there's also another way to do it: ``` [a.x] = deal(val); ``` where `val` is the value you want to assign to *every* element of the struct. The effect of this command is different from those of the others, as every `x` field of every structure `a` will be assigned the `val` value.
13,664,098
Why am I getting the error `Input string was not in a correct format`. in this line of my code? ``` Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) ``` Below is the full code I am using it with: ``` foreach (ListViewItem iiii in listView1.Items) { if (Convert.ToInt32(listView1.Items[4].SubItems[4].ToString()) <= Convert.ToInt32(tenthousand.ToString())) { message2 = "GREAT"; msgColor2 = System.Drawing.Color.Green; break; // no need to check any more items - we have a match! } labelVideoViews2.Text = message2; labelVideoViews2.ForeColor = msgColor2; } ```
2012/12/01
[ "https://Stackoverflow.com/questions/13664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801629/" ]
Using `repmat` is by far the most efficient way to preallocate structs : ``` N = 10000; b = repmat(struct('x',1), N, 1 ); ``` This is **~10x faster** using Matlab 2011a than preallocating via indexing, as in ``` N = 10000; b(N).x = 1 ``` The indexing method is only marginally faster than not preallocating. ``` No preallocation: 0.075524 Preallocate Using indexing: 0.063774 Preallocate with repmat: 0.005234 ``` --- --- Code below in case you want to verify. ``` clear; N = 10000; %1) GROWING A STRUCT tic; for ii=1:N a(ii).x(1)=1; end noPreAll = toc; %2)PREALLOCATING A STRUCT tic; b = repmat( struct( 'x', 1 ), N, 1 ); for ii=1:N b(ii).x(1)=1; end; repmatBased=toc; %3)Index to preallocate tic; c(N).x = 1; for ii=1:N c(ii).x(1)=1; end; preIndex=toc; disp(['No preallocation: ' num2str(noPreAll)]) disp(['Preallocate Indexing: ' num2str(preIndex)]) disp(['Preallocate with repmat: ' num2str(repmatBased)]) ``` Results in command window: ``` No preallocation: 0.075524 Preallocate Indexing: 0.063774 Preallocate with repmat: 0.0052338 >> ``` **P.S.** I'd be interested to know why this is true, if anyone can explain it.
According to [this answer](https://stackoverflow.com/a/13336106/311834), there's also another way to do it: ``` [a.x] = deal(val); ``` where `val` is the value you want to assign to *every* element of the struct. The effect of this command is different from those of the others, as every `x` field of every structure `a` will be assigned the `val` value.
44,650,508
I have a simple case where I want to use pattern matching to identify the algorithm I need to use to perform a collision test between two generic Octrees. My basic case is two Octrees of triangles. The skeleton of the code is. ``` public class Triangle { public static bool Intersects ( IReadOnlyList<Triangle> ta , IReadOnlyList<Triangle> tb) { ... } } public class Octree<T> { public bool Intersects<U>(Octree<U> other) { if (this is Octree<Triangle> ota && other is Octree<Triangle> otb) { return ota.Intersects( otb, Triangle.Intersects ); } throw new NotImplementedException(); } public bool Intersects<U> ( Octree<U> other , Func<IReadOnlyList<T>, IReadOnlyList<U>, bool> intersectsLeaves ) { ... } } ``` but results in the below error. [![enter image description here](https://i.stack.imgur.com/hhoni.png)](https://i.stack.imgur.com/hhoni.png) ``` Error CS8121 An expression of type Octree<T> cannot be handled by a pattern of type Octree<Triangle>. ``` Of course I can just use `typeof(U)` and `typeof(T)` to do the tests but I thought the above should really work. Why doesn't it?
2017/06/20
[ "https://Stackoverflow.com/questions/44650508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158285/" ]
Pattern matching in C# 7.0 has a requirement stating that there must be an explicit or implicit conversion from the left-hand-side type to the right-hand-side type. In C# 7.1, the spec will be expanded so that either the left-hand-side or the right-hand-side can be an open type.
its a bug. take a look at this: <https://github.com/dotnet/roslyn/issues/16195>
44,650,508
I have a simple case where I want to use pattern matching to identify the algorithm I need to use to perform a collision test between two generic Octrees. My basic case is two Octrees of triangles. The skeleton of the code is. ``` public class Triangle { public static bool Intersects ( IReadOnlyList<Triangle> ta , IReadOnlyList<Triangle> tb) { ... } } public class Octree<T> { public bool Intersects<U>(Octree<U> other) { if (this is Octree<Triangle> ota && other is Octree<Triangle> otb) { return ota.Intersects( otb, Triangle.Intersects ); } throw new NotImplementedException(); } public bool Intersects<U> ( Octree<U> other , Func<IReadOnlyList<T>, IReadOnlyList<U>, bool> intersectsLeaves ) { ... } } ``` but results in the below error. [![enter image description here](https://i.stack.imgur.com/hhoni.png)](https://i.stack.imgur.com/hhoni.png) ``` Error CS8121 An expression of type Octree<T> cannot be handled by a pattern of type Octree<Triangle>. ``` Of course I can just use `typeof(U)` and `typeof(T)` to do the tests but I thought the above should really work. Why doesn't it?
2017/06/20
[ "https://Stackoverflow.com/questions/44650508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/158285/" ]
There is a work around to the bug/feature. You can use the **Try\*** pattern with inline declared outvariables. ``` bool TryIs<TU>(object t, out TU u) { if (t is TU uu) { u = uu; return true; } u = default(TU); return false; } ``` then you can use it like ``` public bool Intersects<U>(Octree<U> other) { if ( TryIs<Octree<Triangle>>(out var ota) && TryIs<Octree<Triangle>>(out var otb)) { return ota.Intersects( otb, Triangle.Intersects ); } throw new NotImplementedException(); } ```
its a bug. take a look at this: <https://github.com/dotnet/roslyn/issues/16195>
3,085,796
Show that any null sequence $(a\_n)\_{n\in\mathbb R}, \ a\_n\neq 0$ fulfils $$\lim\_{n\to\infty}\frac{\sqrt{1+a\_n}-1}{a\_n}=\frac{1}{2}\tag{1}$$ Was wondering if my approach is valid. Let's assume that $\lim\_{n\to\infty}a\_n$ exists and that $\lim\_{n\to\infty}=0$ then we know that $\lim\_{n\to\infty} (\sqrt{1+a\_n} -1)$ also exists. So we can write: $$\lim\_{n\to\infty}\frac{\sqrt{1+a\_n}-1}{a\_n}=\frac{\lim\_{n\to\infty}\sqrt{1+a\_n}-1}{\lim\_{n\to\infty}a\_n}=\frac{1}{2}\tag{2}$$ Now we know that we can rewrite this to $$\lim\_{n\to\infty}\sqrt{1+a\_n}-1 = \frac{1}{2}\lim\_{n\to\infty}a\_n\tag{3}$$ We use the fact that the square root is continuous: $$\lim\_{n\to\infty}\sqrt{1+a\_n}-1=\sqrt{\lim\_{n\to\infty}1+a\_n}-1 = \frac{1}{2}\lim\_{n\to\infty}a\_n\tag{4}$$ We get $$\sqrt{1+0}-1=\frac{1}{2}\cdot 0\tag{5}$$ So the equation does hold for any null sequence $a\_n$. **Question:** Is there any flaw here?
2019/01/24
[ "https://math.stackexchange.com/questions/3085796", "https://math.stackexchange.com", "https://math.stackexchange.com/users/33176/" ]
You divide by zero, which is not allowed. If you know a bit of calculus you can find the solution by examining the derivative of the root function at the point x=1.
Multiply numerator and denominator by $$\sqrt{1+a\_n}+1$$
3,085,796
Show that any null sequence $(a\_n)\_{n\in\mathbb R}, \ a\_n\neq 0$ fulfils $$\lim\_{n\to\infty}\frac{\sqrt{1+a\_n}-1}{a\_n}=\frac{1}{2}\tag{1}$$ Was wondering if my approach is valid. Let's assume that $\lim\_{n\to\infty}a\_n$ exists and that $\lim\_{n\to\infty}=0$ then we know that $\lim\_{n\to\infty} (\sqrt{1+a\_n} -1)$ also exists. So we can write: $$\lim\_{n\to\infty}\frac{\sqrt{1+a\_n}-1}{a\_n}=\frac{\lim\_{n\to\infty}\sqrt{1+a\_n}-1}{\lim\_{n\to\infty}a\_n}=\frac{1}{2}\tag{2}$$ Now we know that we can rewrite this to $$\lim\_{n\to\infty}\sqrt{1+a\_n}-1 = \frac{1}{2}\lim\_{n\to\infty}a\_n\tag{3}$$ We use the fact that the square root is continuous: $$\lim\_{n\to\infty}\sqrt{1+a\_n}-1=\sqrt{\lim\_{n\to\infty}1+a\_n}-1 = \frac{1}{2}\lim\_{n\to\infty}a\_n\tag{4}$$ We get $$\sqrt{1+0}-1=\frac{1}{2}\cdot 0\tag{5}$$ So the equation does hold for any null sequence $a\_n$. **Question:** Is there any flaw here?
2019/01/24
[ "https://math.stackexchange.com/questions/3085796", "https://math.stackexchange.com", "https://math.stackexchange.com/users/33176/" ]
Regarding your question whether there is a flaw: You need to be careful with mixing the assumptions and what you actually want to prove. You cannot use $$\lim\_{n\to\infty}\frac{\sqrt{1+a\_n}-1}{a\_n}=\frac{1}{2}$$ in (2) because this is what you actually want to prove! Even if the following steps are equivalences (and you have to be very careful there, in particular with square roots), it is confusing at best and therefore not a very solid proof. Therefore my advice: Try writing proofs in a way that you start with the assumptions and end up with the result instead of mixing the result in somewhere in the middle and conclude with a tautology. This will save you from a lot of trouble and also makes your proofs much easier to read.
Multiply numerator and denominator by $$\sqrt{1+a\_n}+1$$
3,085,796
Show that any null sequence $(a\_n)\_{n\in\mathbb R}, \ a\_n\neq 0$ fulfils $$\lim\_{n\to\infty}\frac{\sqrt{1+a\_n}-1}{a\_n}=\frac{1}{2}\tag{1}$$ Was wondering if my approach is valid. Let's assume that $\lim\_{n\to\infty}a\_n$ exists and that $\lim\_{n\to\infty}=0$ then we know that $\lim\_{n\to\infty} (\sqrt{1+a\_n} -1)$ also exists. So we can write: $$\lim\_{n\to\infty}\frac{\sqrt{1+a\_n}-1}{a\_n}=\frac{\lim\_{n\to\infty}\sqrt{1+a\_n}-1}{\lim\_{n\to\infty}a\_n}=\frac{1}{2}\tag{2}$$ Now we know that we can rewrite this to $$\lim\_{n\to\infty}\sqrt{1+a\_n}-1 = \frac{1}{2}\lim\_{n\to\infty}a\_n\tag{3}$$ We use the fact that the square root is continuous: $$\lim\_{n\to\infty}\sqrt{1+a\_n}-1=\sqrt{\lim\_{n\to\infty}1+a\_n}-1 = \frac{1}{2}\lim\_{n\to\infty}a\_n\tag{4}$$ We get $$\sqrt{1+0}-1=\frac{1}{2}\cdot 0\tag{5}$$ So the equation does hold for any null sequence $a\_n$. **Question:** Is there any flaw here?
2019/01/24
[ "https://math.stackexchange.com/questions/3085796", "https://math.stackexchange.com", "https://math.stackexchange.com/users/33176/" ]
Regarding your question whether there is a flaw: You need to be careful with mixing the assumptions and what you actually want to prove. You cannot use $$\lim\_{n\to\infty}\frac{\sqrt{1+a\_n}-1}{a\_n}=\frac{1}{2}$$ in (2) because this is what you actually want to prove! Even if the following steps are equivalences (and you have to be very careful there, in particular with square roots), it is confusing at best and therefore not a very solid proof. Therefore my advice: Try writing proofs in a way that you start with the assumptions and end up with the result instead of mixing the result in somewhere in the middle and conclude with a tautology. This will save you from a lot of trouble and also makes your proofs much easier to read.
You divide by zero, which is not allowed. If you know a bit of calculus you can find the solution by examining the derivative of the root function at the point x=1.
1,961,805
I am trying to create a way to show and hide a number of different elements on my page, depending if the user is logged in or not. For example I want to hide 'Logout' is users are not logged in, and 'login' when they are. I'm using Coldfusion and Dreamweaver - is there any quick easy code I am able to use to wrap around the page elements I want to hide? Thanks for any help. Georgia.
2009/12/25
[ "https://Stackoverflow.com/questions/1961805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237850/" ]
Generically, if you have a session variable called "loggedIn" and (assuming it's boolean) it's as simple as: ``` <cfif session.loggedIn> <!--- display logged in code ---> </cfif ``` OR ``` <cfif NOT session.loggedIn> <!--- display not logged in code ---> </cfif> ``` But, I mean, it really depends on how you're tracking whether a user is logged in or not.
If you are using the standard CFLOGIN built into Coldfusion you can show/hide elements by checking for a logged in user: ``` <cfif GetAuthUser() neq ""> Show Logout button </cfif> ``` <http://livedocs.adobe.com/coldfusion/8/Tags_j-l_07.html>
1,961,805
I am trying to create a way to show and hide a number of different elements on my page, depending if the user is logged in or not. For example I want to hide 'Logout' is users are not logged in, and 'login' when they are. I'm using Coldfusion and Dreamweaver - is there any quick easy code I am able to use to wrap around the page elements I want to hide? Thanks for any help. Georgia.
2009/12/25
[ "https://Stackoverflow.com/questions/1961805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237850/" ]
Generically, if you have a session variable called "loggedIn" and (assuming it's boolean) it's as simple as: ``` <cfif session.loggedIn> <!--- display logged in code ---> </cfif ``` OR ``` <cfif NOT session.loggedIn> <!--- display not logged in code ---> </cfif> ``` But, I mean, it really depends on how you're tracking whether a user is logged in or not.
If you are using Dreamweaver's Log In User server behavior, then it creates a session variable named MM\_Username (Session.MM\_Username) that contains the user name from the log in form. When that variable exists and is not an empty string, then the user is considered logged in. All you should need to do is to check for the existance of that vairable and it not being an empty string. My CF is rusty, and I don't have a system with ColdFusion installed to be able to give you tested code, but it should be something along the lines of the following: ``` <cfif IsDefined(Session.MM_Username) And Session.MM_Username NEQ ""> Logout link here <cfelse> Log in link here </cfif> ``` FYI: The Log Out User server behavior sets that session variable to an empty string rather than destroying the variable, that's why you need to check for it not being an empty string using the Dreamweaver Log in/out server behaviors.
2,337,438
I came across a weird situation when trying to count the number of rows that DO NOT have varchar values specified by a select statement. Ok, that sounds confusing even to me, so let me give you an example: Let's say I have a field "MyField" in "SomeTable" and I want to count in how many rows MyField values do not belong to a domain defined by the values of "MyOtherField" in "SomeOtherTable". In other words, suppose that I have MyOtherField = {1, 2, 3}, I wanna count in how many rows MyField value are not 1, 2 or 3. For that, I'd use the following query: ``` SELECT COUNT(*) FROM SomeTable WHERE ([MyField] NOT IN (SELECT MyOtherField FROM SomeOtherTable)) ``` And it works like a charm. Notice however that MyField and MyOtherField are int typed. If I try to run the exact same query, except for varchar typed fields, its returning value is 0 even though I know that there are wrong values, I put them there! And if I, however, try to count the opposite (how many rows ARE in the domain opposed to what I want that is how many rows are not) simply by supressing the "NOT" clause in the query above... Well, THAT works! ¬¬ Yeah, there must be tons of workarounds to this but I'd like to know why it doesn't work the way it should. Furthermore, I can't simply alter the whole query as most of it is built inside a C# code and basically the only part I have freedom to change that won't have an impact in any other part of the software is the select statement that corresponds to the domain (whatever comes in the NOT IN clause). I hope I made myself clear and someone out there could help me out. Thanks in advance.
2010/02/25
[ "https://Stackoverflow.com/questions/2337438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/251581/" ]
For NOT IN, it is always false if the subquery returns a NULL value. The accepted answer to [this question](https://stackoverflow.com/questions/129077/sql-not-in-constraint-and-null-values) elegantly describes why. The NULLability of a column value is independent of the datatype used too: most likely your varchar columns has NULL values Do deal with this, use NOT EXISTS. For non-null values, it works the same as NOT IN so is compatible ``` SELECT COUNT(*) FROM SomeTable S1 WHERE NOT EXISTS (SELECT * FROm SomeOtherTable S2 WHERE S1.[MyField] = S2.MyOtherField) ```
gbn has a more complete answer, but I can't be bothered to remember all that. Instead I have the religious habit of filtering nulls out of my IN clauses: ``` SELECT COUNT(*) FROM SomeTable WHERE [MyField] NOT IN ( SELECT MyOtherField FROM SomeOtherTable WHERE MyOtherField is not null ) ```
539,666
In Larry Wasserman's book "All of statistics" on p.151 there is the definition of a one-sided test: > > A test of the form > > $H\_0: \theta \le \theta\_0~~$ versus $~~H\_1: \theta \gt \theta\_0$ > > or > > $H\_0: \theta \ge \theta\_0~~$ versus $~~H\_1: \theta \lt \theta\_0$ > > is called a one-sided test > > > And in the probability course [website](https://www.probabilitycourse.com/chapter8/8_4_3_hypothesis_testing_for_mean.php) there is exactly the same definition. So this definition looks quite popular and widespread. I want to know how to properly name tests in which only one hypothesis is one-sided? For example, can we call the following tests one-sided (I think the first two of them are widespread enough): $H\_0: \theta = \theta\_0~~$ versus $~~H\_1: \theta \gt \theta\_0$ $H\_0: \theta = \theta\_0~~$ versus $~~H\_1: \theta \lt \theta\_0$ $H\_0: \theta \lt \theta\_0~~$ versus $~~H\_1: \theta = \theta\_0$ $H\_0: \theta \gt \theta\_0~~$ versus $~~H\_1: \theta = \theta\_0$
2021/08/09
[ "https://stats.stackexchange.com/questions/539666", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/172777/" ]
$H\_0: \theta = \theta\_0$ versus $H\_1: \theta \gt \theta\_0$ is OK, but some authors might write $H\_0: \theta \le \theta\_0$ versus $H\_1: \theta \gt \theta\_0.$ $H\_0: \theta = \theta\_0$ versus $H\_1: \theta \lt \theta\_0$ is OK, but some authors might write $H\_0: \theta \ge \theta\_0$ versus $H\_1: \theta \lt \theta\_0.$ In each instance above, a test of $H\_0$ would use $\theta = \theta\_0$ to get the null distribution, used to compute the P-value of the test. Both of the formulations below are wrong, because $H\_0$ must always contain an $=$-sign, whether as $\theta = \theta\_0,$ $\theta \le \theta\_0,$ or as $\theta \ge \theta\_0.$ $H\_0: \theta < \theta\_0$ versus $H\_1: \theta = \theta\_0.$ $H\_0: \theta > \theta\_0$ versus $H\_1: \theta = \theta\_0.$
It would be more appropriate to write them this way. $H\_0: \theta = \theta\_0~~$ versus $~~H\_1: \theta \ne \theta\_0$ (two-sided) $H\_0: \theta \le \theta\_0~~$ versus $~~H\_1: \theta > \theta\_0$ (one-sided [upper-tailed]) $H\_0: \theta \ge \theta\_0~~$ versus $~~H\_1: \theta < \theta\_0$ (one-sided [lower-tailed])
8,169,297
I have this Javascript snippet in my application to prevent clickjacking: ``` <script language="javascript" type="text/javascript"> var style = document.createElement('style'); style.type = "text/css"; style.id = "antiClickjack"; style.innerHTML = "body{display:none !important;}"; document.head.appendChild(style); if (self === top) { var antiClickjack = document.getElementById("antiClickjack"); antiClickjack.parentNode.removeChild(antiClickjack); } else { top.location = self.location; } </script> ``` Basically, it creates a style element (CSS on the fly) to hide the body of the current page by default. Then, *if it doesn't* detect clickjacking, it deletes it. So, doing it this way, everyone who doesn't have Javascript can see the page too (although they won't be protected from clickjacking). It works for every browser except for Internet Explorer, which throws a **Unknown runtime error** exception. Does someone have a suggestion on how to fix this? Thanks :-)
2011/11/17
[ "https://Stackoverflow.com/questions/8169297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2612112/" ]
You can't set the content of a `<style>` element via `innerHTML`. I think the correct property name is `cssText` but I'll have to check MSDN. *edit* — yup that's it. Thus your code can do this: ``` var style = document.createElement('style'); style.type = "text/css"; style.id = "antiClickjack"; if ('cssText' in style) style.cssText = "body{display:none !important;}"; else style.innerHTML = "body{display:none !important;}"; ```
In the document HEAD element, add the following: ``` <style id="antiClickjack">body{display:none !important;}</style> <script type="text/javascript"> if (self === top) { var antiClickjack = document.getElementById("antiClickjack"); antiClickjack.parentNode.removeChild(antiClickjack); } else { top.location = self.location; } </script> ```
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
There is a famous example: A compact separable metric space, two different finite Borel measures on the space, but the two measures agree with each other on all of the balls for the metric. R. O. Davies, "Measures not approximable or not specifiable by means of balls." Mathematika 18 (1971) 157--160
Consider the $\sigma$-algebra given by all subsets of $\{a,b,c\}$. It is generated by $A = \{a,b\}$ and $C = \{b,c\}$. Let $\mu(A) = \mu(C) = 1$. It could be that $\mu(\{a\}) = \mu(\{b\}) = \mu(\{c\}) = \frac{1}{2}$. It could also be that $\mu(\{a\}) = \mu(\{c\}) = \frac{1}{3}$ and $\mu(\{b\}) = \frac{2}{3}$.
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
Consider the $\sigma$-algebra given by all subsets of $\{a,b,c\}$. It is generated by $A = \{a,b\}$ and $C = \{b,c\}$. Let $\mu(A) = \mu(C) = 1$. It could be that $\mu(\{a\}) = \mu(\{b\}) = \mu(\{c\}) = \frac{1}{2}$. It could also be that $\mu(\{a\}) = \mu(\{c\}) = \frac{1}{3}$ and $\mu(\{b\}) = \frac{2}{3}$.
Caratheodory’s measure extension theorem.: Theorem 1.41 (Caratheodory). Let $A ⊂ 2^Ω$ be a ring and let $µ$ be a $σ$-finite premeasure on $A$. There exists a unique measure $µ'$ on $σ(A)$ such that $µ'(E) = µ(E)$ for all $E ∈ A$. Furthermore, $µ'$ is $σ$-finite. p. 19 of <http://www.math.unipd.it/~daipra/didattica/galileiana-15/Parte-I.pdf> (The same is given on p. 14 of here: <http://www.mathematik.uni-kl.de/~wwwstoch-alt/skripte/basicmeasuretheory_skript.pdf> and here: <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem> ) premeasure is a $σ$-additive set function $\mu$ to $[0,\infty]$ with $\mu(\emptyset)=0$. Ring contains $\emptyset$ and is closed w.r.t. unions of two elements and complements.
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
There is a famous example: A compact separable metric space, two different finite Borel measures on the space, but the two measures agree with each other on all of the balls for the metric. R. O. Davies, "Measures not approximable or not specifiable by means of balls." Mathematika 18 (1971) 157--160
Consider flipping two coins. Let $A$ be the event that the first coin is heads, and $B$ the event that the second coin is heads. $A$ and $B$ together generate the $\sigma$-algebra of all possible events. Suppose we know that $P(A) = P(B) = 1/2$ (i.e. each coin is unbiased). This is not enough information to determine whether the two coins are independent, so $P$ is not completely determined. This is the same counterexample that I gave in [this answer to another question](https://math.stackexchange.com/a/8184/822). In its notation, $P$ and $Q$ agree on the events in $\mathcal{L}$, and $\sigma(\mathcal{L}) = \mathcal{F}$, but $P \ne Q$.
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
Consider the Borel $\sigma$-algebra $\mathcal B(\mathbb R)$, and the class $\mathcal C:=\left\{(a,+\infty),a\in\mathbb R\right\}$. Then the class $\mathcal C$ generates $\mathcal B(\mathbb R)$. Consider the counting measure $\mu$ over $\mathcal B(\mathbb R)$, that is $\mu(B)=\begin{cases} \operatorname{card} A&\mbox{ if }A \mbox{ is finite, }\\\ +\infty&\mbox{ otherwise,} \end{cases}$ and the Lebesgue measure. These measures have the same value over the elements of $\mathcal C$, but since for example $\{0\}\in\mathcal B(\mathbb R)$, and $\mu(\{0\})=1\neq \lambda(\{0\})=0$, these measure can't be the same. However, we can show the following result: > > Let $\mu\_1$ and $\mu\_2$ be two *$\sigma$-finite* measures on a measurable space $(X,\mathcal S)$ and let $\mathcal A$ be an algebra which generates $\mathcal S$. Assume that for each $A\in\mathcal A$, $\mu\_1(A)=\mu\_2(A)$. > > > Then $\mu\_1(B)=\mu\_2(B)$ for each $B\in\mathcal S$. > > >
There is a famous example: A compact separable metric space, two different finite Borel measures on the space, but the two measures agree with each other on all of the balls for the metric. R. O. Davies, "Measures not approximable or not specifiable by means of balls." Mathematika 18 (1971) 157--160
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
Consider flipping two coins. Let $A$ be the event that the first coin is heads, and $B$ the event that the second coin is heads. $A$ and $B$ together generate the $\sigma$-algebra of all possible events. Suppose we know that $P(A) = P(B) = 1/2$ (i.e. each coin is unbiased). This is not enough information to determine whether the two coins are independent, so $P$ is not completely determined. This is the same counterexample that I gave in [this answer to another question](https://math.stackexchange.com/a/8184/822). In its notation, $P$ and $Q$ agree on the events in $\mathcal{L}$, and $\sigma(\mathcal{L}) = \mathcal{F}$, but $P \ne Q$.
Caratheodory’s measure extension theorem.: Theorem 1.41 (Caratheodory). Let $A ⊂ 2^Ω$ be a ring and let $µ$ be a $σ$-finite premeasure on $A$. There exists a unique measure $µ'$ on $σ(A)$ such that $µ'(E) = µ(E)$ for all $E ∈ A$. Furthermore, $µ'$ is $σ$-finite. p. 19 of <http://www.math.unipd.it/~daipra/didattica/galileiana-15/Parte-I.pdf> (The same is given on p. 14 of here: <http://www.mathematik.uni-kl.de/~wwwstoch-alt/skripte/basicmeasuretheory_skript.pdf> and here: <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem> ) premeasure is a $σ$-additive set function $\mu$ to $[0,\infty]$ with $\mu(\emptyset)=0$. Ring contains $\emptyset$ and is closed w.r.t. unions of two elements and complements.
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
Consider the Borel $\sigma$-algebra $\mathcal B(\mathbb R)$, and the class $\mathcal C:=\left\{(a,+\infty),a\in\mathbb R\right\}$. Then the class $\mathcal C$ generates $\mathcal B(\mathbb R)$. Consider the counting measure $\mu$ over $\mathcal B(\mathbb R)$, that is $\mu(B)=\begin{cases} \operatorname{card} A&\mbox{ if }A \mbox{ is finite, }\\\ +\infty&\mbox{ otherwise,} \end{cases}$ and the Lebesgue measure. These measures have the same value over the elements of $\mathcal C$, but since for example $\{0\}\in\mathcal B(\mathbb R)$, and $\mu(\{0\})=1\neq \lambda(\{0\})=0$, these measure can't be the same. However, we can show the following result: > > Let $\mu\_1$ and $\mu\_2$ be two *$\sigma$-finite* measures on a measurable space $(X,\mathcal S)$ and let $\mathcal A$ be an algebra which generates $\mathcal S$. Assume that for each $A\in\mathcal A$, $\mu\_1(A)=\mu\_2(A)$. > > > Then $\mu\_1(B)=\mu\_2(B)$ for each $B\in\mathcal S$. > > >
Let consider the above mentioned assertion due to Davide Giraudo. **Fact 1.** Let $μ$ a $\sigma$-finite measure on a measurable space $(X,S)$ , $\cal{A}$ an algebra which generates $S$ and $μ\_1 ,μ\_2$ two measures on $S$ such that for each $A\in\cal{A}$ , $μ\_1 (A)=μ\_2 (A)=μ(A)$. Then $μ\_1 (B)=μ\_2 (B)$ for each $B\in S$ . **Remark 1.** Fact 1 , in general, is not true if $X$ is not covered by a countable family of elements of $\cal{A}$ which have finite $\mu$-measures. **Example 1.** Let $N$ denotes a set of all natural munbers. Let $ {\bf R}^N $ be the topological vector space of all real-valued sequences equipped with the Tykhonoff topology. Let us denote by $ B({\bf R}^N) $ the $\sigma$-algebra of all Borel subsets in $ {\bf R}^N $. Let $ (a\_i)\_{i \in N} $ and $ (b\_i)\_{i \in N} $ be sequences of real numbers such that $$ ( \forall i )( i \in N \rightarrow a\_i < b\_i ). $$ We put $$ A\_n={\bf R}\_0 \times \cdots \times {\bf R}\_n \times (\prod \limits\_{i > n}\Delta\_i)~, $$ for $n \in N$, where $$ (\forall i)( i \in N \rightarrow {\bf R}\_i={\bf R}~ \& ~ \Delta\_i=[a\_i;b\_i[). $$ We put also $$ \Delta=\prod\_{i \in N}\Delta\_i. $$ For an arbitrary natural number $i \in N$, consider the Lebesgue measure $ \mu\_i $ defined on the space ${\bf R}\_i$ and satisfying the condition $\mu\_i(\Delta\_i)=1$. Let us denote by $\lambda\_i$ the normed Lebesgue measure defined on the interval $\Delta\_i$. For an arbitrary $n \in N$, let us denote by $\nu\_n$ the measure defined by $$ \nu\_n= \prod \limits\_{1 \le i \le n} \mu\_i \times \prod\limits\_{i > n} \lambda\_i, $$ and by ${\overline{\nu}}\_n$ the Borel measure in the space ${\bf R}^N$ defined by $$ ( \forall X)(X \in B({\bf R}^N) \rightarrow {\overline{\nu}}\_n(X)= \nu\_n(X \cap A\_n)). $$ Following [G.Pantsulaia , Invariant and quasiinvariant measures in infinite-dimensional topological vector spaces. Nova Science Publishers, Inc., New York, 2007. xii+234 pp.](see Lemma 5.1, p. 93), for an arbitrary Borel set $X \subseteq {\bf R}^N $ there exists a limit $$ {\nu}\_{\Delta}(X)= \lim \limits\_{n \rightarrow \infty} \overline{\nu}\_n(X). $$ Moreover, the functional ${\nu}\_{\Delta}$ is a nontrivial $\sigma$-finite measure defined on the Borel $\sigma$-algebra $B({\bf R}^N)$. Let $\Delta^{(1)}=[0,1[^{N}$ and $\Delta^{(2)}=[2,3[^{N}$. Let consider $\cal{A}$-a class of subsets of ${\bf R}^N$ defined by $$ {\cal{A}}=\{X \times R^{N \setminus \{1,\cdots,n\}}:X \in \cal{B}({\bf R}^n)~\&~n \in N\}. $$ Obviously, $\cal{A}$ is an algebra of subsets of ${\bf R}^N$ which generates the Borel $\sigma$-algebra $B({\bf R}^N)$. On the one hand, the measures $\mu\_1:={\nu}\_{\Delta^{(1)}}$ and $\mu\_2:={\nu}\_{\Delta^{(2)}}$ are agree on $\cal{A}$. In particular, $\mu\_1(X \times R^{N \setminus \{1,\cdots,n\}})=\mu\_2(X \times R^{N \setminus \{1,\cdots,n\}})=+\infty$ if $n$-dimensional Lebesgue measure of $X$ is positive and $=0$ if $n$-dimensional Lebesgue measure of $X$ is zero. On the other hand, we have that $\mu\_1(\Delta^{(2)})=0$ and $\mu\_2(\Delta^{(2)})=1$. **Example 2(Simple example)** Let $X=[0,1[$ and $(x\_k)\_{k \in N}$ and $(y\_k)\_{k \in N}$ be two different everywere dense in $[0,1[$ sequences. Let $\cal{A}$ be a class of all subsets of $[0,1[$ every element of which is presented as a union of a finite family of left closed and right open subintervals of $[0,1[$. Obviously, $\cal{A}$ is the algebra of subset of $[0,1[$ which generates the Borel $\sigma$-algebra $\cal{B}([0,1[)$. Let define two measures $\mu\_1$ and $\mu\_2$ as follows: $\mu\_1(X)=\# (\{x\_k:k \in N\} \cap X)$ and $\mu\_2(X)=\# (\{y\_k:k \in N\} \cap X)$ for $X \in \cal{B}([0,1[)$, where $\#$ denotes the counting measure. Then $\mu\_1$ and $\mu\_2$ are agree on $\cal{A}$ but they are dfferent because $(x\_k)\_{k \in N}$ and $(y\_k)\_{k \in N}$ are different. The following assertion is valid. **Fact 2.** Let $μ$ a $\sigma$-finite measure on a measurable space $(X,S)$ , $\cal{A}$ an algebra which generates $S$ such that $X$ is covered by a countable family of elements of $\cal{A}$ which have finite $\mu$-measures. If $μ\_1 ,μ\_2$ are two measures on $S$ such that for each $A\in\cal{A}$ , $μ\_1 (A)=μ\_2 (A)=μ(A)$ then $\mu\_1(B)=\mu\_2(B)$ for all $B \in S$.
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
There is a famous example: A compact separable metric space, two different finite Borel measures on the space, but the two measures agree with each other on all of the balls for the metric. R. O. Davies, "Measures not approximable or not specifiable by means of balls." Mathematika 18 (1971) 157--160
Caratheodory’s measure extension theorem.: Theorem 1.41 (Caratheodory). Let $A ⊂ 2^Ω$ be a ring and let $µ$ be a $σ$-finite premeasure on $A$. There exists a unique measure $µ'$ on $σ(A)$ such that $µ'(E) = µ(E)$ for all $E ∈ A$. Furthermore, $µ'$ is $σ$-finite. p. 19 of <http://www.math.unipd.it/~daipra/didattica/galileiana-15/Parte-I.pdf> (The same is given on p. 14 of here: <http://www.mathematik.uni-kl.de/~wwwstoch-alt/skripte/basicmeasuretheory_skript.pdf> and here: <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem> ) premeasure is a $σ$-additive set function $\mu$ to $[0,\infty]$ with $\mu(\emptyset)=0$. Ring contains $\emptyset$ and is closed w.r.t. unions of two elements and complements.
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
Consider the Borel $\sigma$-algebra $\mathcal B(\mathbb R)$, and the class $\mathcal C:=\left\{(a,+\infty),a\in\mathbb R\right\}$. Then the class $\mathcal C$ generates $\mathcal B(\mathbb R)$. Consider the counting measure $\mu$ over $\mathcal B(\mathbb R)$, that is $\mu(B)=\begin{cases} \operatorname{card} A&\mbox{ if }A \mbox{ is finite, }\\\ +\infty&\mbox{ otherwise,} \end{cases}$ and the Lebesgue measure. These measures have the same value over the elements of $\mathcal C$, but since for example $\{0\}\in\mathcal B(\mathbb R)$, and $\mu(\{0\})=1\neq \lambda(\{0\})=0$, these measure can't be the same. However, we can show the following result: > > Let $\mu\_1$ and $\mu\_2$ be two *$\sigma$-finite* measures on a measurable space $(X,\mathcal S)$ and let $\mathcal A$ be an algebra which generates $\mathcal S$. Assume that for each $A\in\mathcal A$, $\mu\_1(A)=\mu\_2(A)$. > > > Then $\mu\_1(B)=\mu\_2(B)$ for each $B\in\mathcal S$. > > >
Caratheodory’s measure extension theorem.: Theorem 1.41 (Caratheodory). Let $A ⊂ 2^Ω$ be a ring and let $µ$ be a $σ$-finite premeasure on $A$. There exists a unique measure $µ'$ on $σ(A)$ such that $µ'(E) = µ(E)$ for all $E ∈ A$. Furthermore, $µ'$ is $σ$-finite. p. 19 of <http://www.math.unipd.it/~daipra/didattica/galileiana-15/Parte-I.pdf> (The same is given on p. 14 of here: <http://www.mathematik.uni-kl.de/~wwwstoch-alt/skripte/basicmeasuretheory_skript.pdf> and here: <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem> ) premeasure is a $σ$-additive set function $\mu$ to $[0,\infty]$ with $\mu(\emptyset)=0$. Ring contains $\emptyset$ and is closed w.r.t. unions of two elements and complements.
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
There is a famous example: A compact separable metric space, two different finite Borel measures on the space, but the two measures agree with each other on all of the balls for the metric. R. O. Davies, "Measures not approximable or not specifiable by means of balls." Mathematika 18 (1971) 157--160
Let consider the above mentioned assertion due to Davide Giraudo. **Fact 1.** Let $μ$ a $\sigma$-finite measure on a measurable space $(X,S)$ , $\cal{A}$ an algebra which generates $S$ and $μ\_1 ,μ\_2$ two measures on $S$ such that for each $A\in\cal{A}$ , $μ\_1 (A)=μ\_2 (A)=μ(A)$. Then $μ\_1 (B)=μ\_2 (B)$ for each $B\in S$ . **Remark 1.** Fact 1 , in general, is not true if $X$ is not covered by a countable family of elements of $\cal{A}$ which have finite $\mu$-measures. **Example 1.** Let $N$ denotes a set of all natural munbers. Let $ {\bf R}^N $ be the topological vector space of all real-valued sequences equipped with the Tykhonoff topology. Let us denote by $ B({\bf R}^N) $ the $\sigma$-algebra of all Borel subsets in $ {\bf R}^N $. Let $ (a\_i)\_{i \in N} $ and $ (b\_i)\_{i \in N} $ be sequences of real numbers such that $$ ( \forall i )( i \in N \rightarrow a\_i < b\_i ). $$ We put $$ A\_n={\bf R}\_0 \times \cdots \times {\bf R}\_n \times (\prod \limits\_{i > n}\Delta\_i)~, $$ for $n \in N$, where $$ (\forall i)( i \in N \rightarrow {\bf R}\_i={\bf R}~ \& ~ \Delta\_i=[a\_i;b\_i[). $$ We put also $$ \Delta=\prod\_{i \in N}\Delta\_i. $$ For an arbitrary natural number $i \in N$, consider the Lebesgue measure $ \mu\_i $ defined on the space ${\bf R}\_i$ and satisfying the condition $\mu\_i(\Delta\_i)=1$. Let us denote by $\lambda\_i$ the normed Lebesgue measure defined on the interval $\Delta\_i$. For an arbitrary $n \in N$, let us denote by $\nu\_n$ the measure defined by $$ \nu\_n= \prod \limits\_{1 \le i \le n} \mu\_i \times \prod\limits\_{i > n} \lambda\_i, $$ and by ${\overline{\nu}}\_n$ the Borel measure in the space ${\bf R}^N$ defined by $$ ( \forall X)(X \in B({\bf R}^N) \rightarrow {\overline{\nu}}\_n(X)= \nu\_n(X \cap A\_n)). $$ Following [G.Pantsulaia , Invariant and quasiinvariant measures in infinite-dimensional topological vector spaces. Nova Science Publishers, Inc., New York, 2007. xii+234 pp.](see Lemma 5.1, p. 93), for an arbitrary Borel set $X \subseteq {\bf R}^N $ there exists a limit $$ {\nu}\_{\Delta}(X)= \lim \limits\_{n \rightarrow \infty} \overline{\nu}\_n(X). $$ Moreover, the functional ${\nu}\_{\Delta}$ is a nontrivial $\sigma$-finite measure defined on the Borel $\sigma$-algebra $B({\bf R}^N)$. Let $\Delta^{(1)}=[0,1[^{N}$ and $\Delta^{(2)}=[2,3[^{N}$. Let consider $\cal{A}$-a class of subsets of ${\bf R}^N$ defined by $$ {\cal{A}}=\{X \times R^{N \setminus \{1,\cdots,n\}}:X \in \cal{B}({\bf R}^n)~\&~n \in N\}. $$ Obviously, $\cal{A}$ is an algebra of subsets of ${\bf R}^N$ which generates the Borel $\sigma$-algebra $B({\bf R}^N)$. On the one hand, the measures $\mu\_1:={\nu}\_{\Delta^{(1)}}$ and $\mu\_2:={\nu}\_{\Delta^{(2)}}$ are agree on $\cal{A}$. In particular, $\mu\_1(X \times R^{N \setminus \{1,\cdots,n\}})=\mu\_2(X \times R^{N \setminus \{1,\cdots,n\}})=+\infty$ if $n$-dimensional Lebesgue measure of $X$ is positive and $=0$ if $n$-dimensional Lebesgue measure of $X$ is zero. On the other hand, we have that $\mu\_1(\Delta^{(2)})=0$ and $\mu\_2(\Delta^{(2)})=1$. **Example 2(Simple example)** Let $X=[0,1[$ and $(x\_k)\_{k \in N}$ and $(y\_k)\_{k \in N}$ be two different everywere dense in $[0,1[$ sequences. Let $\cal{A}$ be a class of all subsets of $[0,1[$ every element of which is presented as a union of a finite family of left closed and right open subintervals of $[0,1[$. Obviously, $\cal{A}$ is the algebra of subset of $[0,1[$ which generates the Borel $\sigma$-algebra $\cal{B}([0,1[)$. Let define two measures $\mu\_1$ and $\mu\_2$ as follows: $\mu\_1(X)=\# (\{x\_k:k \in N\} \cap X)$ and $\mu\_2(X)=\# (\{y\_k:k \in N\} \cap X)$ for $X \in \cal{B}([0,1[)$, where $\#$ denotes the counting measure. Then $\mu\_1$ and $\mu\_2$ are agree on $\cal{A}$ but they are dfferent because $(x\_k)\_{k \in N}$ and $(y\_k)\_{k \in N}$ are different. The following assertion is valid. **Fact 2.** Let $μ$ a $\sigma$-finite measure on a measurable space $(X,S)$ , $\cal{A}$ an algebra which generates $S$ such that $X$ is covered by a countable family of elements of $\cal{A}$ which have finite $\mu$-measures. If $μ\_1 ,μ\_2$ are two measures on $S$ such that for each $A\in\cal{A}$ , $μ\_1 (A)=μ\_2 (A)=μ(A)$ then $\mu\_1(B)=\mu\_2(B)$ for all $B \in S$.
90,491
If the value of a measure on any subset in a generator of a sigma algebra is known, will the measure for the sigma algebra also be uniquely determined? Thanks!
2011/12/11
[ "https://math.stackexchange.com/questions/90491", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1281/" ]
Let consider the above mentioned assertion due to Davide Giraudo. **Fact 1.** Let $μ$ a $\sigma$-finite measure on a measurable space $(X,S)$ , $\cal{A}$ an algebra which generates $S$ and $μ\_1 ,μ\_2$ two measures on $S$ such that for each $A\in\cal{A}$ , $μ\_1 (A)=μ\_2 (A)=μ(A)$. Then $μ\_1 (B)=μ\_2 (B)$ for each $B\in S$ . **Remark 1.** Fact 1 , in general, is not true if $X$ is not covered by a countable family of elements of $\cal{A}$ which have finite $\mu$-measures. **Example 1.** Let $N$ denotes a set of all natural munbers. Let $ {\bf R}^N $ be the topological vector space of all real-valued sequences equipped with the Tykhonoff topology. Let us denote by $ B({\bf R}^N) $ the $\sigma$-algebra of all Borel subsets in $ {\bf R}^N $. Let $ (a\_i)\_{i \in N} $ and $ (b\_i)\_{i \in N} $ be sequences of real numbers such that $$ ( \forall i )( i \in N \rightarrow a\_i < b\_i ). $$ We put $$ A\_n={\bf R}\_0 \times \cdots \times {\bf R}\_n \times (\prod \limits\_{i > n}\Delta\_i)~, $$ for $n \in N$, where $$ (\forall i)( i \in N \rightarrow {\bf R}\_i={\bf R}~ \& ~ \Delta\_i=[a\_i;b\_i[). $$ We put also $$ \Delta=\prod\_{i \in N}\Delta\_i. $$ For an arbitrary natural number $i \in N$, consider the Lebesgue measure $ \mu\_i $ defined on the space ${\bf R}\_i$ and satisfying the condition $\mu\_i(\Delta\_i)=1$. Let us denote by $\lambda\_i$ the normed Lebesgue measure defined on the interval $\Delta\_i$. For an arbitrary $n \in N$, let us denote by $\nu\_n$ the measure defined by $$ \nu\_n= \prod \limits\_{1 \le i \le n} \mu\_i \times \prod\limits\_{i > n} \lambda\_i, $$ and by ${\overline{\nu}}\_n$ the Borel measure in the space ${\bf R}^N$ defined by $$ ( \forall X)(X \in B({\bf R}^N) \rightarrow {\overline{\nu}}\_n(X)= \nu\_n(X \cap A\_n)). $$ Following [G.Pantsulaia , Invariant and quasiinvariant measures in infinite-dimensional topological vector spaces. Nova Science Publishers, Inc., New York, 2007. xii+234 pp.](see Lemma 5.1, p. 93), for an arbitrary Borel set $X \subseteq {\bf R}^N $ there exists a limit $$ {\nu}\_{\Delta}(X)= \lim \limits\_{n \rightarrow \infty} \overline{\nu}\_n(X). $$ Moreover, the functional ${\nu}\_{\Delta}$ is a nontrivial $\sigma$-finite measure defined on the Borel $\sigma$-algebra $B({\bf R}^N)$. Let $\Delta^{(1)}=[0,1[^{N}$ and $\Delta^{(2)}=[2,3[^{N}$. Let consider $\cal{A}$-a class of subsets of ${\bf R}^N$ defined by $$ {\cal{A}}=\{X \times R^{N \setminus \{1,\cdots,n\}}:X \in \cal{B}({\bf R}^n)~\&~n \in N\}. $$ Obviously, $\cal{A}$ is an algebra of subsets of ${\bf R}^N$ which generates the Borel $\sigma$-algebra $B({\bf R}^N)$. On the one hand, the measures $\mu\_1:={\nu}\_{\Delta^{(1)}}$ and $\mu\_2:={\nu}\_{\Delta^{(2)}}$ are agree on $\cal{A}$. In particular, $\mu\_1(X \times R^{N \setminus \{1,\cdots,n\}})=\mu\_2(X \times R^{N \setminus \{1,\cdots,n\}})=+\infty$ if $n$-dimensional Lebesgue measure of $X$ is positive and $=0$ if $n$-dimensional Lebesgue measure of $X$ is zero. On the other hand, we have that $\mu\_1(\Delta^{(2)})=0$ and $\mu\_2(\Delta^{(2)})=1$. **Example 2(Simple example)** Let $X=[0,1[$ and $(x\_k)\_{k \in N}$ and $(y\_k)\_{k \in N}$ be two different everywere dense in $[0,1[$ sequences. Let $\cal{A}$ be a class of all subsets of $[0,1[$ every element of which is presented as a union of a finite family of left closed and right open subintervals of $[0,1[$. Obviously, $\cal{A}$ is the algebra of subset of $[0,1[$ which generates the Borel $\sigma$-algebra $\cal{B}([0,1[)$. Let define two measures $\mu\_1$ and $\mu\_2$ as follows: $\mu\_1(X)=\# (\{x\_k:k \in N\} \cap X)$ and $\mu\_2(X)=\# (\{y\_k:k \in N\} \cap X)$ for $X \in \cal{B}([0,1[)$, where $\#$ denotes the counting measure. Then $\mu\_1$ and $\mu\_2$ are agree on $\cal{A}$ but they are dfferent because $(x\_k)\_{k \in N}$ and $(y\_k)\_{k \in N}$ are different. The following assertion is valid. **Fact 2.** Let $μ$ a $\sigma$-finite measure on a measurable space $(X,S)$ , $\cal{A}$ an algebra which generates $S$ such that $X$ is covered by a countable family of elements of $\cal{A}$ which have finite $\mu$-measures. If $μ\_1 ,μ\_2$ are two measures on $S$ such that for each $A\in\cal{A}$ , $μ\_1 (A)=μ\_2 (A)=μ(A)$ then $\mu\_1(B)=\mu\_2(B)$ for all $B \in S$.
Caratheodory’s measure extension theorem.: Theorem 1.41 (Caratheodory). Let $A ⊂ 2^Ω$ be a ring and let $µ$ be a $σ$-finite premeasure on $A$. There exists a unique measure $µ'$ on $σ(A)$ such that $µ'(E) = µ(E)$ for all $E ∈ A$. Furthermore, $µ'$ is $σ$-finite. p. 19 of <http://www.math.unipd.it/~daipra/didattica/galileiana-15/Parte-I.pdf> (The same is given on p. 14 of here: <http://www.mathematik.uni-kl.de/~wwwstoch-alt/skripte/basicmeasuretheory_skript.pdf> and here: <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem> ) premeasure is a $σ$-additive set function $\mu$ to $[0,\infty]$ with $\mu(\emptyset)=0$. Ring contains $\emptyset$ and is closed w.r.t. unions of two elements and complements.
25,082,517
The following code works without error or exception - but still, it does not do what it should ! I wanted to save an image into the iOS library/Application Support folder. More precisely, the image should be placed into a /library/Application Support/bundleID\_name/subfolder/ (and the subfolder being called "location1"). If I check the functionality with the iOS-Simulator, I can see the creation of the subfolder (i.e. .../library/Application Support/bundleID\_name/location1/). Also the function "saveImage" works without exception. But there is no image being saved !!!! (i.e.the image-file is missing and the folder remains empty) !! What could be the mistake ?? Here is my code with the call of two functions (see code below): ``` UIImage *in_image = [UIImage imageNamed:@"template009c.jpg"]; NSString *locDirectoryName = @"location1"; NSURL *LocationDirectory = [self appendLocationToApplicationDirectory:locDirectoryName]; [self saveImage:in_image :@"image1" :LocationDirectory]; ``` With the corresponding function-Nr1: ``` - (NSURL*)appendLocationToApplicationDirectory:(NSString*)locationDirName { NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier]; NSFileManager*fm = [NSFileManager defaultManager]; NSURL* dirPath = nil; // Find the application support directory in the home directory. NSArray* appSupportDir = [fm URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask]; if ([appSupportDir count] > 0) { // Append the bundle ID and the location-Foldername to the URL for the Application Support directory dirPath = [[[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:appBundleID] URLByAppendingPathComponent:locationDirName]; // If the directory does not exist, this method creates it. // This method call works in OS X 10.7 and later only. NSError* theError = nil; if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError]) { // Handle the error. NSLog(@"%@", theError.localizedDescription); return nil; } else { // Mark the directory as excluded from iCloud backups if (![dirPath setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&theError]) { NSLog(@"Error excluding %@ from iCloud backup %@", [dirPath lastPathComponent], theError.localizedDescription); } else { NSLog(@"Location Directory excluded from iClud backups"); } } } return dirPath; } ``` And function Nr2: ``` //saving an image - (void)saveImage:(UIImage*)image :(NSString*)imageName :(NSURL*)pathName { NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format. NSFileManager *fileManager = [NSFileManager defaultManager]; // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *LocationDirectory = [pathName absoluteString]; NSString *fullPath = [LocationDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]]; /***** THE FOLLOWING LINE DOES NOT SEEM TO DO WHAT IT IS SUPPOSED TO *******/ [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; /**** I also tried without the FileManager, but same problem - no file written... ***/ // [imageData writeToFile:fullPath atomically:NO]; NSLog(@"image saved"); } ``` By the way, getting the "fullPath" with the XCode-Debugger, I get: ``` "fullPath NSPathStore2 * @"file:/Users/username/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/2BCC3345-9M55F-4580-A1E7-6694E33456777/Library/Application%20Support/bundleID_name/image1.png" 0x09d50950 ``` Doesn't that also seem correct ?? But why is [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; not performing ???
2014/08/01
[ "https://Stackoverflow.com/questions/25082517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3826232/" ]
It took a while but I actually got it working by doing this in onTouch: ``` final int X = (int) event.getRawX(); final int Y = (int) event.getRawY(); ImageView j = (ImageView) findViewById(R.id.image); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: _xDelta = (int) (X - j.getTranslationX()); _yDelta = (int) (Y - j.getTranslationY()); break; case MotionEvent.ACTION_UP: _xDelta = 100; _yDelta = 100; break; case MotionEvent.ACTION_MOVE: j.setTranslationX(X - _xDelta); j.setTranslationY(Y - _yDelta); if (X >= 370 && X <= 500 && Y >= 250 && Y <= 420) { Log.i(null, "Region 1 initiated"); // Do whatever... } ```
There is no MotionEvent.ACTION\_MOVE defined in DragEvent class OnDragListener interface defined the method ``` abstract boolean onDrag(View v, DragEvent event) ``` Action are: * ACTION\_DRAG\_STARTED * ACTION\_DRAG\_ENTERED * ACTION\_DRAG\_LOCATION * ACTION\_DRAG\_EXITED * ACTION\_DROP * ACTION\_DRAG\_ENDED Please refer to this [page](http://developer.android.com/guide/topics/ui/drag-drop.html) for more details
15,008,258
i got jailbreak iphone ios 6 in my tweak on ios 4&5 I used (void) kill to close other app running in the background. this is my code: ```objc #import "SBApplication.h" SBApplication *app ; app = [[objc_getClass("SBApplicationController") sharedInstance] applicationWithDisplayIdentifier:@"my killed program id "]; if(app) [app kill]; ``` now when i trying that in ios 6 i cant get this to work ! need help?
2013/02/21
[ "https://Stackoverflow.com/questions/15008258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/998346/" ]
After few investigations I didn't find any code in jersey where the option list is populated. (probably something that is *not supported yet*) So you can implement your own WadlGenerator and inserting it the generator chain. Here is a sample `OptionsWadlGenerator` adding the `<option>` elements for parameter of type `Enum` ``` package com.mycompany; import com.sun.jersey.api.model.AbstractMethod; import com.sun.jersey.api.model.AbstractResource; import com.sun.jersey.api.model.AbstractResourceMethod; import com.sun.jersey.api.model.Parameter; import com.sun.jersey.server.wadl.WadlGenerator; import com.sun.research.ws.wadl.Application; import com.sun.research.ws.wadl.Method; import com.sun.research.ws.wadl.ObjectFactory; import com.sun.research.ws.wadl.Option; import com.sun.research.ws.wadl.Param; import com.sun.research.ws.wadl.RepresentationType; import com.sun.research.ws.wadl.Request; import com.sun.research.ws.wadl.Resource; import com.sun.research.ws.wadl.Resources; import com.sun.research.ws.wadl.Response; import javax.ws.rs.core.MediaType; public class OptionsWadlGenerator implements WadlGenerator { private WadlGenerator _delegate; private ObjectFactory objectFactory = new ObjectFactory(); @Override public Param createParam(AbstractResource r, AbstractMethod m, Parameter p) { Param param = _delegate.createParam(r, m, p); if(((Parameter)p).getParameterClass().isEnum()){ Object[] values = p.getParameterClass().getEnumConstants(); for(Object enumItem:values){ Option option = objectFactory.createOption(); option.setValue(((Enum)enumItem).name()); param.getOption().add(option); } } return param; } @Override public void setWadlGeneratorDelegate(WadlGenerator delegate) { this._delegate = delegate; } @Override public Application createApplication() { return _delegate.createApplication(); } ... all other methods also simply call the _delegate equivalent method } ``` And of course, to insert it in your chain, do something like that: ``` public class OurWADLGenerator extends WadlGeneratorConfig { @Override public List<WadlGeneratorDescription> configure() { return generator(WadlGeneratorApplicationDoc.class) .prop("applicationDocsStream", "application-doc.xml") .generator(WadlGeneratorResourceDocSupport.class) .prop("resourceDocStream", "resourcedoc.xml") .generator(OptionsWadlGenerator.class).descriptions(); } } ```
A quick search for the usages of `com.sun.research.ws.wadl.Param.getOption()` (see results [here](http://grepcode.com/search/usages?type=method&id=repo1.maven.org%[email protected]%[email protected]@com%24sun%24research%24ws%24wadl@Param@getOption%28%29&k=u)) shows that it's actually never invoked from the library. I guess it's only there because these classes are generated by xjc from the wadl.xsd. It seems though that Jersey basically ignores this piece of information in wadl files, and similarly doesn't care to include it in wadl files it generates. A couple of years ago we ended up writing our own code to generate wadl, because the available tooling was so poor. This might have changed since then, but the above issue shows that proper support for wadl is still not quite there. :(
31,363,867
I am trying to optimize layout of a set of boxes w.r.t. their hanger locations s.t. the boxes are most aligned with their hangers and do not crowd out each other. Using quadprog. Givens: ``` 1. box hanger x-locations (P). =710 850 990 1130 2. box-sizes (W). =690 550 690 130 3. usable x-spread tuple (S). =-150 2090 4. number of boxes (K). =4 5. minimum interbox spread (G). =50 6. box x-locations (X). =objective ``` We can see that the total required x-spread is sum(W) + 3G = 2060 + 150 = 2210 whereas the available x-spread is S[2] - S[1](http://cran.r-project.org/web/packages/quadprog/quadprog.pdf) = 2240. So, a solution should exist. Min: ``` sumof (P[i] – X[i])^2 s.t.: ``` (1) X[i+i] – X[i] >= G + ½ ( W[i+1] + W[i] ); i = 1..(K-1), i.e. the boxes do not crowd out each other ``` -X[i] + X[i+1] >= -( -G – ½ (W[i+1] + W[i]) ) ``` (2) X[1](http://cran.r-project.org/web/packages/quadprog/quadprog.pdf) >= S[left] + ½ W[1](http://cran.r-project.org/web/packages/quadprog/quadprog.pdf), and (3) X[K] <= S[right] – ½ W[K], i.e. the boxes are within the given x-spread ``` X[1] >= - ( S[left] + ½ W[1] ) -X[K] >= - ( S[right] – ½ W[K] ) ``` for a total of 5 constraints - 3 for the inter-box spread, and 2 for extremities. in R: ``` > Dmat = matrix(0,4,4) > diag(Dmat) = 1 > dvec = P, the hanger locations [1] 710 850 990 1130 > bvec [1] -670 -670 -460 -195 2025 > t(Amat) [,1] [,2] [,3] [,4] [1,] -1 1 0 0 [2,] 0 -1 1 0 [3,] 0 0 -1 1 [4,] 1 0 0 0 [5,] 0 0 0 -1 > solve.QP(Dmat, dvec, Amat, bvec) Error in solve.QP(Dmat, dvec, Amat, bvec) : constraints are inconsistent, no solution! ``` Quite obviously I have missed or mis-specified the problem ([Package 'quadprog'](http://cran.r-project.org/web/packages/quadprog/quadprog.pdf))! I am using quadprog as I found a JavaScript port of it. Thanks a lot.
2015/07/12
[ "https://Stackoverflow.com/questions/31363867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1397919/" ]
Strings are compared using [lexicographical order](https://en.wikipedia.org/wiki/Lexicographical_order), which at its simplest is what you would think of as “dictionary ordering”: the string `apple` is less than the string `banana` because the character `a` precedes the character `b` according to my English locale; but `apple` follows `abacus` because `p` follows `b`—you simply compare each character in turn. `strcmp` doesn’t make any particular guarantees about its nonzero return values beyond the sign. Typically they’re simply `-1`, `0`, and `+1`, but you can’t rely on this. The standard could just as well have specified `strcmp` to return a more specific enumeration: ``` enum Ordering { LT, EQ, GT }; ``` But many C standard library functions accept and return “magical” `int` values as a matter of historical accident.
Think of the simplest possible C implementation of the function: ``` int strcmp(char *p1, char *p2) { int diff; do diff = *p1 - *p2; while (*p1++ && *p2++ && diff); return diff; } ``` The returned value happens to have the proper sign, but the value itself is just an artifact of the comparison process. That's why the value is left unspecified, to give implementors the widest possible latitude for an efficient implementation.
43,523
What is the structure of $\ce{[Co(NH3)5SO4]+}$? If sulfate is a bidentate ligand, then the coordination number of cobalt would become 7. How is this possible?
2016/01/10
[ "https://chemistry.stackexchange.com/questions/43523", "https://chemistry.stackexchange.com", "https://chemistry.stackexchange.com/users/24227/" ]
There's a certain amount of misinformation here: > > sulfate is a bidentate ligand > > > Sulfate is actually a flexidentate ligand, which is a term used to describe a polydentate ligand which is found to show different denticity in different complexes. Sulfate can act both as mono- or a bidentate ligand. Remember, *just* because it has two donor atoms doesn't make it a bidentate ligand. The occurrence of complexes where sulfate acts as a bidentate ring would also be rare owing to the fact that four-membered rings are strained. [This page](https://www.cs.mcgill.ca/~rwest/link-suggestion/wpcd_2008-09_augmented/wp/s/Sulfate.htm) lists $\ce{[Pt(SO4)(P(C6H5)3)2]}$ as one example of such an occurrence. > > coordination number of cobalt would become 7. How is this possible? > > > If this implies that coordination numbers of 7 aren't possible, it isn't true. Coordination numbers of 3, 5, 7, 8-12, 14 are possible, albeit such compounds are quite rare. See this [Wikipedia page for some examples](https://en.wikipedia.org/wiki/Coordination_geometry#Table_of_coordination_geometries). --- Thus, the structure of the complex $\ce{[Co(NH3)5SO4]+}$ should be octahedral with cobalt showing a coordination number of 6.
Interestingly enough, it seems that crystal structure of $\ce{[Co(NH3)5(SO4)]+}$ has not yet been obtained. Probably it has something to do with [*trans*-effect](https://en.wikipedia.org/wiki/Trans_effect) of $\ce{SO4^2-}$, which makes $\ce{NH3}$ ligand extremely labile. Also, C.N. 7 is also very common for cobalt and is often found in complexes like $\ce{[Co^{III}(Cp)L2]}$. Anyway, to further illustrate [Berry Holmes' great answer](https://chemistry.stackexchange.com/a/74619/41328) and show that sulfur oxoanions can not only be flexidentate, but also ambidentate (when denticity is 1), there are some examples how coordination abilities of various sulfur oxoanions deviate from each other in case of pentamminocobalt(III) complexes (only cationic parts are shown): 1. ***p*-(Ammine-(sulfato-*O*)-tris(2-aminoethyl)amine-cobalt(III)) perchlorate** $\ce{[Co(C6H21N5)(SO4)](ClO4)}$, CCDC #CULRIK [1]. $\angle(\ce{Co-O-S}) = 131.2^\circ$, $d(\ce{Co-O}) = \pu{1.958(3) Å}$. $\color{#EEEEEE}{\Large\bullet}~\ce{H}$; $\color{#909090}{\Large\bullet}~\ce{C}$; $\color{#3050F8}{\Large\bullet}~\ce{N}$; $\color{#FF0D0D}{\Large\bullet}~\ce{O}$; $\color{#FFFF30}{\Large\bullet}~\ce{S}$; $\color{#F090A0}{\Large\bullet}~\ce{Co}$. [![enter image description here](https://i.stack.imgur.com/fi9VV.png)](https://i.stack.imgur.com/fi9VV.png) 2. **Pentaammine(sulfito-*S*)(IV)cobalt(III) chloride hydrate** $\ce{[Co(NH3)5SO3](H2O)Cl}$, ICSD #37092 [2]. $\angle(\ce{Co-S-O}) = 110.0^\circ$, $d(\ce{Co-S}) = \pu{2.2138(8) Å}$. $\color{#EEEEEE}{\Large\bullet}~\ce{H}$; $\color{#3050F8}{\Large\bullet}~\ce{N}$; $\color{#FF0D0D}{\Large\bullet}~\ce{O}$; $\color{#FFFF30}{\Large\bullet}~\ce{S}$; $\color{#F090A0}{\Large\bullet}~\ce{Co}$. [![enter image description here](https://i.stack.imgur.com/oMNAs.png)](https://i.stack.imgur.com/oMNAs.png) 3. **Pentaammine(thiosulfato-*S*)cobalt(III) chloride hydrate** $\ce{[Co(NH3)5S2O3](H2O)Cl}$, ICSD #16144 [3]. $\angle(\ce{Co-S-S}) = 110.5^\circ$, $d(\ce{Co-S}) = \pu{2.286(6) Å}$. $\color{#EEEEEE}{\Large\bullet}~\ce{H}$; $\color{#3050F8}{\Large\bullet}~\ce{N}$; $\color{#FF0D0D}{\Large\bullet}~\ce{O}$; $\color{#FFFF30}{\Large\bullet}~\ce{S}$; $\color{#F090A0}{\Large\bullet}~\ce{Co}$. [![enter image description here](https://i.stack.imgur.com/sBVsG.png)](https://i.stack.imgur.com/sBVsG.png) ### References 1. Chun, H.; Jackson, W. G.; McKeon, J. A.; Somoza, F. B.; Bernal, I. *Eur. J. Inorg. Chem.* **2000**, 2000 (1), 189–193 DOI: [10.1002/(SICI)1099-0682(200001)2000:1<189::AID-EJIC189>3.0.CO;2-V](http://onlinelibrary.wiley.com/doi/10.1002/(SICI)1099-0682(200001)2000:1%3C189::AID-EJIC189%3E3.0.CO;2-V/abstract). 2. Elder, R. C.; Heeg, M. J.; Payne, M. D.; Trkula, M.; Deutsch, E. *Inorg. Chem.* **1978**, 17 (2), 431–440 DOI: [10.1021/ic50180a048](http://pubs.acs.org/doi/abs/10.1021/ic50180a048). 3. Baggio, S. *J. Chem. Soc. A* **1970**, 0 (0), 2384–2387 DOI: [10.1039/J19700002384](http://pubs.rsc.org/en/Content/ArticleLanding/1970/J1/j19700002384).
4,862,181
I'm using jquery validations and i want to clone rules from an element to another one. Is it possible? ``` var rule = $('[id=' + elementToCopy + ']').rules(); $(this).rules("add", rule); ```
2011/02/01
[ "https://Stackoverflow.com/questions/4862181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511021/" ]
What you're attempting appears to work, at least for simple rules like `required`. Make sure and use the [Id selector](http://api.jquery.com/id-selector/) (`$("#" + elementToCopy)`) when you want to retrieve an element by id. Also, be aware of the restriction on the [`rules("add", rules)`](http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules) method: > > Requires that the parent form is > validated, that is, > $("form").validate() is called first. > > > Basically, make sure both `form1` and `form2` containing `element1` and `element2` have had `validate()` called on them before you start adding/retrieving rules. I've created a simple example here: <http://jsfiddle.net/andrewwhitaker/4ShxX/> **Edit:** It also looks like this works for custom rules: ``` $.validator.addMethod("onlycharacters", function(value, element) { return this.optional(element) || /^[A-Za-z]+$/.test(value); }, "Only characters"); $("#form1").validate({ rules: { name: { onlycharacters: true } } }); $("#form2").validate(); var rules = $("#name").rules(); $("#name2").rules("add", rules); ``` <http://jsfiddle.net/andrewwhitaker/4ShxX/1/>
Yes you can do it. But will more elegant if you do this task using jQuery clone function. That make a deep copy of the set of matched elements. <http://api.jquery.com/clone/> Passing first parameter you can copy the element with ALL events and attributes.
4,862,181
I'm using jquery validations and i want to clone rules from an element to another one. Is it possible? ``` var rule = $('[id=' + elementToCopy + ']').rules(); $(this).rules("add", rule); ```
2011/02/01
[ "https://Stackoverflow.com/questions/4862181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511021/" ]
The script below copies the rules and the messages, the code you have only does it for the rules. Note the query for the messages uses element name, not element id. ``` var rules = $('#elementtocopy').rules(); rules['messages'] = $('form').data('validator').settings["your element name, NOT id"]; $('#newelementid').rules("add", args); ```
Yes you can do it. But will more elegant if you do this task using jQuery clone function. That make a deep copy of the set of matched elements. <http://api.jquery.com/clone/> Passing first parameter you can copy the element with ALL events and attributes.
2,741,300
When I try to run my ASP.NET app from my development environment I get the following error message: *Compiler Error Message: CS1502: The best overloaded method match for 'mmars.Printing.printFunctions.SetPrintSummaryProperties(mmars.contextInfo, ref mmars.Printing.printObjSummary)' has some invalid arguments*. When I publish and run on our production server I don't get this error. It seems to compile fine when I build from the build menu (in fact if I change the second argument of the bolded function call below, i get a compiler error in visual studio), but now i've suddenly started getting this error message at runtime. So another question I have in addition to getting rid of the error is why is the .NET development server even trying to do JIT compilation on my project if it is already compiled into a DLL? `Printing.printObjSummary myPrintObj = new Printing.printObjSummary();` **`Printing.printFunctions.SetPrintSummaryProperties(ci, ref myPrintObj);`** `printObjects.Add(myPrintObj);` This seems to have just suddenly appeared from nowhere today and it's extremely frustrating. Also, though there are no warnings at compile-time, when I get redirected to the page with that first compilation error there are many warnings like the following: Warning: CS0436: The type 'mmars.MMARSSummaryDataItem' in 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\3dad423c\40569048\App\_Code.b0rgpkzr.4.cs' conflicts with the imported type 'mmars.MMARSSummaryDataItem' in 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\3dad423c\40569048\assembly\dl3\7179c19a\345f948c\_ece7ca01\mmars.DLL'. Using the type defined in 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\3dad423c\40569048\App\_Code.b0rgpkzr.4.cs'. What's the deal with that? Is the webserver complaining about name conflicts in the source file and dll resulting from the source file?
2010/04/29
[ "https://Stackoverflow.com/questions/2741300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307960/" ]
Turns out the solution to this problem was simply renaming my App\_Code folder to something else. Apparently the development web-server tries to do JIT compilation on stuff in a folder called App\_Code, even if all the members of those files already exist in the compiled assembly, which is what was causing this problem.
Have you tried clearing the Temporary ASP.NET Files? It's possible a cached version of an assembly is out of sync or something... Another possibility (remote), is that the old version of the dll is in your Assembly Cache?
7,117,778
I'm trying to do a scrollTO function with my code but I keeps just popping up to the top like its not connecting to the id im telling it to go to is there something im doing wrong?. ``` <div class="a-z"> <? $a1=range("A","Z"); foreach($a1 as $char2){ echo "<a href='#$char2' onclick='$.scrollTo( '#$char2', 800, {easing:'elasout'} ); title='$char2'>$char2</a>"; }?> <script type="text/javascript"> $(document).ready('#<?php echo $char2 ?>').localScroll({ target:'<?php echo $char2 ?>' }); </script> </div> ``` code updated i dont get any errors
2011/08/19
[ "https://Stackoverflow.com/questions/7117778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874185/" ]
Both MX and Spark `TextAreas` supports `editable` and `selectable` properties. The first one prevent user to change text, the second - to select it: ``` <mx:TextArea editable="false" selectable="false" text="Sample Text"/> <s:TextArea editable="false" selectable="false" text="Sample Text"/> ```
If you're talking about [MX `TextArea`](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/controls/TextArea.html) you can disable component: ``` myTextArea.enabled = false; ``` If you're using [Spark `TextArea`](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/TextArea.html) you can use [`editable` property](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/supportClasses/SkinnableTextBase.html#editable).
7,117,778
I'm trying to do a scrollTO function with my code but I keeps just popping up to the top like its not connecting to the id im telling it to go to is there something im doing wrong?. ``` <div class="a-z"> <? $a1=range("A","Z"); foreach($a1 as $char2){ echo "<a href='#$char2' onclick='$.scrollTo( '#$char2', 800, {easing:'elasout'} ); title='$char2'>$char2</a>"; }?> <script type="text/javascript"> $(document).ready('#<?php echo $char2 ?>').localScroll({ target:'<?php echo $char2 ?>' }); </script> </div> ``` code updated i dont get any errors
2011/08/19
[ "https://Stackoverflow.com/questions/7117778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874185/" ]
I am not sure if I understand your problem, but it sounds like it could be the Safari 5.1 / Flash Debug player bug. Try switching to another browser when debugging/testing your project. If you get the same behaviour, forget everything I just said. Read more here: <https://discussions.apple.com/message/15666579#15666579> "I also don't think this was intentional at all.  I think it was just a bit careless (Apple pushing out Safari 5.1 before it being thoroughly tested - the flash problem is only one of several issues I've noted with the new browser.  Very dissapointing.)."
If you're talking about [MX `TextArea`](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/controls/TextArea.html) you can disable component: ``` myTextArea.enabled = false; ``` If you're using [Spark `TextArea`](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/TextArea.html) you can use [`editable` property](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/supportClasses/SkinnableTextBase.html#editable).
7,117,778
I'm trying to do a scrollTO function with my code but I keeps just popping up to the top like its not connecting to the id im telling it to go to is there something im doing wrong?. ``` <div class="a-z"> <? $a1=range("A","Z"); foreach($a1 as $char2){ echo "<a href='#$char2' onclick='$.scrollTo( '#$char2', 800, {easing:'elasout'} ); title='$char2'>$char2</a>"; }?> <script type="text/javascript"> $(document).ready('#<?php echo $char2 ?>').localScroll({ target:'<?php echo $char2 ?>' }); </script> </div> ``` code updated i dont get any errors
2011/08/19
[ "https://Stackoverflow.com/questions/7117778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/874185/" ]
Both MX and Spark `TextAreas` supports `editable` and `selectable` properties. The first one prevent user to change text, the second - to select it: ``` <mx:TextArea editable="false" selectable="false" text="Sample Text"/> <s:TextArea editable="false" selectable="false" text="Sample Text"/> ```
I am not sure if I understand your problem, but it sounds like it could be the Safari 5.1 / Flash Debug player bug. Try switching to another browser when debugging/testing your project. If you get the same behaviour, forget everything I just said. Read more here: <https://discussions.apple.com/message/15666579#15666579> "I also don't think this was intentional at all.  I think it was just a bit careless (Apple pushing out Safari 5.1 before it being thoroughly tested - the flash problem is only one of several issues I've noted with the new browser.  Very dissapointing.)."
28,373,328
The title is my question - how would I go about flipping all the bits in an std::ifstream that's been loaded from a file? ``` ifstream file( "filename.png" ); if ( !file.is_open( ) ) { return false; } ``` I don't know how I should be going from here. By flipping, I'm referring to inverting the bits (0 if 1, 1 if 0)
2015/02/06
[ "https://Stackoverflow.com/questions/28373328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709725/" ]
This is an X-Y problem. I really doubt you want to flip all the bits in a PNG format file, simply because there are other fields in the file besides the bitmap bits. Also, unless the image is pure black & white, there is more to the color bits than inverting the bits. That said, here's how to flip the bits. ``` While not the end of the file, do: read a block of bytes (uint8_t) for each byte read do: read the byte invert the byte (a.k.a. using `~` operator) store the byte end-for write block to new file. end-while ``` **Side effects of inverting pixels** Most images are made up of pixels, or picture elements. These elements are usually represented by a number of bits per pixel and if multiple colors, bits per color. Let us take for example an RGB image with 24 bits per pixel. This means that there are 8 bits to represent the red, 8 bits for green and 8 bits for blue. Each color has a value range of 0 to 255. This represents the amount of color. Let us take 1 color, green, with a value of 0x55 or in binary 0101 0101. Inverting (flipping) the bits will yield a value of 0xAA or 1010 1010. So after flipping the green value is now 0xAA. If this is what you want to happen, changing the amount of color on each pixel, then you will need to extract the color quantities from the PNG file for the image and invert them.
Here's one way to do it: ``` #include <fstream> int main(int argc, char **argv) { std::ifstream ifile(argv[1]); /// input std::ofstream ofile(argv[2]); /// output if (ifile.is_open() && ofile.is_open()) { char ch; std::string data = ""; while (ifile.get(ch)) { for (unsigned int i = 0; i < 8; ++i) ch ^= (1 << i); data += ch; } ofile << data; } ifile.close(); ofile.close(); return 0; } ``` usage: ``` ./prog input output ``` input: ``` $ xxd -b input 0000000: 00110001 00110000 00110000 00110001 00001010 ``` output: ``` $ xxd -b output 0000000: 11001110 11001111 11001111 11001110 11110101 ```
15,952,669
I am using the FOSUserBundle to manage my website users. My goal is to make the login form get displayed in a modal window based on the boostrap framework. Down is my code for the modal window ``` <div class="modal hide" data-backdrop="static" id="login"> <div class="modal-header"> <a class="close" data-dismiss="modal">×</a> <h3>Connexion</h3> </div> <div class="modal-body" > </div> </div> <a class="btn btn-primary" data-toggle="modal" data-target="#login" href="{{ path('fos_user_security_login') }}">Sign in</a> ``` This code works perfectly well if the user does not make any mistake while entring his username and his password. In case of errors, symfony2 redirect me directly to `/login` page which is the minimalist twig page provided by the bundle FOSUserBundle. In order to get rid of the problem, my idea consisted in listening to javascript event that will display the window again. This is done through the window.hashchange event. The proposed code for that is: ``` <script type="text/javascript" src="{{ asset('jquery/1.9.1/jquery.ba-hashchange.min.js')}}"></script> <script> $(function() { // Bind the event. $(window).hashchange(function() { // Alerts every time the hash changes! alert(location.hash); if(location.hash === "#login"){ $('#login').modal(); } }); // Trigger the event (useful on page load). $(window).hashchange(); }); </script> ``` This was great: throught this code, I become able to display to login modal window if I get to this url `/#login`. But, the problem is still not solved yet, because there is a routing problem in symfony. I am afaid to have to rewrite all the bundle to make redirection in the controllers of FOSUserBundle. Any idea?
2013/04/11
[ "https://Stackoverflow.com/questions/15952669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2269738/" ]
You can check if there are errors after logging in using: ``` {% if error %} {# do something #} {% endif %} ``` This means that you can check whether you want to modal hidden or if you want to show it on the page-load like so: ``` <div class="modal{% if not error %} hide{% endif %}"> <!-- model window --> </div> ```
I think this is the best way to manage redirections after login succes/faillure using FOSUserBundle : Stackoverflow question : [redirect after login fos user bundle symfony](https://stackoverflow.com/questions/16020508/redirect-after-login-fos-user-bundle-symfony) Basicly, add a [LoginSuccessHandler](http://www.reecefowell.com/2011/10/26/redirecting-on-loginlogout-in-symfony2-using-loginhandlers/) which implements the AuthenticationSuccessHandler Interface to do different action on success or faillure of loginAction
15,952,669
I am using the FOSUserBundle to manage my website users. My goal is to make the login form get displayed in a modal window based on the boostrap framework. Down is my code for the modal window ``` <div class="modal hide" data-backdrop="static" id="login"> <div class="modal-header"> <a class="close" data-dismiss="modal">×</a> <h3>Connexion</h3> </div> <div class="modal-body" > </div> </div> <a class="btn btn-primary" data-toggle="modal" data-target="#login" href="{{ path('fos_user_security_login') }}">Sign in</a> ``` This code works perfectly well if the user does not make any mistake while entring his username and his password. In case of errors, symfony2 redirect me directly to `/login` page which is the minimalist twig page provided by the bundle FOSUserBundle. In order to get rid of the problem, my idea consisted in listening to javascript event that will display the window again. This is done through the window.hashchange event. The proposed code for that is: ``` <script type="text/javascript" src="{{ asset('jquery/1.9.1/jquery.ba-hashchange.min.js')}}"></script> <script> $(function() { // Bind the event. $(window).hashchange(function() { // Alerts every time the hash changes! alert(location.hash); if(location.hash === "#login"){ $('#login').modal(); } }); // Trigger the event (useful on page load). $(window).hashchange(); }); </script> ``` This was great: throught this code, I become able to display to login modal window if I get to this url `/#login`. But, the problem is still not solved yet, because there is a routing problem in symfony. I am afaid to have to rewrite all the bundle to make redirection in the controllers of FOSUserBundle. Any idea?
2013/04/11
[ "https://Stackoverflow.com/questions/15952669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2269738/" ]
I solved that overriding the login.twig.html and putting this near the beginning ``` {% if error %} <script> $('.modal').modal("show"); </script> <div>{{ error|trans }}</div> {% endif %} ``` but im still missing how to make this modal appear when the user clicks on a secured action and get redirected to link he clicked and not the page that contains the link (that whats gets in the $request->headers->get('referer') in spite being first redirected from wherever the secured action was)
I think this is the best way to manage redirections after login succes/faillure using FOSUserBundle : Stackoverflow question : [redirect after login fos user bundle symfony](https://stackoverflow.com/questions/16020508/redirect-after-login-fos-user-bundle-symfony) Basicly, add a [LoginSuccessHandler](http://www.reecefowell.com/2011/10/26/redirecting-on-loginlogout-in-symfony2-using-loginhandlers/) which implements the AuthenticationSuccessHandler Interface to do different action on success or faillure of loginAction
427,102
> > **Possible Duplicate:** > > [Turn off display in Windows 7 without additional software](https://superuser.com/questions/321342/turn-off-display-in-windows-7-without-additional-software) > > > I have windows 7 installed with two monitors connected to it. I want to create a shortcut that will put both of my monitors to sleep. not to put the entire computer to sleep, just the monitors. is that possible ?! thanks kfir
2012/05/21
[ "https://superuser.com/questions/427102", "https://superuser.com", "https://superuser.com/users/14946/" ]
Engaging the screen saver doesn't turn off the monitor. Also, using the `Windows` + `L` doesn't either, it only locks it. So, you could try a utility at NirSoft called [NirCmd](http://www.nirsoft.net/utils/nircmd.html) which will do what you need, as well as many other things. You will just need to set up a short cut to the command needed and you are set. If you need step by step instructions, go [here](http://www.howtogeek.com/howto/windows-vista/create-a-shortcut-or-hotkey-to-turn-off-the-monitor/) for that.
For standbying the 2 monitors i am now using the progam "LCDoff" , I was using "monitoroff", both are very tiny utilities. <http://www.kev009.com/wp/projects/lcdoff/> I made a shortcut to it, and it works. One time a video playback program was running that disables monitor standby, other than that, it is working. Moving the mouse, or using the keyboard wakes it back up, so I assume it is triggering windows own standby routine.
54,636
On a 10.7.4 Lion Server installation the Server Admin.app fails to start correctly. The window is drawn and the last known server and its services are displayed, but a spinning wheel keeps spinning on the bottom status bar. Console.app log shows: ``` Jun 24 18:19:56 mac01 servermgrd[437]: [437] error in getAndLockContext: flock(servermgr_info) FATAL time out Jun 24 18:19:56 mac01 servermgrd[437]: [437] process will force-quit to avoid deadlock Jun 24 18:19:56 mac01 servermgrd[437]: outstanding requests are: ( { Command = getHistory; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = getState; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = Idle; Module = "servermgr_info"; Timestamp = "2012-06-24 16:18:50 +0000"; } ) Jun 24 18:19:56 mac01 com.apple.launchd[1] (com.apple.servermgrd[437]): Exited with code: 1 ``` There are **3 services enabled: dns, firewall, mail**. DNS plugin gave an error message which cannot be reproduced. Other errors in Console.app are: ``` Jun 28 12:49:58 mac01 ServerBackup[32087]: Error in calling backup command for service postgresql, error :=69 Jun 28 12:51:24 mac01 mds[99]: (Error) Volume: Could not find requested backup type:2 for volume Jun 28 12:53:01 mac01 mds[99]: (Error) Server: ==== XPC handleXPCMessage XPC_ERROR_CONNECTION_INVALID ``` (Regression) Other sources suggested to try: 1. review DNS settings, no problem found there 2. check the hostname with `sudo changeip -checkhostname`, no problem found there 3. destroy the Open Directory installation, OD is not used here 4. reboot, that did not solve the problem 5. replace `/Library/Preferences/com.apple.servermgrd.plist` with a known good copy, that did not help 6. replace the Server Admin.app itself with a known good copy, also did not improve 7. issuing a `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, as in my answer below, which only partly solves the issue. Server Admin started correctly once, but on second and consecutive launches the spinning wheel keeps spinning again and log shows the deadlock situations again. 8. untick 'require valid digital signature (SSL)' in server admin prefs just incase you haven't trusted your server cert, no change. 9. check if it is a user issue, by creating a new admin user and try starting server admin from that login, errors out (kReceivedUnknownError says Server Admin, process will force-quit to avoid deadlock is in the log, but no outstanding requests are in the log) 10. Changed the connecting server address from 'name.local' to '127.0.0.1', no change. 11. `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo rm -r /var/servermgrd;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, no change 12. Server.app > hardware > hostname > settings > uncheck dedicate resources to server services, reboot, check again, reboot, no change 13. `$ diskutil repairPermissions /;sudo reboot`, no change 14. corrected the rDNS entry to match the machine name, so that Server.app no longer displays an alert that the network has changed on every boot. Other repeating log file entries are: ``` 29-06-12 02:58:01,943 configd: network configuration changed. 29-06-12 02:58:33,575 configd: network configuration changed. 29-06-12 02:58:33,597 configd: network configuration changed. 29-06-12 02:58:34,266 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv4 rules 29-06-12 02:58:34,578 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv6 rules 29-06-12 02:59:50,707 servermgrd: servermgr_filebrowser:Error:servermgr_filebrowser: Error getting quotas for volume /Volumes/H of type exfat ``` After hours of trying to isolate the problem, I can reproduce that the flock(servermgr\_info) FATAL time out is related to the local DNS service. When DNS service is started the Server Admin.app generates the flock(servermgr\_info) FATAL time out, when DNS is then stopped (and `$ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist` to be sure that there is a clean starting point) next time Server Admin.app behaves OK and no flock(servermgr\_info) FATAL time out is logged. Anonymised serveradmin DNS configuration extracted using `$ sudo serveradmin settings dns`) is here: ``` dns:acls:_array_index:0:name = "com.apple.ServerAdmin.DNS.public" dns:acls:_array_index:0:addressMatchList:_array_index:0 = "localhost" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:name = "xyz.nl" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:0 = "1.1.1.237" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:1 = "2.2.1.247" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:2 = "1.2.1.59" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:3 = "2.1.1.23" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:primaryZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:allowRecursion = "com.apple.ServerAdmin.DNS.public" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:reverseZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:name = "com.apple.ServerAdmin.DNS.public" dns:isBonjourClientBrowsingEnabled = no ``` Irony is that localhost is not configured as DNS resolver: ``` $ networksetup -getdnsservers Ethernet 91.196.170.5 8.8.8.8 8.8.4.4 ``` When DNS service is stopped, Server Admin sometimes still keeps spinning. Having a look at Servername > Network > shows that in the pane with "Network Interfaces" the DNS name is empty. `nslookup -type=ptr z.y.x.91.in-addr.arpa` returns the correct value. A `dig PTR z.y.x.91.in-addr.arpa` for the PTR is ok, and a `dig PTR z.y.x.91.in-addr.arpa +trace` stops after recursion number 4: ``` . 77760 IN NS m.root-servers.net. ...<cut>... . 77760 IN NS l.root-servers.net. ;; Received 244 bytes from 91.196.170.5#53(91.196.170.5) in 5 ms in-addr.arpa. 172800 IN NS a.in-addr-servers.arpa. ...<cut>... in-addr.arpa. 172800 IN NS f.in-addr-servers.arpa. ;; Received 432 bytes from 192.203.230.10#53(e.root-servers.net) in 7 ms 91.in-addr.arpa. 86400 IN NS sec3.apnic.net. ...<cut>... 91.in-addr.arpa. 86400 IN NS sns-pb.isc.org. ;; Received 200 bytes from 193.0.9.1#53(f.in-addr-servers.arpa) in 2 ms 170.196.91.in-addr.arpa. 172800 IN NS ns2.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns3.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns1.technotop.nl. ;; Received 110 bytes from 193.0.9.5#53(pri.authdns.ripe.net) in 1 ms ;; connection timed out; no servers could be reached ``` Now there is also a new message logged: ``` Jun 29 14:49:10 mac01 servermgrd[1039]: Still servicing 0:0 requests after 300 seconds, with 1 sessions outstanding, resetting idleTimer ``` --- **Update #1** It looks like the issue might be a rDNS (reverse DNS) PTR configuration error. A `dig +trace` from a 10.5 machine at a different location results in `couldn't get address for 'ns3.technotop.nl': not found`. The network provider has been asked to fix this flaky (and faulty) DNS configuration. --- **Update #2** Another suspect is the built-in firewall. When the firewall is stopped there are no hangs. When the firewall is started, the spinning wheel never stops. --- **Update #3** The provider fixed ns3.technotop.nl by assigning a DNS A record with IP address 91.196.170.72 at August 23th. Result: still a spinning wheel at the bottom right part of Mac OS Server Admin, and after a few minutes > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Server). (kReceivedUnkownError). > > > Followed by a: > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Certificates). (kReceivedUnkownError). > > > **Update #4** The next issue is a CentOS version 5.4 software firewall at the servers where both ns1.technotop.nl and ns2.technotop.nl are running on, that kicked in on Mac OS X 10.7.4 Lion + Server + Admin Tools DNS traffic patterns: > > 123.45.67.89 # lfd: (PERMBLOCK) 123.45.67.89 has had more than 4 temp blocks in the last 86400 secs - Sun Jun 17 21:20:08 2012 > > > After clearing this block in the CentOS firewall, the firewall block is back within 10 hours for each IP address that is running 10.7.4 and is having a reverse DNS name that is authoritatively served by the CentOS 5.4 machines. Let's see what a whitelist on the CentOS firewall will do for machines running Mac OS 10.7.4. --- **Question** How to fix this DNS service related servermgrd flock(servermgr\_info) error (for instance by factory default resetting dns service)?
2012/06/24
[ "https://apple.stackexchange.com/questions/54636", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/21252/" ]
Review the firewall configuration of the authoritative DNS servers for the PTR records of your (public) IP address. In our case, when looking up the PTR records of the public IP address (123.45.67.89 for example) by using the reverse notation (89.67.45.123.in-addr.arpa) in Terminal on the Lion Server: 1. `$ dig NS 67.45.123.in-addr.arpa +short` results in: ns1.technotop.nl. ns2.technotop.nl. 2. `$ dig PTR 89.67.45.123.in-addr.arpa @ns1.technotop.nl` results in: ; <<>> DiG 9.7.3-P3 <<>> PTR 89.67.45.123.in-addr.arpa @ns1.technotop.nl ;; global options: +cmd ;; connection timed out; no servers could be reached In other words the DNS packets were discarded by an intermediary firewall. After whitelisting the IP adress of the Mac OS X Server in the firewall of each authorative DNS server, the "getAndLockContext: flock(servermgr\_info) FATAL time out" issue was gone.
`$ sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist` and the issue was gone for a few minutes.
54,636
On a 10.7.4 Lion Server installation the Server Admin.app fails to start correctly. The window is drawn and the last known server and its services are displayed, but a spinning wheel keeps spinning on the bottom status bar. Console.app log shows: ``` Jun 24 18:19:56 mac01 servermgrd[437]: [437] error in getAndLockContext: flock(servermgr_info) FATAL time out Jun 24 18:19:56 mac01 servermgrd[437]: [437] process will force-quit to avoid deadlock Jun 24 18:19:56 mac01 servermgrd[437]: outstanding requests are: ( { Command = getHistory; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = getState; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = Idle; Module = "servermgr_info"; Timestamp = "2012-06-24 16:18:50 +0000"; } ) Jun 24 18:19:56 mac01 com.apple.launchd[1] (com.apple.servermgrd[437]): Exited with code: 1 ``` There are **3 services enabled: dns, firewall, mail**. DNS plugin gave an error message which cannot be reproduced. Other errors in Console.app are: ``` Jun 28 12:49:58 mac01 ServerBackup[32087]: Error in calling backup command for service postgresql, error :=69 Jun 28 12:51:24 mac01 mds[99]: (Error) Volume: Could not find requested backup type:2 for volume Jun 28 12:53:01 mac01 mds[99]: (Error) Server: ==== XPC handleXPCMessage XPC_ERROR_CONNECTION_INVALID ``` (Regression) Other sources suggested to try: 1. review DNS settings, no problem found there 2. check the hostname with `sudo changeip -checkhostname`, no problem found there 3. destroy the Open Directory installation, OD is not used here 4. reboot, that did not solve the problem 5. replace `/Library/Preferences/com.apple.servermgrd.plist` with a known good copy, that did not help 6. replace the Server Admin.app itself with a known good copy, also did not improve 7. issuing a `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, as in my answer below, which only partly solves the issue. Server Admin started correctly once, but on second and consecutive launches the spinning wheel keeps spinning again and log shows the deadlock situations again. 8. untick 'require valid digital signature (SSL)' in server admin prefs just incase you haven't trusted your server cert, no change. 9. check if it is a user issue, by creating a new admin user and try starting server admin from that login, errors out (kReceivedUnknownError says Server Admin, process will force-quit to avoid deadlock is in the log, but no outstanding requests are in the log) 10. Changed the connecting server address from 'name.local' to '127.0.0.1', no change. 11. `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo rm -r /var/servermgrd;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, no change 12. Server.app > hardware > hostname > settings > uncheck dedicate resources to server services, reboot, check again, reboot, no change 13. `$ diskutil repairPermissions /;sudo reboot`, no change 14. corrected the rDNS entry to match the machine name, so that Server.app no longer displays an alert that the network has changed on every boot. Other repeating log file entries are: ``` 29-06-12 02:58:01,943 configd: network configuration changed. 29-06-12 02:58:33,575 configd: network configuration changed. 29-06-12 02:58:33,597 configd: network configuration changed. 29-06-12 02:58:34,266 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv4 rules 29-06-12 02:58:34,578 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv6 rules 29-06-12 02:59:50,707 servermgrd: servermgr_filebrowser:Error:servermgr_filebrowser: Error getting quotas for volume /Volumes/H of type exfat ``` After hours of trying to isolate the problem, I can reproduce that the flock(servermgr\_info) FATAL time out is related to the local DNS service. When DNS service is started the Server Admin.app generates the flock(servermgr\_info) FATAL time out, when DNS is then stopped (and `$ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist` to be sure that there is a clean starting point) next time Server Admin.app behaves OK and no flock(servermgr\_info) FATAL time out is logged. Anonymised serveradmin DNS configuration extracted using `$ sudo serveradmin settings dns`) is here: ``` dns:acls:_array_index:0:name = "com.apple.ServerAdmin.DNS.public" dns:acls:_array_index:0:addressMatchList:_array_index:0 = "localhost" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:name = "xyz.nl" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:0 = "1.1.1.237" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:1 = "2.2.1.247" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:2 = "1.2.1.59" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:3 = "2.1.1.23" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:primaryZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:allowRecursion = "com.apple.ServerAdmin.DNS.public" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:reverseZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:name = "com.apple.ServerAdmin.DNS.public" dns:isBonjourClientBrowsingEnabled = no ``` Irony is that localhost is not configured as DNS resolver: ``` $ networksetup -getdnsservers Ethernet 91.196.170.5 8.8.8.8 8.8.4.4 ``` When DNS service is stopped, Server Admin sometimes still keeps spinning. Having a look at Servername > Network > shows that in the pane with "Network Interfaces" the DNS name is empty. `nslookup -type=ptr z.y.x.91.in-addr.arpa` returns the correct value. A `dig PTR z.y.x.91.in-addr.arpa` for the PTR is ok, and a `dig PTR z.y.x.91.in-addr.arpa +trace` stops after recursion number 4: ``` . 77760 IN NS m.root-servers.net. ...<cut>... . 77760 IN NS l.root-servers.net. ;; Received 244 bytes from 91.196.170.5#53(91.196.170.5) in 5 ms in-addr.arpa. 172800 IN NS a.in-addr-servers.arpa. ...<cut>... in-addr.arpa. 172800 IN NS f.in-addr-servers.arpa. ;; Received 432 bytes from 192.203.230.10#53(e.root-servers.net) in 7 ms 91.in-addr.arpa. 86400 IN NS sec3.apnic.net. ...<cut>... 91.in-addr.arpa. 86400 IN NS sns-pb.isc.org. ;; Received 200 bytes from 193.0.9.1#53(f.in-addr-servers.arpa) in 2 ms 170.196.91.in-addr.arpa. 172800 IN NS ns2.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns3.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns1.technotop.nl. ;; Received 110 bytes from 193.0.9.5#53(pri.authdns.ripe.net) in 1 ms ;; connection timed out; no servers could be reached ``` Now there is also a new message logged: ``` Jun 29 14:49:10 mac01 servermgrd[1039]: Still servicing 0:0 requests after 300 seconds, with 1 sessions outstanding, resetting idleTimer ``` --- **Update #1** It looks like the issue might be a rDNS (reverse DNS) PTR configuration error. A `dig +trace` from a 10.5 machine at a different location results in `couldn't get address for 'ns3.technotop.nl': not found`. The network provider has been asked to fix this flaky (and faulty) DNS configuration. --- **Update #2** Another suspect is the built-in firewall. When the firewall is stopped there are no hangs. When the firewall is started, the spinning wheel never stops. --- **Update #3** The provider fixed ns3.technotop.nl by assigning a DNS A record with IP address 91.196.170.72 at August 23th. Result: still a spinning wheel at the bottom right part of Mac OS Server Admin, and after a few minutes > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Server). (kReceivedUnkownError). > > > Followed by a: > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Certificates). (kReceivedUnkownError). > > > **Update #4** The next issue is a CentOS version 5.4 software firewall at the servers where both ns1.technotop.nl and ns2.technotop.nl are running on, that kicked in on Mac OS X 10.7.4 Lion + Server + Admin Tools DNS traffic patterns: > > 123.45.67.89 # lfd: (PERMBLOCK) 123.45.67.89 has had more than 4 temp blocks in the last 86400 secs - Sun Jun 17 21:20:08 2012 > > > After clearing this block in the CentOS firewall, the firewall block is back within 10 hours for each IP address that is running 10.7.4 and is having a reverse DNS name that is authoritatively served by the CentOS 5.4 machines. Let's see what a whitelist on the CentOS firewall will do for machines running Mac OS 10.7.4. --- **Question** How to fix this DNS service related servermgrd flock(servermgr\_info) error (for instance by factory default resetting dns service)?
2012/06/24
[ "https://apple.stackexchange.com/questions/54636", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/21252/" ]
I had the same issue. As suggested here, I tracked the problem down to a bad NS record (typo) for the reverse zone. changeip -checkhostname reported no issues manually checking the forward/reverse all looked good. But when I specifically checked the NS record for the reverse zone, noticed the typo.
`$ sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist` and the issue was gone for a few minutes.
54,636
On a 10.7.4 Lion Server installation the Server Admin.app fails to start correctly. The window is drawn and the last known server and its services are displayed, but a spinning wheel keeps spinning on the bottom status bar. Console.app log shows: ``` Jun 24 18:19:56 mac01 servermgrd[437]: [437] error in getAndLockContext: flock(servermgr_info) FATAL time out Jun 24 18:19:56 mac01 servermgrd[437]: [437] process will force-quit to avoid deadlock Jun 24 18:19:56 mac01 servermgrd[437]: outstanding requests are: ( { Command = getHistory; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = getState; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = Idle; Module = "servermgr_info"; Timestamp = "2012-06-24 16:18:50 +0000"; } ) Jun 24 18:19:56 mac01 com.apple.launchd[1] (com.apple.servermgrd[437]): Exited with code: 1 ``` There are **3 services enabled: dns, firewall, mail**. DNS plugin gave an error message which cannot be reproduced. Other errors in Console.app are: ``` Jun 28 12:49:58 mac01 ServerBackup[32087]: Error in calling backup command for service postgresql, error :=69 Jun 28 12:51:24 mac01 mds[99]: (Error) Volume: Could not find requested backup type:2 for volume Jun 28 12:53:01 mac01 mds[99]: (Error) Server: ==== XPC handleXPCMessage XPC_ERROR_CONNECTION_INVALID ``` (Regression) Other sources suggested to try: 1. review DNS settings, no problem found there 2. check the hostname with `sudo changeip -checkhostname`, no problem found there 3. destroy the Open Directory installation, OD is not used here 4. reboot, that did not solve the problem 5. replace `/Library/Preferences/com.apple.servermgrd.plist` with a known good copy, that did not help 6. replace the Server Admin.app itself with a known good copy, also did not improve 7. issuing a `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, as in my answer below, which only partly solves the issue. Server Admin started correctly once, but on second and consecutive launches the spinning wheel keeps spinning again and log shows the deadlock situations again. 8. untick 'require valid digital signature (SSL)' in server admin prefs just incase you haven't trusted your server cert, no change. 9. check if it is a user issue, by creating a new admin user and try starting server admin from that login, errors out (kReceivedUnknownError says Server Admin, process will force-quit to avoid deadlock is in the log, but no outstanding requests are in the log) 10. Changed the connecting server address from 'name.local' to '127.0.0.1', no change. 11. `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo rm -r /var/servermgrd;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, no change 12. Server.app > hardware > hostname > settings > uncheck dedicate resources to server services, reboot, check again, reboot, no change 13. `$ diskutil repairPermissions /;sudo reboot`, no change 14. corrected the rDNS entry to match the machine name, so that Server.app no longer displays an alert that the network has changed on every boot. Other repeating log file entries are: ``` 29-06-12 02:58:01,943 configd: network configuration changed. 29-06-12 02:58:33,575 configd: network configuration changed. 29-06-12 02:58:33,597 configd: network configuration changed. 29-06-12 02:58:34,266 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv4 rules 29-06-12 02:58:34,578 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv6 rules 29-06-12 02:59:50,707 servermgrd: servermgr_filebrowser:Error:servermgr_filebrowser: Error getting quotas for volume /Volumes/H of type exfat ``` After hours of trying to isolate the problem, I can reproduce that the flock(servermgr\_info) FATAL time out is related to the local DNS service. When DNS service is started the Server Admin.app generates the flock(servermgr\_info) FATAL time out, when DNS is then stopped (and `$ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist` to be sure that there is a clean starting point) next time Server Admin.app behaves OK and no flock(servermgr\_info) FATAL time out is logged. Anonymised serveradmin DNS configuration extracted using `$ sudo serveradmin settings dns`) is here: ``` dns:acls:_array_index:0:name = "com.apple.ServerAdmin.DNS.public" dns:acls:_array_index:0:addressMatchList:_array_index:0 = "localhost" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:name = "xyz.nl" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:0 = "1.1.1.237" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:1 = "2.2.1.247" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:2 = "1.2.1.59" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:3 = "2.1.1.23" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:primaryZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:allowRecursion = "com.apple.ServerAdmin.DNS.public" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:reverseZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:name = "com.apple.ServerAdmin.DNS.public" dns:isBonjourClientBrowsingEnabled = no ``` Irony is that localhost is not configured as DNS resolver: ``` $ networksetup -getdnsservers Ethernet 91.196.170.5 8.8.8.8 8.8.4.4 ``` When DNS service is stopped, Server Admin sometimes still keeps spinning. Having a look at Servername > Network > shows that in the pane with "Network Interfaces" the DNS name is empty. `nslookup -type=ptr z.y.x.91.in-addr.arpa` returns the correct value. A `dig PTR z.y.x.91.in-addr.arpa` for the PTR is ok, and a `dig PTR z.y.x.91.in-addr.arpa +trace` stops after recursion number 4: ``` . 77760 IN NS m.root-servers.net. ...<cut>... . 77760 IN NS l.root-servers.net. ;; Received 244 bytes from 91.196.170.5#53(91.196.170.5) in 5 ms in-addr.arpa. 172800 IN NS a.in-addr-servers.arpa. ...<cut>... in-addr.arpa. 172800 IN NS f.in-addr-servers.arpa. ;; Received 432 bytes from 192.203.230.10#53(e.root-servers.net) in 7 ms 91.in-addr.arpa. 86400 IN NS sec3.apnic.net. ...<cut>... 91.in-addr.arpa. 86400 IN NS sns-pb.isc.org. ;; Received 200 bytes from 193.0.9.1#53(f.in-addr-servers.arpa) in 2 ms 170.196.91.in-addr.arpa. 172800 IN NS ns2.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns3.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns1.technotop.nl. ;; Received 110 bytes from 193.0.9.5#53(pri.authdns.ripe.net) in 1 ms ;; connection timed out; no servers could be reached ``` Now there is also a new message logged: ``` Jun 29 14:49:10 mac01 servermgrd[1039]: Still servicing 0:0 requests after 300 seconds, with 1 sessions outstanding, resetting idleTimer ``` --- **Update #1** It looks like the issue might be a rDNS (reverse DNS) PTR configuration error. A `dig +trace` from a 10.5 machine at a different location results in `couldn't get address for 'ns3.technotop.nl': not found`. The network provider has been asked to fix this flaky (and faulty) DNS configuration. --- **Update #2** Another suspect is the built-in firewall. When the firewall is stopped there are no hangs. When the firewall is started, the spinning wheel never stops. --- **Update #3** The provider fixed ns3.technotop.nl by assigning a DNS A record with IP address 91.196.170.72 at August 23th. Result: still a spinning wheel at the bottom right part of Mac OS Server Admin, and after a few minutes > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Server). (kReceivedUnkownError). > > > Followed by a: > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Certificates). (kReceivedUnkownError). > > > **Update #4** The next issue is a CentOS version 5.4 software firewall at the servers where both ns1.technotop.nl and ns2.technotop.nl are running on, that kicked in on Mac OS X 10.7.4 Lion + Server + Admin Tools DNS traffic patterns: > > 123.45.67.89 # lfd: (PERMBLOCK) 123.45.67.89 has had more than 4 temp blocks in the last 86400 secs - Sun Jun 17 21:20:08 2012 > > > After clearing this block in the CentOS firewall, the firewall block is back within 10 hours for each IP address that is running 10.7.4 and is having a reverse DNS name that is authoritatively served by the CentOS 5.4 machines. Let's see what a whitelist on the CentOS firewall will do for machines running Mac OS 10.7.4. --- **Question** How to fix this DNS service related servermgrd flock(servermgr\_info) error (for instance by factory default resetting dns service)?
2012/06/24
[ "https://apple.stackexchange.com/questions/54636", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/21252/" ]
Review the firewall configuration of the authoritative DNS servers for the PTR records of your (public) IP address. In our case, when looking up the PTR records of the public IP address (123.45.67.89 for example) by using the reverse notation (89.67.45.123.in-addr.arpa) in Terminal on the Lion Server: 1. `$ dig NS 67.45.123.in-addr.arpa +short` results in: ns1.technotop.nl. ns2.technotop.nl. 2. `$ dig PTR 89.67.45.123.in-addr.arpa @ns1.technotop.nl` results in: ; <<>> DiG 9.7.3-P3 <<>> PTR 89.67.45.123.in-addr.arpa @ns1.technotop.nl ;; global options: +cmd ;; connection timed out; no servers could be reached In other words the DNS packets were discarded by an intermediary firewall. After whitelisting the IP adress of the Mac OS X Server in the firewall of each authorative DNS server, the "getAndLockContext: flock(servermgr\_info) FATAL time out" issue was gone.
1. Add a firewall "Address Group" for IP address "127.0.0.1". 2. Give the "Services"-tab "Allow all traffic" permissions for that newly created group.
54,636
On a 10.7.4 Lion Server installation the Server Admin.app fails to start correctly. The window is drawn and the last known server and its services are displayed, but a spinning wheel keeps spinning on the bottom status bar. Console.app log shows: ``` Jun 24 18:19:56 mac01 servermgrd[437]: [437] error in getAndLockContext: flock(servermgr_info) FATAL time out Jun 24 18:19:56 mac01 servermgrd[437]: [437] process will force-quit to avoid deadlock Jun 24 18:19:56 mac01 servermgrd[437]: outstanding requests are: ( { Command = getHistory; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = getState; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = Idle; Module = "servermgr_info"; Timestamp = "2012-06-24 16:18:50 +0000"; } ) Jun 24 18:19:56 mac01 com.apple.launchd[1] (com.apple.servermgrd[437]): Exited with code: 1 ``` There are **3 services enabled: dns, firewall, mail**. DNS plugin gave an error message which cannot be reproduced. Other errors in Console.app are: ``` Jun 28 12:49:58 mac01 ServerBackup[32087]: Error in calling backup command for service postgresql, error :=69 Jun 28 12:51:24 mac01 mds[99]: (Error) Volume: Could not find requested backup type:2 for volume Jun 28 12:53:01 mac01 mds[99]: (Error) Server: ==== XPC handleXPCMessage XPC_ERROR_CONNECTION_INVALID ``` (Regression) Other sources suggested to try: 1. review DNS settings, no problem found there 2. check the hostname with `sudo changeip -checkhostname`, no problem found there 3. destroy the Open Directory installation, OD is not used here 4. reboot, that did not solve the problem 5. replace `/Library/Preferences/com.apple.servermgrd.plist` with a known good copy, that did not help 6. replace the Server Admin.app itself with a known good copy, also did not improve 7. issuing a `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, as in my answer below, which only partly solves the issue. Server Admin started correctly once, but on second and consecutive launches the spinning wheel keeps spinning again and log shows the deadlock situations again. 8. untick 'require valid digital signature (SSL)' in server admin prefs just incase you haven't trusted your server cert, no change. 9. check if it is a user issue, by creating a new admin user and try starting server admin from that login, errors out (kReceivedUnknownError says Server Admin, process will force-quit to avoid deadlock is in the log, but no outstanding requests are in the log) 10. Changed the connecting server address from 'name.local' to '127.0.0.1', no change. 11. `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo rm -r /var/servermgrd;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, no change 12. Server.app > hardware > hostname > settings > uncheck dedicate resources to server services, reboot, check again, reboot, no change 13. `$ diskutil repairPermissions /;sudo reboot`, no change 14. corrected the rDNS entry to match the machine name, so that Server.app no longer displays an alert that the network has changed on every boot. Other repeating log file entries are: ``` 29-06-12 02:58:01,943 configd: network configuration changed. 29-06-12 02:58:33,575 configd: network configuration changed. 29-06-12 02:58:33,597 configd: network configuration changed. 29-06-12 02:58:34,266 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv4 rules 29-06-12 02:58:34,578 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv6 rules 29-06-12 02:59:50,707 servermgrd: servermgr_filebrowser:Error:servermgr_filebrowser: Error getting quotas for volume /Volumes/H of type exfat ``` After hours of trying to isolate the problem, I can reproduce that the flock(servermgr\_info) FATAL time out is related to the local DNS service. When DNS service is started the Server Admin.app generates the flock(servermgr\_info) FATAL time out, when DNS is then stopped (and `$ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist` to be sure that there is a clean starting point) next time Server Admin.app behaves OK and no flock(servermgr\_info) FATAL time out is logged. Anonymised serveradmin DNS configuration extracted using `$ sudo serveradmin settings dns`) is here: ``` dns:acls:_array_index:0:name = "com.apple.ServerAdmin.DNS.public" dns:acls:_array_index:0:addressMatchList:_array_index:0 = "localhost" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:name = "xyz.nl" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:0 = "1.1.1.237" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:1 = "2.2.1.247" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:2 = "1.2.1.59" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:3 = "2.1.1.23" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:primaryZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:allowRecursion = "com.apple.ServerAdmin.DNS.public" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:reverseZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:name = "com.apple.ServerAdmin.DNS.public" dns:isBonjourClientBrowsingEnabled = no ``` Irony is that localhost is not configured as DNS resolver: ``` $ networksetup -getdnsservers Ethernet 91.196.170.5 8.8.8.8 8.8.4.4 ``` When DNS service is stopped, Server Admin sometimes still keeps spinning. Having a look at Servername > Network > shows that in the pane with "Network Interfaces" the DNS name is empty. `nslookup -type=ptr z.y.x.91.in-addr.arpa` returns the correct value. A `dig PTR z.y.x.91.in-addr.arpa` for the PTR is ok, and a `dig PTR z.y.x.91.in-addr.arpa +trace` stops after recursion number 4: ``` . 77760 IN NS m.root-servers.net. ...<cut>... . 77760 IN NS l.root-servers.net. ;; Received 244 bytes from 91.196.170.5#53(91.196.170.5) in 5 ms in-addr.arpa. 172800 IN NS a.in-addr-servers.arpa. ...<cut>... in-addr.arpa. 172800 IN NS f.in-addr-servers.arpa. ;; Received 432 bytes from 192.203.230.10#53(e.root-servers.net) in 7 ms 91.in-addr.arpa. 86400 IN NS sec3.apnic.net. ...<cut>... 91.in-addr.arpa. 86400 IN NS sns-pb.isc.org. ;; Received 200 bytes from 193.0.9.1#53(f.in-addr-servers.arpa) in 2 ms 170.196.91.in-addr.arpa. 172800 IN NS ns2.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns3.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns1.technotop.nl. ;; Received 110 bytes from 193.0.9.5#53(pri.authdns.ripe.net) in 1 ms ;; connection timed out; no servers could be reached ``` Now there is also a new message logged: ``` Jun 29 14:49:10 mac01 servermgrd[1039]: Still servicing 0:0 requests after 300 seconds, with 1 sessions outstanding, resetting idleTimer ``` --- **Update #1** It looks like the issue might be a rDNS (reverse DNS) PTR configuration error. A `dig +trace` from a 10.5 machine at a different location results in `couldn't get address for 'ns3.technotop.nl': not found`. The network provider has been asked to fix this flaky (and faulty) DNS configuration. --- **Update #2** Another suspect is the built-in firewall. When the firewall is stopped there are no hangs. When the firewall is started, the spinning wheel never stops. --- **Update #3** The provider fixed ns3.technotop.nl by assigning a DNS A record with IP address 91.196.170.72 at August 23th. Result: still a spinning wheel at the bottom right part of Mac OS Server Admin, and after a few minutes > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Server). (kReceivedUnkownError). > > > Followed by a: > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Certificates). (kReceivedUnkownError). > > > **Update #4** The next issue is a CentOS version 5.4 software firewall at the servers where both ns1.technotop.nl and ns2.technotop.nl are running on, that kicked in on Mac OS X 10.7.4 Lion + Server + Admin Tools DNS traffic patterns: > > 123.45.67.89 # lfd: (PERMBLOCK) 123.45.67.89 has had more than 4 temp blocks in the last 86400 secs - Sun Jun 17 21:20:08 2012 > > > After clearing this block in the CentOS firewall, the firewall block is back within 10 hours for each IP address that is running 10.7.4 and is having a reverse DNS name that is authoritatively served by the CentOS 5.4 machines. Let's see what a whitelist on the CentOS firewall will do for machines running Mac OS 10.7.4. --- **Question** How to fix this DNS service related servermgrd flock(servermgr\_info) error (for instance by factory default resetting dns service)?
2012/06/24
[ "https://apple.stackexchange.com/questions/54636", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/21252/" ]
I had the same issue. As suggested here, I tracked the problem down to a bad NS record (typo) for the reverse zone. changeip -checkhostname reported no issues manually checking the forward/reverse all looked good. But when I specifically checked the NS record for the reverse zone, noticed the typo.
1. Add a firewall "Address Group" for IP address "127.0.0.1". 2. Give the "Services"-tab "Allow all traffic" permissions for that newly created group.
54,636
On a 10.7.4 Lion Server installation the Server Admin.app fails to start correctly. The window is drawn and the last known server and its services are displayed, but a spinning wheel keeps spinning on the bottom status bar. Console.app log shows: ``` Jun 24 18:19:56 mac01 servermgrd[437]: [437] error in getAndLockContext: flock(servermgr_info) FATAL time out Jun 24 18:19:56 mac01 servermgrd[437]: [437] process will force-quit to avoid deadlock Jun 24 18:19:56 mac01 servermgrd[437]: outstanding requests are: ( { Command = getHistory; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = getState; Module = "servermgr_info"; Timestamp = "2012-06-24 16:17:51 +0000"; }, { Command = Idle; Module = "servermgr_info"; Timestamp = "2012-06-24 16:18:50 +0000"; } ) Jun 24 18:19:56 mac01 com.apple.launchd[1] (com.apple.servermgrd[437]): Exited with code: 1 ``` There are **3 services enabled: dns, firewall, mail**. DNS plugin gave an error message which cannot be reproduced. Other errors in Console.app are: ``` Jun 28 12:49:58 mac01 ServerBackup[32087]: Error in calling backup command for service postgresql, error :=69 Jun 28 12:51:24 mac01 mds[99]: (Error) Volume: Could not find requested backup type:2 for volume Jun 28 12:53:01 mac01 mds[99]: (Error) Server: ==== XPC handleXPCMessage XPC_ERROR_CONNECTION_INVALID ``` (Regression) Other sources suggested to try: 1. review DNS settings, no problem found there 2. check the hostname with `sudo changeip -checkhostname`, no problem found there 3. destroy the Open Directory installation, OD is not used here 4. reboot, that did not solve the problem 5. replace `/Library/Preferences/com.apple.servermgrd.plist` with a known good copy, that did not help 6. replace the Server Admin.app itself with a known good copy, also did not improve 7. issuing a `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, as in my answer below, which only partly solves the issue. Server Admin started correctly once, but on second and consecutive launches the spinning wheel keeps spinning again and log shows the deadlock situations again. 8. untick 'require valid digital signature (SSL)' in server admin prefs just incase you haven't trusted your server cert, no change. 9. check if it is a user issue, by creating a new admin user and try starting server admin from that login, errors out (kReceivedUnknownError says Server Admin, process will force-quit to avoid deadlock is in the log, but no outstanding requests are in the log) 10. Changed the connecting server address from 'name.local' to '127.0.0.1', no change. 11. `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo rm -r /var/servermgrd;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist`, no change 12. Server.app > hardware > hostname > settings > uncheck dedicate resources to server services, reboot, check again, reboot, no change 13. `$ diskutil repairPermissions /;sudo reboot`, no change 14. corrected the rDNS entry to match the machine name, so that Server.app no longer displays an alert that the network has changed on every boot. Other repeating log file entries are: ``` 29-06-12 02:58:01,943 configd: network configuration changed. 29-06-12 02:58:33,575 configd: network configuration changed. 29-06-12 02:58:33,597 configd: network configuration changed. 29-06-12 02:58:34,266 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv4 rules 29-06-12 02:58:34,578 servermgrd: servermgr_ipfilter:ipfw config:Notice:Flushed IPv6 rules 29-06-12 02:59:50,707 servermgrd: servermgr_filebrowser:Error:servermgr_filebrowser: Error getting quotas for volume /Volumes/H of type exfat ``` After hours of trying to isolate the problem, I can reproduce that the flock(servermgr\_info) FATAL time out is related to the local DNS service. When DNS service is started the Server Admin.app generates the flock(servermgr\_info) FATAL time out, when DNS is then stopped (and `$ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist;sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.servermgrd.plist` to be sure that there is a clean starting point) next time Server Admin.app behaves OK and no flock(servermgr\_info) FATAL time out is logged. Anonymised serveradmin DNS configuration extracted using `$ sudo serveradmin settings dns`) is here: ``` dns:acls:_array_index:0:name = "com.apple.ServerAdmin.DNS.public" dns:acls:_array_index:0:addressMatchList:_array_index:0 = "localhost" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:name = "xyz.nl" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:0 = "1.1.1.237" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:1 = "2.2.1.247" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:2 = "1.2.1.59" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:secondaryZones:_array_id:xyz.nl:ipAddresses:_array_index:3 = "2.1.1.23" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:primaryZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:allowRecursion = "com.apple.ServerAdmin.DNS.public" dns:views:_array_id:com.apple.ServerAdmin.DNS.public:reverseZones = _empty_array dns:views:_array_id:com.apple.ServerAdmin.DNS.public:name = "com.apple.ServerAdmin.DNS.public" dns:isBonjourClientBrowsingEnabled = no ``` Irony is that localhost is not configured as DNS resolver: ``` $ networksetup -getdnsservers Ethernet 91.196.170.5 8.8.8.8 8.8.4.4 ``` When DNS service is stopped, Server Admin sometimes still keeps spinning. Having a look at Servername > Network > shows that in the pane with "Network Interfaces" the DNS name is empty. `nslookup -type=ptr z.y.x.91.in-addr.arpa` returns the correct value. A `dig PTR z.y.x.91.in-addr.arpa` for the PTR is ok, and a `dig PTR z.y.x.91.in-addr.arpa +trace` stops after recursion number 4: ``` . 77760 IN NS m.root-servers.net. ...<cut>... . 77760 IN NS l.root-servers.net. ;; Received 244 bytes from 91.196.170.5#53(91.196.170.5) in 5 ms in-addr.arpa. 172800 IN NS a.in-addr-servers.arpa. ...<cut>... in-addr.arpa. 172800 IN NS f.in-addr-servers.arpa. ;; Received 432 bytes from 192.203.230.10#53(e.root-servers.net) in 7 ms 91.in-addr.arpa. 86400 IN NS sec3.apnic.net. ...<cut>... 91.in-addr.arpa. 86400 IN NS sns-pb.isc.org. ;; Received 200 bytes from 193.0.9.1#53(f.in-addr-servers.arpa) in 2 ms 170.196.91.in-addr.arpa. 172800 IN NS ns2.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns3.technotop.nl. 170.196.91.in-addr.arpa. 172800 IN NS ns1.technotop.nl. ;; Received 110 bytes from 193.0.9.5#53(pri.authdns.ripe.net) in 1 ms ;; connection timed out; no servers could be reached ``` Now there is also a new message logged: ``` Jun 29 14:49:10 mac01 servermgrd[1039]: Still servicing 0:0 requests after 300 seconds, with 1 sessions outstanding, resetting idleTimer ``` --- **Update #1** It looks like the issue might be a rDNS (reverse DNS) PTR configuration error. A `dig +trace` from a 10.5 machine at a different location results in `couldn't get address for 'ns3.technotop.nl': not found`. The network provider has been asked to fix this flaky (and faulty) DNS configuration. --- **Update #2** Another suspect is the built-in firewall. When the firewall is stopped there are no hangs. When the firewall is started, the spinning wheel never stops. --- **Update #3** The provider fixed ns3.technotop.nl by assigning a DNS A record with IP address 91.196.170.72 at August 23th. Result: still a spinning wheel at the bottom right part of Mac OS Server Admin, and after a few minutes > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Server). (kReceivedUnkownError). > > > Followed by a: > > "**The service has encountered an error.** > Try to refresh the view > (127.0.0.1/Certificates). (kReceivedUnkownError). > > > **Update #4** The next issue is a CentOS version 5.4 software firewall at the servers where both ns1.technotop.nl and ns2.technotop.nl are running on, that kicked in on Mac OS X 10.7.4 Lion + Server + Admin Tools DNS traffic patterns: > > 123.45.67.89 # lfd: (PERMBLOCK) 123.45.67.89 has had more than 4 temp blocks in the last 86400 secs - Sun Jun 17 21:20:08 2012 > > > After clearing this block in the CentOS firewall, the firewall block is back within 10 hours for each IP address that is running 10.7.4 and is having a reverse DNS name that is authoritatively served by the CentOS 5.4 machines. Let's see what a whitelist on the CentOS firewall will do for machines running Mac OS 10.7.4. --- **Question** How to fix this DNS service related servermgrd flock(servermgr\_info) error (for instance by factory default resetting dns service)?
2012/06/24
[ "https://apple.stackexchange.com/questions/54636", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/21252/" ]
I had the same issue. As suggested here, I tracked the problem down to a bad NS record (typo) for the reverse zone. changeip -checkhostname reported no issues manually checking the forward/reverse all looked good. But when I specifically checked the NS record for the reverse zone, noticed the typo.
Review the firewall configuration of the authoritative DNS servers for the PTR records of your (public) IP address. In our case, when looking up the PTR records of the public IP address (123.45.67.89 for example) by using the reverse notation (89.67.45.123.in-addr.arpa) in Terminal on the Lion Server: 1. `$ dig NS 67.45.123.in-addr.arpa +short` results in: ns1.technotop.nl. ns2.technotop.nl. 2. `$ dig PTR 89.67.45.123.in-addr.arpa @ns1.technotop.nl` results in: ; <<>> DiG 9.7.3-P3 <<>> PTR 89.67.45.123.in-addr.arpa @ns1.technotop.nl ;; global options: +cmd ;; connection timed out; no servers could be reached In other words the DNS packets were discarded by an intermediary firewall. After whitelisting the IP adress of the Mac OS X Server in the firewall of each authorative DNS server, the "getAndLockContext: flock(servermgr\_info) FATAL time out" issue was gone.
6,886,018
I'm building a WP7 app that gets all its data through WCF services. I want to implement MVVM-Light in it but in tutorials I've done, I see that in the ViewModelLocator it wants to create a static instance of all my ViewModels when the app starts. My problem is that in my constructors for my VM's is where I make my WCF calls with the results of course coming back in the callback. It is in the callback where I assign the results to my observable collection that my Views see. This works fine when not using MVVM-Light but if I implement it I can't have these WCF calls at startup as they pass parameters not known/available until the user uses the app (selecting items, etc.) I tried moving my calls to the WCF to the getter of my observable collection but it keeps calling the WCF in an endless loop. In all the samples of MVVM-light that I've seen I haven't seen anyone calling WCF services. Any suggestions as to where to put my WCF calls in the model?
2011/07/30
[ "https://Stackoverflow.com/questions/6886018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2391654/" ]
As ever in MVVM there is no *right* way ... as it is about feedom ... :-) You can put the code into your view model if you want. However, you then will have to also generate the design time data in the view model too - if you want to use it. The big disadvantage with this approach is that you introduce a coupling between your view model and your service code (as you will have to instantiate the service in your view model). The general approach to de-couple the components is to create an interface describing your service and injecting an instance of an object implementing this interface into your view model in it's constructor. This enables you to create a design time and a run time implementation and your view model does not care which one it uses - i.e. the objects are decoupled. **Edit** Injecting in my post **does not** imply hat you use an injection container/framework, it only means that you use an interface to abstract your service behavior, and then pass an implementor or of this interface into the constructor of your view model. You now can pass different implementatios of the interface when you create your view model, e.g. in a view locator. The pattern suggested is called "inversion of control" and injecting is a technique to pass objects created elsewhere into the class you creating. Through this your our class is now shielded from any detail knowledge of the implementators and they become interchangeable. Inversion of control containers - like ninject, unity, etc. - just help you automatically resolving dependencies, however, **they are not required** for using the in version of control pattern.
I don't think it's good to put WCF call in ViewModel, you should encapsulate the WCF call in another class. Your ViewModel should only contain the GUI logic. I think what you get from the WCF call is the model, you can use the model to create ViewModel.
6,886,018
I'm building a WP7 app that gets all its data through WCF services. I want to implement MVVM-Light in it but in tutorials I've done, I see that in the ViewModelLocator it wants to create a static instance of all my ViewModels when the app starts. My problem is that in my constructors for my VM's is where I make my WCF calls with the results of course coming back in the callback. It is in the callback where I assign the results to my observable collection that my Views see. This works fine when not using MVVM-Light but if I implement it I can't have these WCF calls at startup as they pass parameters not known/available until the user uses the app (selecting items, etc.) I tried moving my calls to the WCF to the getter of my observable collection but it keeps calling the WCF in an endless loop. In all the samples of MVVM-light that I've seen I haven't seen anyone calling WCF services. Any suggestions as to where to put my WCF calls in the model?
2011/07/30
[ "https://Stackoverflow.com/questions/6886018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2391654/" ]
As ever in MVVM there is no *right* way ... as it is about feedom ... :-) You can put the code into your view model if you want. However, you then will have to also generate the design time data in the view model too - if you want to use it. The big disadvantage with this approach is that you introduce a coupling between your view model and your service code (as you will have to instantiate the service in your view model). The general approach to de-couple the components is to create an interface describing your service and injecting an instance of an object implementing this interface into your view model in it's constructor. This enables you to create a design time and a run time implementation and your view model does not care which one it uses - i.e. the objects are decoupled. **Edit** Injecting in my post **does not** imply hat you use an injection container/framework, it only means that you use an interface to abstract your service behavior, and then pass an implementor or of this interface into the constructor of your view model. You now can pass different implementatios of the interface when you create your view model, e.g. in a view locator. The pattern suggested is called "inversion of control" and injecting is a technique to pass objects created elsewhere into the class you creating. Through this your our class is now shielded from any detail knowledge of the implementators and they become interchangeable. Inversion of control containers - like ninject, unity, etc. - just help you automatically resolving dependencies, however, **they are not required** for using the in version of control pattern.
Here is my example of my CommonServiceHelper.cs file ``` public void GetUserSettings(UserInfoIn input, Action<UserInfoOut, Exception> callback) { var proxy = new CommonServiceClient(); try { proxy.GetUserSettingsCompleted += (sender, eventargs) => { var userCallback = eventargs.UserState as Action<UserInfoOut, Exception>; if (userCallback == null) return; if (eventargs.Error != null) { userCallback(null, eventargs.Error); return; } userCallback(eventargs.Result, null); }; proxy.GetUserSettingsAsync(input, callback); } catch (Exception ex) { proxy.Abort(); //ErrorHelper.WriteErrorLog(ex.ToString()); } finally { if (proxy.State != CommunicationState.Closed) { proxy.CloseAsync(); } } } ``` Then in the ViewModel I call it like this: ``` var serviceCommon = new CommonServiceHelper(); serviceCommon.GetUserSettings(userSettingsInput, (result, error) => { if (result != null && error != null) { //everything is ok } else { //handle errors } }); ```
19,215,948
Can the synchronization statements be reordered. i.e : Can : ``` synchronized(A) { synchronized(B) { ...... } } ``` become : ``` synchronized(B) { synchronized(A) { ...... } } ```
2013/10/07
[ "https://Stackoverflow.com/questions/19215948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630327/" ]
> > Can the synchronization statements be reordered? > > > I assume you are asking if the compiler can reorder the `synchronized` blocks so the lock order happens in a different order than the code. The answer is no. A `synchronized` block (and a `volatile` field access) impose ordering restrictions on the compiler. In your case, you cannot move a monitor-enter before another monitor-enter nor a monitor-exit after another monitor-exit. See the grid below. To quote from [JSR 133 (Java Memory Model) FAQ](http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#synchronization): > > It is not possible, for example, for the compiler to move your code before an acquire or after a release. When we say that acquires and releases act on caches, we are using shorthand for a number of possible effects. > > > Doug Lea's [JSR-133 Cookbook](http://g.oswego.edu/dl/jmm/cookbook.html) has a grid which shows the reordering possibilities. A blank entry in the grid means that reordering is allowed. In your case, entering a `synchronized` block is a "MonitorEnter" (same reordering limitations as loading of a `volatile` field) and exiting a `synchronized` block is a "MonitorExit" (same as storing to a `volatile` field). ![enter image description here](https://i.stack.imgur.com/a5JHh.png)
Yes and no. The order must be consistent. Suppose you are creating a transaction between two bank accounts, and always grab the sender's lock first, then grab the receiver's lock. Problem is - say both Dan and Bob want to transfer money to each other at the same time. Thread 1 might grab Dan's lock, as it processes Dan's transaction to Bob. Then thread 2 grab's Bob's lock, as it processes Bob's transaction to Dan. Then, bam, deadlock. The morals are: 1. Lock less. 2. Read [Java: Concurrency in Practice](https://rads.stackoverflow.com/amzn/click/com/0321349601). My example is taken from there. I like arguing about the merits of books in programming as much as the next guy, but it's pretty rare you get comprehensive coverage of a difficult topic between two covers, so enjoy it. So this is the part of the answer where I guess at other things you might have been trying to ask instead, because the expectation is firmly on me that I act psychic. The JVM will not acquire the locks in an order different from which you have programmed. How do I know this? Because otherwise it would not be possible to solve the problem in the first half of my answer.
19,215,948
Can the synchronization statements be reordered. i.e : Can : ``` synchronized(A) { synchronized(B) { ...... } } ``` become : ``` synchronized(B) { synchronized(A) { ...... } } ```
2013/10/07
[ "https://Stackoverflow.com/questions/19215948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630327/" ]
> > Can the synchronization statements be reordered? > > > I assume you are asking if the compiler can reorder the `synchronized` blocks so the lock order happens in a different order than the code. The answer is no. A `synchronized` block (and a `volatile` field access) impose ordering restrictions on the compiler. In your case, you cannot move a monitor-enter before another monitor-enter nor a monitor-exit after another monitor-exit. See the grid below. To quote from [JSR 133 (Java Memory Model) FAQ](http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#synchronization): > > It is not possible, for example, for the compiler to move your code before an acquire or after a release. When we say that acquires and releases act on caches, we are using shorthand for a number of possible effects. > > > Doug Lea's [JSR-133 Cookbook](http://g.oswego.edu/dl/jmm/cookbook.html) has a grid which shows the reordering possibilities. A blank entry in the grid means that reordering is allowed. In your case, entering a `synchronized` block is a "MonitorEnter" (same reordering limitations as loading of a `volatile` field) and exiting a `synchronized` block is a "MonitorExit" (same as storing to a `volatile` field). ![enter image description here](https://i.stack.imgur.com/a5JHh.png)
Synchronized statements are never reordered by the compiler as it has a big effect on what ends up happening. Synchronized blocks are used to obtain a lock on the specific Object placed between the synchronized parenthesis. ``` private final Object LOCK_1 = new Object(); public void foo(){ synchronized(LOCK_1){ //code here... } } ``` Obtains the lock for Object LOCK\_1 and releases it when the synchronization block completes. Since synchronization blocks are used to guard against concurrent access it may be sometimes required to use multiple locks especially when multiple thread-unsafe objects are being written/read to/from. Consider the following code that uses a nested synchronization block: ``` private final Object LOCK_1 = new Object(); private final Object LOCK_2 = new Object(); public void bar(){ synchronized(LOCK_1){ //Point A synchronized(LOCK_2){ //Point B } //Point C } //Point D } ``` If we look at points A,B,C,D we can realize why the order of synchronization matters. First at point A, the lock for LOCK\_1 is obtained therefore any other threads trying to obtain LOCK\_1 is put into a queue. At point B, the currently executing thread owns the lock for **both** LOCK\_1 and LOCK\_2. At point C, the currently executing thread has **released** the lock for LOCK\_2 At point D, the currently executing thread has released all locks. If we flip this example around and decided to put LOCK\_2 on the outer block, you will realize that the thread's order of obtaining locks changes which has a big effect on what it ends up doing. Normally, when I make programs with synchronization blocks I use one MUTEX object per thread-unsafe resource I am accessing (or one MUTEX per group). Say I want to read from a stream using LOCK\_1 and write to a stream using LOCK\_2. It would be illogical to think that swapping the locking order around means the same thing. Consider that LOCK\_2 (the writing lock) is being held by another thread. If we have LOCK\_1 on the outer block the currently executing thread can at least process all the reading code before being put into a queue for the writing lock (essentially, the ability to execute code at point A). If we flipped the order of the locks around, the currently executing thread will end up having to wait for the writing is complete, then proceed onto reading **and** writing whilst holding onto the writing lock (all the way through reading too). Another problem that comes up when the order of locks are switched (and not consistently, some code has LOCK\_1 first and others have LOCK\_2 first). Consider that two threads both eagerly try to execute code which have different locking orders. Thread 1 obtains LOCK\_1 in the outer block and thread 2 obtains LOCK\_2 from the outer block. Now when thread 1 tries to obtain LOCK\_2, it can't since thread 2 has it. And when thread 2 tries to obtain LOCK\_1, it can't either because thread 1 has it. The two threads essentially block on each other forever, forming a **deadlock** situation. To answer your question, if you want to lock on two objects immediately without doing any sort of processing between locks then the order is irrelevant (essentially no processing at point A or C). **HOWEVER** it is *essential* to keep the order consistent throughout your program as to avoid deadlocking.
12,096,325
I want to select a range of model records via created\_at attribute, I tried this query ``` Client.where('created_at BETWEEN ? AND ?', 30.days.from_now, DateTime.now.utc) ``` But it return an empty array. ``` 1.9.3-p125 :029 > Client.where('created_at BETWEEN ? AND ?', 30.days.from_now, DateTime.now.utc) Posting Load (1.0ms) SELECT `clients`.* FROM `clients` WHERE (created_at BETWEEN '2012-09-22 16:30:04' AND '2012-08-23') => [] ``` Also I want to group this records into array of arrays using `.day` method, I mean if I've 10 records I wanna group records which have created in the same day into separated array!
2012/08/23
[ "https://Stackoverflow.com/questions/12096325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/611350/" ]
``` Client. where(created_at: 30.days.ago..Date.current). group_by{|u| u.created_at.to_date} ``` You can pass `where` an array of values between which you would like the results (for inclusive vs. exclusive ranges, look up the differences between `..` and `...`). Further, you can group results by calling `group_by`, which will take a method to call, i.e. `.group_by(&:created_at)` or a block, as in my example. I used a full block because you wanted the results grouped by date rather than by specific timestamp. If you *actually* want the day of the month rather than the full date, you can also call `.group_by{ |u| u.created_at.day}`, but the date seems more useful to me.
I believe what you want is (note ago versus from now): ``` Client.where('created_at BETWEEN ? AND ?', 30.days.ago.utc, Time.now.utc) ```
35,752,918
``` private void button1_Click(object sender, EventArgs e) { string accountsSettingsFile = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\accounts" + "\\accounts.txt"; if (!File.Exists(accountsSettingsFile)) File.Create(accountsSettingsFile); System.IO.File.WriteAllText(accountsSettingsFile,); } ``` I want to build a string right before writing the content to the text file in the button click event. Maybe `StringBuilder` and to format it to contain all the data from some controls. I have a `textBox1`, `textBox2`, `textBox3` a `checkBox`. I want to get all this controls data and write it in lines to the text file. For example if in `textBox1` I have `"hello"` and in `textBox2` `"world"` and in `textBox3` `"hi"` and the `checkBox` is `false`, then the text file content should be something like: ``` hello world hi false ```
2016/03/02
[ "https://Stackoverflow.com/questions/35752918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5921706/" ]
I would go with something like this, especially if your list of controls might get longer later on: ``` private void button1_Click(object sender, EventArgs e) { Form1.WriteToFile(textBox1, textBox2, textBox3, checkBox); } private static void WriteToFile(params Control[] controls) { string accountsSettingsFile = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\accounts" + "\\accounts.txt"; List<string> lines = new List<string>(controls.Length); foreach (var control in controls) { string value = Form1.GetValueFromControl(control); //this will skip null entries, not sure you really //want to do that, otherwise when you read this file back in //you will have no idea which values represent which fields if (value != null) lines.Add(value); } //This will overwrite the file. //If you want to append use File.AppendAllLines File.WriteAllLines(accountsSettingsFile, lines); } private static string GetValueFromControl(Control control) { if (control is TextBox) { return ((TextBox)control).Text; } if (control is CheckBox) { return ((CheckBox)control).Checked.ToString(); } return null; } ``` Though, since you are using this for settings, writing raw values to a text file is a very brittle approach. Might I recommend using serialization? Though this requires that you reference Newtonsoft.Json (via nuget) in your project: ``` private void Button_Write_Click(object sender, EventArgs e) { AccountSettings settings = new AccountSettings(); settings.Setting1 = this.textBox1.Text; settings.Setting2 = this.textBox2.Text; settings.Setting3 = this.textBox3.Text; settings.CheckboxValue = this.checkBox.Checked; WriteJson(settings, SettingsFile); } private void Button_Read_Click(object sender, EventArgs e) { AccountSettings settings = ReadJson<AccountSettings>(SettingsFile); this.textBox1.Text = settings.Setting1; this.textBox2.Text = settings.Setting2; this.textBox3.Text = settings.Setting3; this.checkBox.Checked = settings.CheckboxValue; } private static string SettingsFile { get { return Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\accounts" + "\\accounts.txt"; } } private static void WriteJson(Object obj, string path) { var ser = new JsonSerializer(); using (var file = File.CreateText(path)) using (var writer = new JsonTextWriter(file)) { ser.Serialize(writer, obj); } } private static T ReadJson<T>(string path) where T: new() { if (!File.Exists(path)) return new T(); var ser = new JsonSerializer(); using (var file = File.OpenText(path)) using (var reader = new JsonTextReader(file)) { return ser.Deserialize<T>(reader); } } private class AccountSettings { public string Setting1 { get; set; } public string Setting2 { get; set; } public string Setting3 { get; set; } public bool CheckboxValue { get; set; } } } ``` This gives you a strongly typed `AccountSettings` object that can be written and read in a very concrete and repeatable manner.
``` var checked = checkBox.Checked ? "true" : "false"; var textToBeSaved = string.Format("{0}\n{1}\n{2}\n{3}", textBox1.Text, textBox2.Text, textBox3.Text, checked) ```
35,752,918
``` private void button1_Click(object sender, EventArgs e) { string accountsSettingsFile = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\accounts" + "\\accounts.txt"; if (!File.Exists(accountsSettingsFile)) File.Create(accountsSettingsFile); System.IO.File.WriteAllText(accountsSettingsFile,); } ``` I want to build a string right before writing the content to the text file in the button click event. Maybe `StringBuilder` and to format it to contain all the data from some controls. I have a `textBox1`, `textBox2`, `textBox3` a `checkBox`. I want to get all this controls data and write it in lines to the text file. For example if in `textBox1` I have `"hello"` and in `textBox2` `"world"` and in `textBox3` `"hi"` and the `checkBox` is `false`, then the text file content should be something like: ``` hello world hi false ```
2016/03/02
[ "https://Stackoverflow.com/questions/35752918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5921706/" ]
I would go with something like this, especially if your list of controls might get longer later on: ``` private void button1_Click(object sender, EventArgs e) { Form1.WriteToFile(textBox1, textBox2, textBox3, checkBox); } private static void WriteToFile(params Control[] controls) { string accountsSettingsFile = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\accounts" + "\\accounts.txt"; List<string> lines = new List<string>(controls.Length); foreach (var control in controls) { string value = Form1.GetValueFromControl(control); //this will skip null entries, not sure you really //want to do that, otherwise when you read this file back in //you will have no idea which values represent which fields if (value != null) lines.Add(value); } //This will overwrite the file. //If you want to append use File.AppendAllLines File.WriteAllLines(accountsSettingsFile, lines); } private static string GetValueFromControl(Control control) { if (control is TextBox) { return ((TextBox)control).Text; } if (control is CheckBox) { return ((CheckBox)control).Checked.ToString(); } return null; } ``` Though, since you are using this for settings, writing raw values to a text file is a very brittle approach. Might I recommend using serialization? Though this requires that you reference Newtonsoft.Json (via nuget) in your project: ``` private void Button_Write_Click(object sender, EventArgs e) { AccountSettings settings = new AccountSettings(); settings.Setting1 = this.textBox1.Text; settings.Setting2 = this.textBox2.Text; settings.Setting3 = this.textBox3.Text; settings.CheckboxValue = this.checkBox.Checked; WriteJson(settings, SettingsFile); } private void Button_Read_Click(object sender, EventArgs e) { AccountSettings settings = ReadJson<AccountSettings>(SettingsFile); this.textBox1.Text = settings.Setting1; this.textBox2.Text = settings.Setting2; this.textBox3.Text = settings.Setting3; this.checkBox.Checked = settings.CheckboxValue; } private static string SettingsFile { get { return Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\accounts" + "\\accounts.txt"; } } private static void WriteJson(Object obj, string path) { var ser = new JsonSerializer(); using (var file = File.CreateText(path)) using (var writer = new JsonTextWriter(file)) { ser.Serialize(writer, obj); } } private static T ReadJson<T>(string path) where T: new() { if (!File.Exists(path)) return new T(); var ser = new JsonSerializer(); using (var file = File.OpenText(path)) using (var reader = new JsonTextReader(file)) { return ser.Deserialize<T>(reader); } } private class AccountSettings { public string Setting1 { get; set; } public string Setting2 { get; set; } public string Setting3 { get; set; } public bool CheckboxValue { get; set; } } } ``` This gives you a strongly typed `AccountSettings` object that can be written and read in a very concrete and repeatable manner.
``` private void button1_Click(object sender, EventArgs e) { string accountsSettingsFile = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\accounts" + "\\accounts.txt"; if (!File.Exists(accountsSettingsFile)) File.Create(accountsSettingsFile); //New Code StringBuilder accountText = new StringBuilder(); accountText.AppendLine(textbox1.Text); accountText.AppendLine(textbox2.Text); accountText.AppendLine(textbox3.Text); accountText.AppendLine(checkbox.Checked.ToString().ToLowerInvariant()); //Above line assumes you want a trailing newline System.IO.File.WriteAllText(accountsSettingsFile, accountText.toString()); } ``` Of course, this is pretty boring and isn't particularly scaleable, if you wanted to generate a dynamic page with multiple accounts being entered at once, you could use `Page.FindControl` to loop through your text boxes and append all of them to the file.
9,408,210
> > **Possible Duplicate:** > > [Display numbers from 1 to 100 without loops or conditions](https://stackoverflow.com/questions/2044033/display-numbers-from-1-to-100-without-loops-or-conditions) > > > Interview question: Print 1 to 10 without any loop in java.
2012/02/23
[ "https://Stackoverflow.com/questions/9408210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559070/" ]
Simple way: `System.out.println` the values: ``` System.out.println(1); System.out.println(2); System.out.println(3); System.out.println(4); System.out.println(5); System.out.println(6); System.out.println(7); System.out.println(8); System.out.println(9); System.out.println(10); ``` Complex way: use recursion ``` public void recursiveMe(int n) { if(n <= 10) {// 10 is the max limit System.out.println(n);//print n recursiveMe(n+1);//call recursiveMe with n=n+1 } } recursiveMe(1); // call the function with 1. ```
If you like your programs obtuse, no loops, condition statements or main method. ``` static int i = 0; static { try { recurse(); } catch (Throwable t) { System.exit(0); } } private static void recurse() { System.out.print(++i + 0 / (i - 11) + " "); recurse(); } ``` --- This uses a loop but may be an interesting answer ``` Random random = new Random(-6732303926L); for(int i = 0; i < 10; i++) System.out.print((1+random.nextInt(10))+" "); } ``` You can restructure this to not use a loop.
83,619
I'm displaying an overview table of items. The items have a: * category * a date * additional, domain-specific information that needs to be displayed in the same view On the overview list, only one item is shown per category. The **most interesting**, from the user's point of view, is an item **in a given category** that has the latest date, but **no later than the current date**. For example, suppose that today is 2015-08-26. Our datastore looks like this: * Item 1, Category A, 2015-04-12 * **Item 2, Category A, 2015-06-30** * **Item 3, Category B, 2015-07-12** * Item 4, Category B, 2016-11-15 (the most user-relevant ones are **bolded**) However, it is **also important that the user is made aware of items with dates in the future**. --- Regarding ideas for a UI to present the situation described above, ones that come to mind are either: * provide a filter view for showing "future" items. ![mockup](https://i.stack.imgur.com/hQliu.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fhQliu.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) * or mark categories with "future" items in some way (including a relevant mouseover). ![mockup](https://i.stack.imgur.com/v7Wsr.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fv7Wsr.png) None of these feel perfect, however. So, **what would be the optimum way to present such data, given the two constraints (temporal relevance, and presence of "future" items)**?
2015/08/26
[ "https://ux.stackexchange.com/questions/83619", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/33936/" ]
It wasnt made clear if they only need to know if there are future items or if they need to know what these items are. I'll go under the premise that they do. It's also not clear why this is important. I'll add a bit of data to your example. Item 1, Category A, 2015-04-12 Item 2, Category A, 2015-06-30 Item 3, Category B, 2015-07-12 Item 4, Category B, 2016-11-15 Item 5, Category B, 2016-11-17 So here you have an on-demand tooltip that would show all the future items. [![enter image description here](https://i.stack.imgur.com/iQK0B.png)](https://i.stack.imgur.com/iQK0B.png) And with the checkbox you can include **all** the future items. If the grid has filtering and sorting options I can quickly analyse data by filtering on category B for instance and have a timeline of future items in that category. Or I can filter by date etc...I think this gives your power users more flexibility. Maybe the tooltip is not there anymore when the checkbox is checked. I always try to give my users opportunities to use data in ways they didn't realize they could. The tooltip is nice for a quick overview. The checkbox gives the option to work with the data. [![enter image description here](https://i.stack.imgur.com/GNfic.png)](https://i.stack.imgur.com/GNfic.png)
The language in your wireframes doesn't seem to match how you're explaining things. It sounds like the thing a user needs to do to get from the full table to the "most interesting" view, is **hide future dates**. ![mockup](https://i.stack.imgur.com/l3mbd.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fl3mbd.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) Regarding the communication of future items, rather than mark every item, you could make future dates bold, or a different color, and explain that somewhere else in the UI.
83,619
I'm displaying an overview table of items. The items have a: * category * a date * additional, domain-specific information that needs to be displayed in the same view On the overview list, only one item is shown per category. The **most interesting**, from the user's point of view, is an item **in a given category** that has the latest date, but **no later than the current date**. For example, suppose that today is 2015-08-26. Our datastore looks like this: * Item 1, Category A, 2015-04-12 * **Item 2, Category A, 2015-06-30** * **Item 3, Category B, 2015-07-12** * Item 4, Category B, 2016-11-15 (the most user-relevant ones are **bolded**) However, it is **also important that the user is made aware of items with dates in the future**. --- Regarding ideas for a UI to present the situation described above, ones that come to mind are either: * provide a filter view for showing "future" items. ![mockup](https://i.stack.imgur.com/hQliu.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fhQliu.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) * or mark categories with "future" items in some way (including a relevant mouseover). ![mockup](https://i.stack.imgur.com/v7Wsr.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fv7Wsr.png) None of these feel perfect, however. So, **what would be the optimum way to present such data, given the two constraints (temporal relevance, and presence of "future" items)**?
2015/08/26
[ "https://ux.stackexchange.com/questions/83619", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/33936/" ]
It wasnt made clear if they only need to know if there are future items or if they need to know what these items are. I'll go under the premise that they do. It's also not clear why this is important. I'll add a bit of data to your example. Item 1, Category A, 2015-04-12 Item 2, Category A, 2015-06-30 Item 3, Category B, 2015-07-12 Item 4, Category B, 2016-11-15 Item 5, Category B, 2016-11-17 So here you have an on-demand tooltip that would show all the future items. [![enter image description here](https://i.stack.imgur.com/iQK0B.png)](https://i.stack.imgur.com/iQK0B.png) And with the checkbox you can include **all** the future items. If the grid has filtering and sorting options I can quickly analyse data by filtering on category B for instance and have a timeline of future items in that category. Or I can filter by date etc...I think this gives your power users more flexibility. Maybe the tooltip is not there anymore when the checkbox is checked. I always try to give my users opportunities to use data in ways they didn't realize they could. The tooltip is nice for a quick overview. The checkbox gives the option to work with the data. [![enter image description here](https://i.stack.imgur.com/GNfic.png)](https://i.stack.imgur.com/GNfic.png)
Okay. If I am reading this correct: items appear in the client-side database, they have a name, date (of creation or access), some metadata, maybe amount. The user need is to follow the right items availability. A simple date filter would allow your users filter data by date and filter out future only or existing items only. [![enter image description here](https://i.stack.imgur.com/OX1h6.png)](https://i.stack.imgur.com/OX1h6.png) Marking future items with some icon or a colored row highlight will not help users to sort out all the future things at once, but it won't hurt, either. I'd keep it, too.
83,619
I'm displaying an overview table of items. The items have a: * category * a date * additional, domain-specific information that needs to be displayed in the same view On the overview list, only one item is shown per category. The **most interesting**, from the user's point of view, is an item **in a given category** that has the latest date, but **no later than the current date**. For example, suppose that today is 2015-08-26. Our datastore looks like this: * Item 1, Category A, 2015-04-12 * **Item 2, Category A, 2015-06-30** * **Item 3, Category B, 2015-07-12** * Item 4, Category B, 2016-11-15 (the most user-relevant ones are **bolded**) However, it is **also important that the user is made aware of items with dates in the future**. --- Regarding ideas for a UI to present the situation described above, ones that come to mind are either: * provide a filter view for showing "future" items. ![mockup](https://i.stack.imgur.com/hQliu.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fhQliu.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups) * or mark categories with "future" items in some way (including a relevant mouseover). ![mockup](https://i.stack.imgur.com/v7Wsr.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fv7Wsr.png) None of these feel perfect, however. So, **what would be the optimum way to present such data, given the two constraints (temporal relevance, and presence of "future" items)**?
2015/08/26
[ "https://ux.stackexchange.com/questions/83619", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/33936/" ]
It wasnt made clear if they only need to know if there are future items or if they need to know what these items are. I'll go under the premise that they do. It's also not clear why this is important. I'll add a bit of data to your example. Item 1, Category A, 2015-04-12 Item 2, Category A, 2015-06-30 Item 3, Category B, 2015-07-12 Item 4, Category B, 2016-11-15 Item 5, Category B, 2016-11-17 So here you have an on-demand tooltip that would show all the future items. [![enter image description here](https://i.stack.imgur.com/iQK0B.png)](https://i.stack.imgur.com/iQK0B.png) And with the checkbox you can include **all** the future items. If the grid has filtering and sorting options I can quickly analyse data by filtering on category B for instance and have a timeline of future items in that category. Or I can filter by date etc...I think this gives your power users more flexibility. Maybe the tooltip is not there anymore when the checkbox is checked. I always try to give my users opportunities to use data in ways they didn't realize they could. The tooltip is nice for a quick overview. The checkbox gives the option to work with the data. [![enter image description here](https://i.stack.imgur.com/GNfic.png)](https://i.stack.imgur.com/GNfic.png)
After reading the comment thread on dennislees' answer, it seems like we have a table that's trying to do too much. There are two items of interest for the user. - What's the the most recently "delivered" item for each category - What items are scheduled to be "delivered" It'll make sense to break this up into 2 separate tables ![mockup](https://i.stack.imgur.com/wgqGE.png) [download bmml source](/plugins/mockups/download?image=http%3a%2f%2fi.stack.imgur.com%2fwgqGE.png) – Wireframes created with [Balsamiq Mockups](http://www.balsamiq.com/products/mockups)
14,556,569
For some reason, my camera app saves all photos rotated 90 degrees (pictures only look right when taken with camera on landscape mode) I believe onPictureTaken should rotate photos automatically but I read there is a problem with Samsung devices (I haven't been able to test it on another brand so I don't know if it's the case). This is my code: ``` public void onPictureTaken(byte[] data, Camera camera) { // Generate file name FileOutputStream outStream = null; outStream = new FileOutputStream(filePath); outStream.write(data); outStream.close(); ``` I was thinking it could be fixed by checking the orientation and rotating the byte array but there must be a more straightforward way to do it since handling byte arrays is a pain. How can I make sure photos are saved matching the orientation they were taken?
2013/01/28
[ "https://Stackoverflow.com/questions/14556569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
I think is caused by the character set you used in you HTML file. Check out the wiki page about charset <http://en.wikipedia.org/wiki/Character_encodings_in_HTML> And, this problem can also be caused by using a different charset in your text editor from your HTML charset. For non-ascii chars, I recommend to use UTF-8 as the charset. So you can add this line into your HTML file. in the <head> tag. ``` <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> ```
This is a character encoding issue. From the symptoms, it seems that the HTML document is in fact UTF-8 encoded, which is fine, but it is being treated as being in another encoding, probably ISO-8859-6. You can check this out by selecting UTF-8 in the character encoding menu in “View” command (or equivalent) in your browser when viewing your page. To fix this, make sure that the HTTP headers sent by server declare the encoding as UTF-8, or at least leave it unspecified. You can e.g. Rex Swain’s [HTTP header viewer](http://www.rexswain.com/httpview.html) to check this out. In addition, add the tag `<meta charset=utf-8>` as the first subelement of the `head` element; this alone would suffice *if* the server does not declare character encoding at all (i.e., it says `Content-Type: text/html` without `charset` parameter). If more information is needed, check out the W3C page on [character encodings](http://www.w3.org/International/O-charset.en.php).
19,154,780
``` public void clear() { lblage.Text = ""; lblclosingbirds.Text = ""; lbltypeoffeed.Text = ""; lbltypeoffeedf.Text = ""; lblstdfeed.Text = ""; lblstdfeedf.Text = ""; lblstdhd.Text = ""; lblstdhe.Text = ""; lblExpeggs.Text = ""; lblbirdsf.Text = ""; txtacteggs.Text = ""; txtactfeed.Text = ""; txtactfeedf.Text = ""; txtfemaleclosingstock50.Text = ""; txtfemaleclosingstock70.Text = ""; txtmale50kgcstock.Text = ""; txtmale70kgscstock.Text = ""; txtmort.Text = ""; txtmortf.Text = ""; txtuseeggs.Text = ""; ddlFemaleFeedtype.SelectedValue = "0"; ddlMaleFeedtype.SelectedValue = "0"; } ``` how to use foreach loop method for replace with clear()..please tell me.. any one... is it possible to write foreach loop...please tell me
2013/10/03
[ "https://Stackoverflow.com/questions/19154780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813924/" ]
``` void ClearAllControlsRecursive(Control container) { foreach(var control As Control in container.Controls) { if(typeof control is TextBox) { ((TextBox)control).Text = String.Empty; } if(control.HasControls()) { ClearAllControlsRecursive(control); } } } ``` then call this method like this: ``` ClearAllControlsRecursive(yourContainer); ``` You can also switch on the control type and clear the values accordingly.
you can try like this ``` foreach (object control in form1.Controls) { if (control is TextBox) { control.Text = ""; } } ```
19,154,780
``` public void clear() { lblage.Text = ""; lblclosingbirds.Text = ""; lbltypeoffeed.Text = ""; lbltypeoffeedf.Text = ""; lblstdfeed.Text = ""; lblstdfeedf.Text = ""; lblstdhd.Text = ""; lblstdhe.Text = ""; lblExpeggs.Text = ""; lblbirdsf.Text = ""; txtacteggs.Text = ""; txtactfeed.Text = ""; txtactfeedf.Text = ""; txtfemaleclosingstock50.Text = ""; txtfemaleclosingstock70.Text = ""; txtmale50kgcstock.Text = ""; txtmale70kgscstock.Text = ""; txtmort.Text = ""; txtmortf.Text = ""; txtuseeggs.Text = ""; ddlFemaleFeedtype.SelectedValue = "0"; ddlMaleFeedtype.SelectedValue = "0"; } ``` how to use foreach loop method for replace with clear()..please tell me.. any one... is it possible to write foreach loop...please tell me
2013/10/03
[ "https://Stackoverflow.com/questions/19154780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813924/" ]
``` void ClearAllControlsRecursive(Control container) { foreach(var control As Control in container.Controls) { if(typeof control is TextBox) { ((TextBox)control).Text = String.Empty; } if(control.HasControls()) { ClearAllControlsRecursive(control); } } } ``` then call this method like this: ``` ClearAllControlsRecursive(yourContainer); ``` You can also switch on the control type and clear the values accordingly.
you can use this extension method : ``` public static IEnumerable<TControl> GetChildControls(this Control control) where TControl : Control { var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>(); return children.SelectMany(c => GetChildControls(c)).Concat(children); } ``` use : ``` foreach (TextBox tb in this.GetChildControls<TextBox>()) { tb.Text = String.Empty; } ``` and [here](https://stackoverflow.com/questions/297526/what-is-the-best-way-to-clear-all-controls-on-a-form-c) is a code(answer the question) for clear all controls on the form. **Another method** : ``` yourForm.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear()); ```
19,154,780
``` public void clear() { lblage.Text = ""; lblclosingbirds.Text = ""; lbltypeoffeed.Text = ""; lbltypeoffeedf.Text = ""; lblstdfeed.Text = ""; lblstdfeedf.Text = ""; lblstdhd.Text = ""; lblstdhe.Text = ""; lblExpeggs.Text = ""; lblbirdsf.Text = ""; txtacteggs.Text = ""; txtactfeed.Text = ""; txtactfeedf.Text = ""; txtfemaleclosingstock50.Text = ""; txtfemaleclosingstock70.Text = ""; txtmale50kgcstock.Text = ""; txtmale70kgscstock.Text = ""; txtmort.Text = ""; txtmortf.Text = ""; txtuseeggs.Text = ""; ddlFemaleFeedtype.SelectedValue = "0"; ddlMaleFeedtype.SelectedValue = "0"; } ``` how to use foreach loop method for replace with clear()..please tell me.. any one... is it possible to write foreach loop...please tell me
2013/10/03
[ "https://Stackoverflow.com/questions/19154780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813924/" ]
``` void ClearAllControlsRecursive(Control container) { foreach(var control As Control in container.Controls) { if(typeof control is TextBox) { ((TextBox)control).Text = String.Empty; } if(control.HasControls()) { ClearAllControlsRecursive(control); } } } ``` then call this method like this: ``` ClearAllControlsRecursive(yourContainer); ``` You can also switch on the control type and clear the values accordingly.
``` void ClearAllControlsRecursive(Control container) { foreach (var control in container.Controls) { if (control is TextBox) { ((TextBox)control).Text = String.Empty; } } } ``` and i cal this method like... ``` ClearAllControlsRecursive(panel1); ```
19,154,780
``` public void clear() { lblage.Text = ""; lblclosingbirds.Text = ""; lbltypeoffeed.Text = ""; lbltypeoffeedf.Text = ""; lblstdfeed.Text = ""; lblstdfeedf.Text = ""; lblstdhd.Text = ""; lblstdhe.Text = ""; lblExpeggs.Text = ""; lblbirdsf.Text = ""; txtacteggs.Text = ""; txtactfeed.Text = ""; txtactfeedf.Text = ""; txtfemaleclosingstock50.Text = ""; txtfemaleclosingstock70.Text = ""; txtmale50kgcstock.Text = ""; txtmale70kgscstock.Text = ""; txtmort.Text = ""; txtmortf.Text = ""; txtuseeggs.Text = ""; ddlFemaleFeedtype.SelectedValue = "0"; ddlMaleFeedtype.SelectedValue = "0"; } ``` how to use foreach loop method for replace with clear()..please tell me.. any one... is it possible to write foreach loop...please tell me
2013/10/03
[ "https://Stackoverflow.com/questions/19154780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813924/" ]
you can try like this ``` foreach (object control in form1.Controls) { if (control is TextBox) { control.Text = ""; } } ```
you can use this extension method : ``` public static IEnumerable<TControl> GetChildControls(this Control control) where TControl : Control { var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>(); return children.SelectMany(c => GetChildControls(c)).Concat(children); } ``` use : ``` foreach (TextBox tb in this.GetChildControls<TextBox>()) { tb.Text = String.Empty; } ``` and [here](https://stackoverflow.com/questions/297526/what-is-the-best-way-to-clear-all-controls-on-a-form-c) is a code(answer the question) for clear all controls on the form. **Another method** : ``` yourForm.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear()); ```
19,154,780
``` public void clear() { lblage.Text = ""; lblclosingbirds.Text = ""; lbltypeoffeed.Text = ""; lbltypeoffeedf.Text = ""; lblstdfeed.Text = ""; lblstdfeedf.Text = ""; lblstdhd.Text = ""; lblstdhe.Text = ""; lblExpeggs.Text = ""; lblbirdsf.Text = ""; txtacteggs.Text = ""; txtactfeed.Text = ""; txtactfeedf.Text = ""; txtfemaleclosingstock50.Text = ""; txtfemaleclosingstock70.Text = ""; txtmale50kgcstock.Text = ""; txtmale70kgscstock.Text = ""; txtmort.Text = ""; txtmortf.Text = ""; txtuseeggs.Text = ""; ddlFemaleFeedtype.SelectedValue = "0"; ddlMaleFeedtype.SelectedValue = "0"; } ``` how to use foreach loop method for replace with clear()..please tell me.. any one... is it possible to write foreach loop...please tell me
2013/10/03
[ "https://Stackoverflow.com/questions/19154780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813924/" ]
``` void ClearAllControlsRecursive(Control container) { foreach (var control in container.Controls) { if (control is TextBox) { ((TextBox)control).Text = String.Empty; } } } ``` and i cal this method like... ``` ClearAllControlsRecursive(panel1); ```
you can try like this ``` foreach (object control in form1.Controls) { if (control is TextBox) { control.Text = ""; } } ```
19,154,780
``` public void clear() { lblage.Text = ""; lblclosingbirds.Text = ""; lbltypeoffeed.Text = ""; lbltypeoffeedf.Text = ""; lblstdfeed.Text = ""; lblstdfeedf.Text = ""; lblstdhd.Text = ""; lblstdhe.Text = ""; lblExpeggs.Text = ""; lblbirdsf.Text = ""; txtacteggs.Text = ""; txtactfeed.Text = ""; txtactfeedf.Text = ""; txtfemaleclosingstock50.Text = ""; txtfemaleclosingstock70.Text = ""; txtmale50kgcstock.Text = ""; txtmale70kgscstock.Text = ""; txtmort.Text = ""; txtmortf.Text = ""; txtuseeggs.Text = ""; ddlFemaleFeedtype.SelectedValue = "0"; ddlMaleFeedtype.SelectedValue = "0"; } ``` how to use foreach loop method for replace with clear()..please tell me.. any one... is it possible to write foreach loop...please tell me
2013/10/03
[ "https://Stackoverflow.com/questions/19154780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813924/" ]
``` void ClearAllControlsRecursive(Control container) { foreach (var control in container.Controls) { if (control is TextBox) { ((TextBox)control).Text = String.Empty; } } } ``` and i cal this method like... ``` ClearAllControlsRecursive(panel1); ```
you can use this extension method : ``` public static IEnumerable<TControl> GetChildControls(this Control control) where TControl : Control { var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>(); return children.SelectMany(c => GetChildControls(c)).Concat(children); } ``` use : ``` foreach (TextBox tb in this.GetChildControls<TextBox>()) { tb.Text = String.Empty; } ``` and [here](https://stackoverflow.com/questions/297526/what-is-the-best-way-to-clear-all-controls-on-a-form-c) is a code(answer the question) for clear all controls on the form. **Another method** : ``` yourForm.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear()); ```
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
It is possible that the type is in an assembly that has not yet been loaded. Later in your program it then is. If you look at the output window this should give you sn idea of when the assemblies are being loaded.
And if you exlucde mscorlib assembly?? , you can try this: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(asb=>!asb.FullName.StartsWith("mscorlib")).ToList(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ```
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
Problem you are facing is caused by design of [GetAssemblies](http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx) method of `AppDomain` class - according to documentation this method: > > Gets the assemblies that have been loaded into the execution context of this application domain. > > > So when in your program type fails to be found first time - its assembly isn't obviously loaded by the application yet. And afterwards - when some functionality from assembly that contains type in question had been used - assembly is already loaded, and same code can already find missing type. Please try loading assemblies directly. Instead of using: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); ``` you can use: ``` List<Assembly> assemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(assembly => Assembly.LoadFrom(assembly.Name)).ToList(); ```
It is possible that the type is in an assembly that has not yet been loaded. Later in your program it then is. If you look at the output window this should give you sn idea of when the assemblies are being loaded.
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
It is possible that the type is in an assembly that has not yet been loaded. Later in your program it then is. If you look at the output window this should give you sn idea of when the assemblies are being loaded.
BTW if you *do* know the `FullName` of the assembly containing the type (or an assembly containing a `TypeForwardedToAttribute` for the type) you *can* use `Type.GetType`. Specifically, `Type.GetType(Assembly.CreateQualifiedName(assembly.FullName, myTypeName))` which will look something like: ``` Type.GetType("Some.Complete.Namespace.myTypeName, Some.Assembly.Name, Version=1.2.3.4, Culture=neutral, PublicKeyToken=ffffffffffffffff"); ``` This *will load* the assembly if it is not already, assuming the framework can resolve the location of the assembly. Here's my sample LinqPad query confirming the parenthetic `TypeForwardedToAttribute` remark: ``` var u = (from a in AppDomain.CurrentDomain.GetAssemblies() let t = a.GetType("System.Lazy`2") where t != null select t).FirstOrDefault(); (u?.AssemblyQualifiedName).Dump(); u = Type.GetType("System.Lazy`2, System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); (u?.AssemblyQualifiedName).Dump(); ``` Output: > > *null* > > System.Lazy`2, System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 > > >
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
It is possible that the type is in an assembly that has not yet been loaded. Later in your program it then is. If you look at the output window this should give you sn idea of when the assemblies are being loaded.
Another [answer](https://stackoverflow.com/a/39489661/147511) shows the best way for obtaining (at runtime) a `Type` defined in an `Assembly` that might not be loaded: ``` var T1 = Type.GetType("System.Web.Configuration.IAssemblyCache, " + "System.Web, " + "Version=4.0.0.0, " + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a"); ``` As you can see, unfortunately that method requires you to supply the full [AssemblyQualifiedName](https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx) of the `Type` and will not work with any of the [abbreviated forms](https://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx#Anchor_2) of the [assembly name](https://msdn.microsoft.com/en-us/library/system.reflection.assemblyname(v=vs.110).aspx) that I tried. This somewhat defeats our main purposes here. If you knew that much detail about the assembly, it wouldn't be that much harder to just load it yourself: ``` var T2 = Assembly.Load("System.Web, " + "Version=4.0.0.0, " + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a") .GetType("System.Web.Configuration.IAssemblyCache"); ``` Although these two examples look similar, they execute very different code paths; note for example, that the latter version calls an *instance* overload on `Assembly.GetType` versus the *static* call `Type.GetType`. Because of this, the second version is probably faster or more efficient. Either way, though, you seem to end up at the following CLR internal method, and with the second argument set to `false`, and this is why *neither method* goes to the trouble of searching for the required assembly on your behalf. > > [System.Runtime.Remoting.RemotingServices] > > private static RuntimeType **LoadClrTypeWithPartialBindFallback**( > >                   String typeName, > >                   bool partialFallback); > > > A tiny step forward from these inconveniences would be to instead call this CLR method yourself, but with the `partialFallback` parameter set to **true**. In this mode, the function will accept a truncated version of the `AssemblyQualifiedName` and will *locate and load* the relevant assembly, as necessary: ``` static Func<String, bool, TypeInfo> LoadClrTypeWithPartialBindFallback = typeof(RemotingServices) .GetMethod("LoadClrTypeWithPartialBindFallback", (BindingFlags)0x28) .CreateDelegate(typeof(Func<String, bool, TypeInfo>)) as Func<String, bool, TypeInfo>; // ... var T3 = LoadClrTypeWithPartialBindFallback( "System.Web.Configuration.IAssemblyCache, System.Web", true); // <-- enables searching for the assembly ``` This works as shown, and also continues to support specifying the full `AssemblyQualifiedName` as in the earlier examples. This is a small improvement, but it's still not a fully unqualified namespace search, because you do still have to specify the short name of the assembly, even if it might be deduced from the namespace that appears in the type name itself.
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
Problem you are facing is caused by design of [GetAssemblies](http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx) method of `AppDomain` class - according to documentation this method: > > Gets the assemblies that have been loaded into the execution context of this application domain. > > > So when in your program type fails to be found first time - its assembly isn't obviously loaded by the application yet. And afterwards - when some functionality from assembly that contains type in question had been used - assembly is already loaded, and same code can already find missing type. Please try loading assemblies directly. Instead of using: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); ``` you can use: ``` List<Assembly> assemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(assembly => Assembly.LoadFrom(assembly.Name)).ToList(); ```
And if you exlucde mscorlib assembly?? , you can try this: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(asb=>!asb.FullName.StartsWith("mscorlib")).ToList(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ```
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
Another [answer](https://stackoverflow.com/a/39489661/147511) shows the best way for obtaining (at runtime) a `Type` defined in an `Assembly` that might not be loaded: ``` var T1 = Type.GetType("System.Web.Configuration.IAssemblyCache, " + "System.Web, " + "Version=4.0.0.0, " + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a"); ``` As you can see, unfortunately that method requires you to supply the full [AssemblyQualifiedName](https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx) of the `Type` and will not work with any of the [abbreviated forms](https://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx#Anchor_2) of the [assembly name](https://msdn.microsoft.com/en-us/library/system.reflection.assemblyname(v=vs.110).aspx) that I tried. This somewhat defeats our main purposes here. If you knew that much detail about the assembly, it wouldn't be that much harder to just load it yourself: ``` var T2 = Assembly.Load("System.Web, " + "Version=4.0.0.0, " + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a") .GetType("System.Web.Configuration.IAssemblyCache"); ``` Although these two examples look similar, they execute very different code paths; note for example, that the latter version calls an *instance* overload on `Assembly.GetType` versus the *static* call `Type.GetType`. Because of this, the second version is probably faster or more efficient. Either way, though, you seem to end up at the following CLR internal method, and with the second argument set to `false`, and this is why *neither method* goes to the trouble of searching for the required assembly on your behalf. > > [System.Runtime.Remoting.RemotingServices] > > private static RuntimeType **LoadClrTypeWithPartialBindFallback**( > >                   String typeName, > >                   bool partialFallback); > > > A tiny step forward from these inconveniences would be to instead call this CLR method yourself, but with the `partialFallback` parameter set to **true**. In this mode, the function will accept a truncated version of the `AssemblyQualifiedName` and will *locate and load* the relevant assembly, as necessary: ``` static Func<String, bool, TypeInfo> LoadClrTypeWithPartialBindFallback = typeof(RemotingServices) .GetMethod("LoadClrTypeWithPartialBindFallback", (BindingFlags)0x28) .CreateDelegate(typeof(Func<String, bool, TypeInfo>)) as Func<String, bool, TypeInfo>; // ... var T3 = LoadClrTypeWithPartialBindFallback( "System.Web.Configuration.IAssemblyCache, System.Web", true); // <-- enables searching for the assembly ``` This works as shown, and also continues to support specifying the full `AssemblyQualifiedName` as in the earlier examples. This is a small improvement, but it's still not a fully unqualified namespace search, because you do still have to specify the short name of the assembly, even if it might be deduced from the namespace that appears in the type name itself.
And if you exlucde mscorlib assembly?? , you can try this: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(asb=>!asb.FullName.StartsWith("mscorlib")).ToList(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ```
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
Problem you are facing is caused by design of [GetAssemblies](http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx) method of `AppDomain` class - according to documentation this method: > > Gets the assemblies that have been loaded into the execution context of this application domain. > > > So when in your program type fails to be found first time - its assembly isn't obviously loaded by the application yet. And afterwards - when some functionality from assembly that contains type in question had been used - assembly is already loaded, and same code can already find missing type. Please try loading assemblies directly. Instead of using: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); ``` you can use: ``` List<Assembly> assemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(assembly => Assembly.LoadFrom(assembly.Name)).ToList(); ```
BTW if you *do* know the `FullName` of the assembly containing the type (or an assembly containing a `TypeForwardedToAttribute` for the type) you *can* use `Type.GetType`. Specifically, `Type.GetType(Assembly.CreateQualifiedName(assembly.FullName, myTypeName))` which will look something like: ``` Type.GetType("Some.Complete.Namespace.myTypeName, Some.Assembly.Name, Version=1.2.3.4, Culture=neutral, PublicKeyToken=ffffffffffffffff"); ``` This *will load* the assembly if it is not already, assuming the framework can resolve the location of the assembly. Here's my sample LinqPad query confirming the parenthetic `TypeForwardedToAttribute` remark: ``` var u = (from a in AppDomain.CurrentDomain.GetAssemblies() let t = a.GetType("System.Lazy`2") where t != null select t).FirstOrDefault(); (u?.AssemblyQualifiedName).Dump(); u = Type.GetType("System.Lazy`2, System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); (u?.AssemblyQualifiedName).Dump(); ``` Output: > > *null* > > System.Lazy`2, System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 > > >
12,422,744
I had an issue that code `Type.GetType(myTypeName)` was returning `null` because assembly with that type is not current executing assembly. The solution I found for this issue is next: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); Type myType = assemblies.SelectMany(a => a.GetTypes()) .Single(t => t.FullName == myTypeName); ``` The problem is that the first run of this code causes exception `"Sequence contains no matching element"`. When I call this part of code again - everything is ok and needed Type is loaded. Can anyone explain such behavior? Why in the scope of first call no needed assembly/type found?
2012/09/14
[ "https://Stackoverflow.com/questions/12422744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/801306/" ]
Problem you are facing is caused by design of [GetAssemblies](http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx) method of `AppDomain` class - according to documentation this method: > > Gets the assemblies that have been loaded into the execution context of this application domain. > > > So when in your program type fails to be found first time - its assembly isn't obviously loaded by the application yet. And afterwards - when some functionality from assembly that contains type in question had been used - assembly is already loaded, and same code can already find missing type. Please try loading assemblies directly. Instead of using: ``` var assemblies = AppDomain.CurrentDomain.GetAssemblies(); ``` you can use: ``` List<Assembly> assemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies().Select(assembly => Assembly.LoadFrom(assembly.Name)).ToList(); ```
Another [answer](https://stackoverflow.com/a/39489661/147511) shows the best way for obtaining (at runtime) a `Type` defined in an `Assembly` that might not be loaded: ``` var T1 = Type.GetType("System.Web.Configuration.IAssemblyCache, " + "System.Web, " + "Version=4.0.0.0, " + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a"); ``` As you can see, unfortunately that method requires you to supply the full [AssemblyQualifiedName](https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx) of the `Type` and will not work with any of the [abbreviated forms](https://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx#Anchor_2) of the [assembly name](https://msdn.microsoft.com/en-us/library/system.reflection.assemblyname(v=vs.110).aspx) that I tried. This somewhat defeats our main purposes here. If you knew that much detail about the assembly, it wouldn't be that much harder to just load it yourself: ``` var T2 = Assembly.Load("System.Web, " + "Version=4.0.0.0, " + "Culture=neutral, " + "PublicKeyToken=b03f5f7f11d50a3a") .GetType("System.Web.Configuration.IAssemblyCache"); ``` Although these two examples look similar, they execute very different code paths; note for example, that the latter version calls an *instance* overload on `Assembly.GetType` versus the *static* call `Type.GetType`. Because of this, the second version is probably faster or more efficient. Either way, though, you seem to end up at the following CLR internal method, and with the second argument set to `false`, and this is why *neither method* goes to the trouble of searching for the required assembly on your behalf. > > [System.Runtime.Remoting.RemotingServices] > > private static RuntimeType **LoadClrTypeWithPartialBindFallback**( > >                   String typeName, > >                   bool partialFallback); > > > A tiny step forward from these inconveniences would be to instead call this CLR method yourself, but with the `partialFallback` parameter set to **true**. In this mode, the function will accept a truncated version of the `AssemblyQualifiedName` and will *locate and load* the relevant assembly, as necessary: ``` static Func<String, bool, TypeInfo> LoadClrTypeWithPartialBindFallback = typeof(RemotingServices) .GetMethod("LoadClrTypeWithPartialBindFallback", (BindingFlags)0x28) .CreateDelegate(typeof(Func<String, bool, TypeInfo>)) as Func<String, bool, TypeInfo>; // ... var T3 = LoadClrTypeWithPartialBindFallback( "System.Web.Configuration.IAssemblyCache, System.Web", true); // <-- enables searching for the assembly ``` This works as shown, and also continues to support specifying the full `AssemblyQualifiedName` as in the earlier examples. This is a small improvement, but it's still not a fully unqualified namespace search, because you do still have to specify the short name of the assembly, even if it might be deduced from the namespace that appears in the type name itself.