qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
226,735
I am looking at establish a circuit allowing to detect when one or two wire are cut such as a tamper system. When the wire are cut it should signal this a GPIO. I suppose I need to use a transistor connected to GPIO but I have a bit some difficulty to see how.
2016/04/06
[ "https://electronics.stackexchange.com/questions/226735", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/104309/" ]
![schematic](https://i.stack.imgur.com/A8UqT.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fA8UqT.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) *Figure 1. GPIO normally pulled low by tamper loop. Cutting loop causes GPIO to be pulled high by R1.* C1 will help eliminate any noise on a long tamper loop.
It depends on what level of tampering you want to be able to detect. The minimum approach is described by transistor. Note that a clever tamperer can simply ground the top line, then cut the loop and perform mischief. A more robust system uses two pins. The processor drives one with different values, then checks the other to verify the new output value is detected. For extra credit, you make the values pseudo-random, like what comes from something like a CRC calculation. However, all this only describes the logic, not the real implementation. I would not just want to connect processor pins directly to external wires, especially when tampering is a possibility. At least any processor input should be protected. CMOS inputs are high impedance, and there is no reason to require high speed, so 100 kΩ or so between any external connection and a processor input is a good idea. Depending on the level of abuse you want to be able to live thru, you may want your own clamping or rely on the built-in clamping circuitry of the processor. The processor may not be specified to operate correctly with current thru its clamping circuitry, but it should survive. For good tamper resistance, I'd say that external lines should be able to tolerate being connected to whatever line power is where the device will be used. That means 120 VAC here in North America, for example.
226,735
I am looking at establish a circuit allowing to detect when one or two wire are cut such as a tamper system. When the wire are cut it should signal this a GPIO. I suppose I need to use a transistor connected to GPIO but I have a bit some difficulty to see how.
2016/04/06
[ "https://electronics.stackexchange.com/questions/226735", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/104309/" ]
An alternative to detecting change in voltage on the GPIO pin would be to use a dedicated [current loop](https://en.wikipedia.org/wiki/Current_loop) controller. There exists many [4–20mA](https://electronics.stackexchange.com/tags/4-20ma/info) control circuits that will have a indicator pin for when there is no current flowing which you can monitor.
It depends on what level of tampering you want to be able to detect. The minimum approach is described by transistor. Note that a clever tamperer can simply ground the top line, then cut the loop and perform mischief. A more robust system uses two pins. The processor drives one with different values, then checks the other to verify the new output value is detected. For extra credit, you make the values pseudo-random, like what comes from something like a CRC calculation. However, all this only describes the logic, not the real implementation. I would not just want to connect processor pins directly to external wires, especially when tampering is a possibility. At least any processor input should be protected. CMOS inputs are high impedance, and there is no reason to require high speed, so 100 kΩ or so between any external connection and a processor input is a good idea. Depending on the level of abuse you want to be able to live thru, you may want your own clamping or rely on the built-in clamping circuitry of the processor. The processor may not be specified to operate correctly with current thru its clamping circuitry, but it should survive. For good tamper resistance, I'd say that external lines should be able to tolerate being connected to whatever line power is where the device will be used. That means 120 VAC here in North America, for example.
226,735
I am looking at establish a circuit allowing to detect when one or two wire are cut such as a tamper system. When the wire are cut it should signal this a GPIO. I suppose I need to use a transistor connected to GPIO but I have a bit some difficulty to see how.
2016/04/06
[ "https://electronics.stackexchange.com/questions/226735", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/104309/" ]
Pull up the GPIO externally to HIGH. Configure a cheap uC to trigger an interrupt when the pin value changes from HIGH->LOW.When you enter the ISR,you'l know that your circuit was tampered/cut. If you want to go a little further,you could use an [Event Monitor](http://www.nxp.com/documents/data_sheet/PCF2127.pdf) to capture such an event for you and log the time when it occurred. Note: The value of the wire must remain at a known value and not change/toggle. That is always HIGH. Or if you need to detect a LOW->HIGH,you can configure appropriately.
It depends on what level of tampering you want to be able to detect. The minimum approach is described by transistor. Note that a clever tamperer can simply ground the top line, then cut the loop and perform mischief. A more robust system uses two pins. The processor drives one with different values, then checks the other to verify the new output value is detected. For extra credit, you make the values pseudo-random, like what comes from something like a CRC calculation. However, all this only describes the logic, not the real implementation. I would not just want to connect processor pins directly to external wires, especially when tampering is a possibility. At least any processor input should be protected. CMOS inputs are high impedance, and there is no reason to require high speed, so 100 kΩ or so between any external connection and a processor input is a good idea. Depending on the level of abuse you want to be able to live thru, you may want your own clamping or rely on the built-in clamping circuitry of the processor. The processor may not be specified to operate correctly with current thru its clamping circuitry, but it should survive. For good tamper resistance, I'd say that external lines should be able to tolerate being connected to whatever line power is where the device will be used. That means 120 VAC here in North America, for example.
15,216,048
My Box Shadow is not showing in IE7 and IE8. ``` #bodyContainer{ background: url(../images/site_bg.png) repeat ; margin: 0px auto; width:1000px; float:left; position:relative; border: 1px solid #EEEEEE; /*background:#FFFFFF;*/ box-shadow: 0 0 5px 0 #000000; } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15216048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548927/" ]
You have to use the non-standard IE filter property. See [this article](http://hedgerwow.appspot.com/demo/shadow)
Accoding to `Box-shadow`'s [MDN compatibility table](https://developer.mozilla.org/en-US/docs/CSS/box-shadow#Browser_compatibility), Box-shadow doesn't support in IE7 and IE8. Check the same link (Notes section) for more info on alternative properties like [Dropshadow](http://msdn.microsoft.com/en-us/library/ms532985%28VS.85,loband%29.aspx) and [shadow](http://msdn.microsoft.com/en-us/library/ms533086%28VS.85,loband%29.aspx) properties. **Syntax**: ``` filter:progid:DXImageTransform.Microsoft.DropShadow(sProperties) ``` --- ``` filter:progid:DXImageTransform.Microsoft.Shadow(sProperties) ```
15,216,048
My Box Shadow is not showing in IE7 and IE8. ``` #bodyContainer{ background: url(../images/site_bg.png) repeat ; margin: 0px auto; width:1000px; float:left; position:relative; border: 1px solid #EEEEEE; /*background:#FFFFFF;*/ box-shadow: 0 0 5px 0 #000000; } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15216048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548927/" ]
Use [CSS3 PIE](http://css3pie.com/), which emulates [some CSS3 properties](http://css3pie.com/documentation/supported-css3-features/) in older versions of IE. It supports `box-shadow` ([except for](https://github.com/lojjic/PIE/issues/3) the `inset` keyword). and There are article about [CSS3 Box Shadow in Internet Explorer](http://placenamehere.com/article/384/css3boxshadowininternetexplorerblurshadow/) and [Box-shadow](http://www.css3.info/preview/box-shadow/). Hope this helps also you can use ``` style="FILTER: DropShadow(Color=#0066cc, OffX=5, OffY=-3, Positive=1);width:300px;font-size:20pt;" style="filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='-2', OffY='-2', Color='#c0c0c0', Positive='true')" ```
Accoding to `Box-shadow`'s [MDN compatibility table](https://developer.mozilla.org/en-US/docs/CSS/box-shadow#Browser_compatibility), Box-shadow doesn't support in IE7 and IE8. Check the same link (Notes section) for more info on alternative properties like [Dropshadow](http://msdn.microsoft.com/en-us/library/ms532985%28VS.85,loband%29.aspx) and [shadow](http://msdn.microsoft.com/en-us/library/ms533086%28VS.85,loband%29.aspx) properties. **Syntax**: ``` filter:progid:DXImageTransform.Microsoft.DropShadow(sProperties) ``` --- ``` filter:progid:DXImageTransform.Microsoft.Shadow(sProperties) ```
15,216,048
My Box Shadow is not showing in IE7 and IE8. ``` #bodyContainer{ background: url(../images/site_bg.png) repeat ; margin: 0px auto; width:1000px; float:left; position:relative; border: 1px solid #EEEEEE; /*background:#FFFFFF;*/ box-shadow: 0 0 5px 0 #000000; } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15216048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548927/" ]
You have to use the non-standard IE filter property. See [this article](http://hedgerwow.appspot.com/demo/shadow)
box-shadow is a feature of CSS3 hence it is not supported below ie9 you can check the compatibity here: <http://caniuse.com/#search=box-shadow>
15,216,048
My Box Shadow is not showing in IE7 and IE8. ``` #bodyContainer{ background: url(../images/site_bg.png) repeat ; margin: 0px auto; width:1000px; float:left; position:relative; border: 1px solid #EEEEEE; /*background:#FFFFFF;*/ box-shadow: 0 0 5px 0 #000000; } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15216048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548927/" ]
Use [CSS3 PIE](http://css3pie.com/), which emulates [some CSS3 properties](http://css3pie.com/documentation/supported-css3-features/) in older versions of IE. It supports `box-shadow` ([except for](https://github.com/lojjic/PIE/issues/3) the `inset` keyword). and There are article about [CSS3 Box Shadow in Internet Explorer](http://placenamehere.com/article/384/css3boxshadowininternetexplorerblurshadow/) and [Box-shadow](http://www.css3.info/preview/box-shadow/). Hope this helps also you can use ``` style="FILTER: DropShadow(Color=#0066cc, OffX=5, OffY=-3, Positive=1);width:300px;font-size:20pt;" style="filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='-2', OffY='-2', Color='#c0c0c0', Positive='true')" ```
You have to use the non-standard IE filter property. See [this article](http://hedgerwow.appspot.com/demo/shadow)
15,216,048
My Box Shadow is not showing in IE7 and IE8. ``` #bodyContainer{ background: url(../images/site_bg.png) repeat ; margin: 0px auto; width:1000px; float:left; position:relative; border: 1px solid #EEEEEE; /*background:#FFFFFF;*/ box-shadow: 0 0 5px 0 #000000; } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15216048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548927/" ]
You have to use the non-standard IE filter property. See [this article](http://hedgerwow.appspot.com/demo/shadow)
Box-Shadow is not compatible below IE9 Always check compatibility of CSS Properties using following link <http://caniuse.com/css-boxshadow>
15,216,048
My Box Shadow is not showing in IE7 and IE8. ``` #bodyContainer{ background: url(../images/site_bg.png) repeat ; margin: 0px auto; width:1000px; float:left; position:relative; border: 1px solid #EEEEEE; /*background:#FFFFFF;*/ box-shadow: 0 0 5px 0 #000000; } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15216048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548927/" ]
Use [CSS3 PIE](http://css3pie.com/), which emulates [some CSS3 properties](http://css3pie.com/documentation/supported-css3-features/) in older versions of IE. It supports `box-shadow` ([except for](https://github.com/lojjic/PIE/issues/3) the `inset` keyword). and There are article about [CSS3 Box Shadow in Internet Explorer](http://placenamehere.com/article/384/css3boxshadowininternetexplorerblurshadow/) and [Box-shadow](http://www.css3.info/preview/box-shadow/). Hope this helps also you can use ``` style="FILTER: DropShadow(Color=#0066cc, OffX=5, OffY=-3, Positive=1);width:300px;font-size:20pt;" style="filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='-2', OffY='-2', Color='#c0c0c0', Positive='true')" ```
box-shadow is a feature of CSS3 hence it is not supported below ie9 you can check the compatibity here: <http://caniuse.com/#search=box-shadow>
15,216,048
My Box Shadow is not showing in IE7 and IE8. ``` #bodyContainer{ background: url(../images/site_bg.png) repeat ; margin: 0px auto; width:1000px; float:left; position:relative; border: 1px solid #EEEEEE; /*background:#FFFFFF;*/ box-shadow: 0 0 5px 0 #000000; } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15216048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548927/" ]
Use [CSS3 PIE](http://css3pie.com/), which emulates [some CSS3 properties](http://css3pie.com/documentation/supported-css3-features/) in older versions of IE. It supports `box-shadow` ([except for](https://github.com/lojjic/PIE/issues/3) the `inset` keyword). and There are article about [CSS3 Box Shadow in Internet Explorer](http://placenamehere.com/article/384/css3boxshadowininternetexplorerblurshadow/) and [Box-shadow](http://www.css3.info/preview/box-shadow/). Hope this helps also you can use ``` style="FILTER: DropShadow(Color=#0066cc, OffX=5, OffY=-3, Positive=1);width:300px;font-size:20pt;" style="filter: progid:DXImageTransform.Microsoft.dropShadow (OffX='-2', OffY='-2', Color='#c0c0c0', Positive='true')" ```
Box-Shadow is not compatible below IE9 Always check compatibility of CSS Properties using following link <http://caniuse.com/css-boxshadow>
16,134,120
Visual Studio / monodevelop have awesome feature that can let you specify xml comments above every function / variable which is then displayed as a description of that function when you roll over it, click it etc. ``` /// <summary> /// This is example for stack overflow /// </summary> public void Foo() { } ``` This is cool, but it works only in your local code (within 1 project) how can I make these comments that are in functions in external library, which is referenced in another project, available in THAT project as well? It should be possible, because it works for .Net assemblies (when you reference a .Net library, you will be able to see these descriptions for functions in that library)
2013/04/21
[ "https://Stackoverflow.com/questions/16134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514983/" ]
You can generate the xml for documentation of your library using visual studio, check it [here](http://msdn.microsoft.com/en-us/library/vstudio/x4sa0ak0%28v=vs.100%29.aspx). > > The Generate XML documentation file property determines whether an XML > file will be generated during compilation. You set this property on > the Compile page (for Visual Basic) or Build page (for Visual C#) of > the Project Designer. When this option is selected, XML documentation > is automatically emitted into an XML file, which will have the same > name as your project and the .xml extension, [Reference](http://msdn.microsoft.com/en-us/library/vstudio/x4sa0ak0%28v=vs.100%29.aspx). > > >
You can use `/doc` and then bundle the generated documentation with your assemblies: <http://msdn.microsoft.com/en-us/library/3260k4x7.aspx>
6,411
How can I make backup from iPhoto without time machine?
2009/05/08
[ "https://serverfault.com/questions/6411", "https://serverfault.com", "https://serverfault.com/users/1968/" ]
iPhoto puts all of your photos into a library similar to the way iTunes puts all of your music into a music in a library folder structure. That being said you could easily just copy the library from your hard drive to another. I know you want to back it up, but here is some information on how to move the library and much of the info should be useful in your soluition: <http://basics4mac.com/article.php/move_iphoto_lib> and <http://www.hinkty.com/blogger/2006/02/how-to-move-your-iphoto-library-to.html> Also if you want to share a library between users/systems see here: <http://forums.macrumors.com/showthread.php?t=158248> And lastly there is a application manager which can handle much of this in a more simplier manner called [iPhoto Library Manager](http://www.fatcatsoftware.com/iplm/)
If you don't mind getting your hands dirty with the command line, there are a couple of great ways. Personally, I use rsync to keep my iPhoto library (and iTunes for that matter) coordinated between 3 systems by pushing out the newest copy whenever I make changes. ``` rsync -azv -e ssh ~/Pictures/iPhoto\ Library/ <remote_ip>:~/Pictures/iPhoto\ Library ``` Rsync is smart enough to only copy the changes, and not the entire library each time. Now, if you want something that performs regular backups with history you can also try [rdiff-backup](http://www.gnu.org/savannah-checkouts/non-gnu/rdiff-backup/). It uses rsync internally, which makes it fairly fast, and can be found in MacPorts.
415,701
I am working on my chess engine in C++ and I went for bitboards to represent the board. It is basically a 64-bit number for which I use the `bitset` library. I feel the most crucial part in performance comes through the move generation. Earlier I encoded moves as `std::string`'s in a `std::vector` which would perform moves on a 2-D array. A move has to include at the most basic, A start location, and an end location. That means for my purpose, two numbers would be enough. However, it shall also include two more attributes which are, castling rights(if any) en-passant squares. One choice is to use a `struct` to represent two coordinates and the additional two attributes. And then create an array of those moves. Another choice is to use a 16-bit number to represent a move. For example: 6-bits for the first number, 6-bits for the second. And the remaining for the additional values. And then store them in an array/vector/any container. Even a `std::vector<int>` can work. The main purpose is to be able to iterate through the container efficiently as it will happen **multiple** times. What is the best way to encode the move?
2020/09/09
[ "https://softwareengineering.stackexchange.com/questions/415701", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/-1/" ]
Questions like this usually boil down to a trade-off between memory usage and speed. A program which uses a highly packed representation for keeping boards in memory will always require some time to unpack the data into a form where it can evaluate and apply the game's semantics. This is especially true when this "unpacking" is done implicitly, by the accessor functions. Keeping boards and moves directly in an unpacked representation hence saves these CPU cycles. However, in reality, the situation becomes more complex: if your program has to manage lots of boards and moves, and it is going to process millions of them, small-size representations may increase speed, since more boards and moves can be kept in main memory or CPU cache. As a compromise for such scenarios, it is not uncommon to keep boards in a highly packed representation, unpack them explicitly when they are pulled from the queue or lookup-table (or whatever container your program uses for a tree search), process the unpacked representation to generate new boards and pack the results again to put them into the containers. As you see, this is going to depend on the gory details of the algorithms of your program, and it may sometimes depend on the hardware on which the program is executed. Hence, if you want maximum speed, there is no way around * implementing different approaches, and * benchmark them!
You want to store enough information to make the move and to undo the move. So that is start position, end position, piece taken, and piece converted to at the very least. 6 bit + 6 bit + 3 bit + 2 bit. If you want to take it to 16 bit at most, store 1 bit for "conversion" set if a pawn moves to the last row, and you can leave out either the 2 bit what the pawn was converted to, or you leave out 3 bits of the "end position" because it must be on the last row.
415,701
I am working on my chess engine in C++ and I went for bitboards to represent the board. It is basically a 64-bit number for which I use the `bitset` library. I feel the most crucial part in performance comes through the move generation. Earlier I encoded moves as `std::string`'s in a `std::vector` which would perform moves on a 2-D array. A move has to include at the most basic, A start location, and an end location. That means for my purpose, two numbers would be enough. However, it shall also include two more attributes which are, castling rights(if any) en-passant squares. One choice is to use a `struct` to represent two coordinates and the additional two attributes. And then create an array of those moves. Another choice is to use a 16-bit number to represent a move. For example: 6-bits for the first number, 6-bits for the second. And the remaining for the additional values. And then store them in an array/vector/any container. Even a `std::vector<int>` can work. The main purpose is to be able to iterate through the container efficiently as it will happen **multiple** times. What is the best way to encode the move?
2020/09/09
[ "https://softwareengineering.stackexchange.com/questions/415701", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/-1/" ]
Questions like this usually boil down to a trade-off between memory usage and speed. A program which uses a highly packed representation for keeping boards in memory will always require some time to unpack the data into a form where it can evaluate and apply the game's semantics. This is especially true when this "unpacking" is done implicitly, by the accessor functions. Keeping boards and moves directly in an unpacked representation hence saves these CPU cycles. However, in reality, the situation becomes more complex: if your program has to manage lots of boards and moves, and it is going to process millions of them, small-size representations may increase speed, since more boards and moves can be kept in main memory or CPU cache. As a compromise for such scenarios, it is not uncommon to keep boards in a highly packed representation, unpack them explicitly when they are pulled from the queue or lookup-table (or whatever container your program uses for a tree search), process the unpacked representation to generate new boards and pack the results again to put them into the containers. As you see, this is going to depend on the gory details of the algorithms of your program, and it may sometimes depend on the hardware on which the program is executed. Hence, if you want maximum speed, there is no way around * implementing different approaches, and * benchmark them!
Best way? No clue. It depends on what you are using this encoding for. For example the best way would for a human would be column/row to column/row. For a computer? Considering that you have a 64bit board it takes exactly 6 bits to identify a location. Even then extra information such the piece being white/black bishop reduces that to 5 bits. 12bit moves, don't pack them in shorts though, more efficient to pack them into a 64bit/128bit (5moves/10moves respectively). Alternately it might make more sense to step back and consider the board itself. A move is a state transition from one board-layout to another board layout. * 64 locations * 6 piece kinds + You can encode castling rights by having two rook types, so make that 7 piece kinds. * and empty. That makes 15 unique types. Simplistic 4 bit packing gives a 256 bits for the board. A game could be described by a list of such boards, which makes resuming a game, or even undoing moves a snap. If this were a chess playing service (playing many opponents) this can even help with caching decisions. Is that best? Not sure depends on what you want the move information for.
54,754,090
I am trying to see if two times, both with start and end times, overlap in any way. for instance, if A has a start time of 0800 and an end time of 0900 and I want to see if B, which has a start time of 0845 and an end time of 0945, interests/ overlaps it in any way. I don't care about the actual date just the times.
2019/02/18
[ "https://Stackoverflow.com/questions/54754090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9761440/" ]
If you want to do this specifically using moment.js then you can try this plugin `moment-range` which allows you to have two date ranges and a function `overlaps` that can check this for you. <https://github.com/rotaready/moment-range#overlaps> Alternatively, you can manually do this check with if statements as well if you don't want to use moment.js.
You want to check if the EndDate of A > StartDate of B EndDate of B > Start
126,532
So I have generic fantasy Human Empire, relatively Good folks, but mostly Orderly. Racially mostly homogeneous, some elves and dwarves are present, but 99% humans. And there is the Monster Empire, which is ruled by dragons, but has all kinds of naturally Evil monsters (and by Evil I mean DnD like alignments, so tangible Evil), from goblinoids to ogres and whatnot. Pre-Threat the two sides were in equilibrium: the monsters were never united enough to pose a significant threat to the otherwise also quite powerful Human Empire (lots of magic users and a strong army + various paramilitaristic organizations), and the Monster Empire is located in a hard to pass terrain, so a formal army's movements are extremely hindered. The monsters range from threat to only unskilled or old/wounded/ill/children to the mentioned dragons, which pose a significant threat to whole groups, though not unbeatable by any means. Border skirmishes were regular before the alliance. They both got undeniable proof that there is some Generic Threat that threatens the very existence of the world, and the lead dragon bands together with the Human King to stand togetherish against the threat. The world is a band of land from west to east, bound by mountains and waters. Monster Empire is to the west, Human Empire is in the middle, and the Threat comes from the east. The thing is, the threat is yet to materialize. What are some key points I would have to keep in mind when thinking about this? I would imagine the dragon would keep a sizable force in Human Empire, because of logistics, if the threat arrives (and they have no clear idea of how long it will take from the first actual sign to the invasion), they have to be there. So right now, there is a whole family of dragons (Evil, macho, aggressive), a good number of giant sized creatures (ogres, trolls, actual giants) and a sizable array of smaller goblionoids, orcs, kobolds and other cannon fodder. Is there any kind of historical reference for this? That might be a good basis for it, sans the Evil monsters part.
2018/10/02
[ "https://worldbuilding.stackexchange.com/questions/126532", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/55884/" ]
The US and Britain worked with the USSR in WW2. ----------------------------------------------- It's not exactly like your scenario, though, since the US+Britain and USSR made Germany fight a three-front war whereas your scenario is a one-front war. More importantly, there were people in US+Britain who were deluded into thinking that the USSR was a Workers Paradise.
Continued from my comment... There's a TV show running just now, "Britannia", that tells a story (a story expanded and exaggerated for the sake of romance/theatrics) of the second attempt of the Roman empire to invade Britain. As the story is told (minor spoiler), **after the Romans establish a foothold, while considered to be demonic outsiders by one dominant tribe, they're still possible allies in an upcoming war against the other dominant tribe**. Both tribes are willing to "sleep with the devil" against the more hated devil they know. This kind of thing happened and was encouraged by the Roman Empire as it made its conquests, many times.
29,934,164
I have two fragments within one fragment using ViewPager. Sometimes my app crash with following error: ``` java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.MyAcitivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.fragments.MyFragment: make sure class name exists, is public, and has an empty constructor that is public at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Method.java) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(NativeStart.java) Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.fragments.MyFragment: make sure class name exists, is public, and has an empty constructor that is public at android.support.v4.app.Fragment.instantiate(Fragment.java:413) at android.support.v4.app.FragmentState.instantiate(Fragment.java:97) at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1801) at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:213) at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:97) at com.buzzreel.MyActivity.onCreate(MyActivity.java:55) at android.app.Activity.performCreate(Activity.java:5411) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Method.java) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(NativeStart.java) Caused by: java.lang.InstantiationException: can't instantiate class com.fragments.MyFragment; no empty constructor at java.lang.Class.newInstanceImpl(Class.java) at java.lang.Class.newInstance(Class.java:1208) at android.support.v4.app.Fragment.instantiate(Fragment.java:402) at android.support.v4.app.FragmentState.instantiate(Fragment.java:97) at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1801) at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:213) at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:97) at com.buzzreel.MyActivity.onCreate(MyActivity.java:55) at android.app.Activity.performCreate(Activity.java:5411) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:149) at android.app.ActivityThread.main(ActivityThread.java:5257) at java.lang.reflect.Method.invokeNative(Method.java) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:633) at dalvik.system.NativeStart.main(NativeStart.java) ``` But i have two constructors in my fragment class as follows: ``` public MyFragment(CustomObject custom) { this.custom = custom; } public MyFragment() { } ``` My pager adapter call: ``` import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.fragments.MyFragment public class MyPagerAdapter extends FragmentPagerAdapter { private String tabtitles[] = new String[] { "Info" }; private CustomOjbect object; public MyPagerAdapter(FragmentManager fm, CustomOjbect object) { super(fm); this.object = object; } @Override public Fragment getItem(int index) { switch (index) { case 0: return new MyFragment(object); } return null; } @Override public int getCount() { return 1; } @Override public CharSequence getPageTitle(int position) { return tabtitles[position]; } } ``` Fragment Code [Code was big as other was relevant just keeping core code] ``` public class MyFragment extends Fragment implements OnClickListener { /** Variable declaration for widgets and views comes here **/ public MyFragment(CustomObject object) { this.object = object; } public MyFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_layout, container, false); initializeUIComponents(); /** ... .. rest of code **/ return view; } private void initializeUIComponents() { // ui views initialization } } ``` In View pager i call constructor with arguements. Why is it failing?
2015/04/29
[ "https://Stackoverflow.com/questions/29934164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3176004/" ]
The deadlock is at `Line 3`. At this line both the `Threads` are waiting continuously to acquire lock on resource `t`. The initial value of `t` is 0, which means it is already in a locked state, so for example if `Thread1` reaches first to `line 3` it waits till the value of `t` becomes 1 and similarly after some time `Thread2` will wait at the same line for `t` to become 1. In this way both the process will wait continuously for the resource creating a `deadlock.
Hint: You can avoid deadlocks by lock ordering. For example, all code must lock `s` before it locks `t`. The question demonstrates what can happen if that is not the case. You can "make changes to the initial semaphore values" to conform with lock ordering.
63,077,450
I've spent the last few hours trying to figure how to do something relatively simple- i'd like to write a python script that returns a number of strings from a predefined alphabet using certain weights. So for example ``` strings = 3 length= 4 alphabet = list('QWER') weights=[0.0, 0.0, 0.0, 1.0] ``` this would return ``` RRRR RRRR RRRR ``` or another example ``` strings = 2 length= 3 alphabet = list('ABC') weights=[0.3,0.3,0.3] ``` This would return ``` CBA ABC CAA ``` I've tried playing around with a number of example codes and this is the closest i've come- ``` import random import numpy as np LENGTH = 3 NO_CODES = 100 alphabet = list('ABCD') weights=[0.0, 0.0, 0.0, 1.0] np_alphabet = np.array(alphabet, dtype="|U1") np_codes = np.random.choice(np_alphabet, [NO_CODES, LENGTH]) codes = ["".join(np_codes[i]) for i in range(len(np_codes))] print(codes) ``` However, i know i'm not using the weight function correctly. If anyone can tell me what i'm doing wrong or suggest a better way to do it, that would be appreciated. As i'm sure you can tell i don't really know what i'm doing, so any advice would be useful.
2020/07/24
[ "https://Stackoverflow.com/questions/63077450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989644/" ]
SO thank you for the suggestions, i manged to puzzle through it- ``` import random for i in range(100): #number of strings a = random.choices(["A", "B", "C"], [0.5, 0.5, 0.0], k=100) #weights of strings random_sequence='' for i in range(0,5): #length of string random_sequence+=random.choice(a) print(random_sequence) ```
As of Python 3.6, there's a built-in method for this, [`random.choices()`](https://docs.python.org/3/library/random.html#random.choices). Here's a working example with output. ```py import random strings = 2 length= 3 alphabet = list('ABC') weights=[0.3,0.3,0.3] for i in range(10): print(random.choices(alphabet, weights, k=len(alphabet))) ```
64,366,902
My code: Added data in array adapter but last data only comming how to add all the data in spinner using arrayadapter ``` while (rs.next()) { int_EMP_ID = rs.getInt("EmpID"); str_EMP_Name = rs.getString("EmployeeName"); int User_ID_List[] = {int_EMP_ID}; String User_name_List[] = {str_EMP_Name}; for (int i=0;i<=10;i++) { // Step 2: Create and fill an ArrayAdapter with a bunch of "State" objects ArrayAdapter<Employee> spinnerArrayAdapter = new ArrayAdapter<Employee>(this, android.R.layout.simple_spinner_item, new Employee[]{ new Employee(User_ID_List[i], User_name_List[i]), new Employee(User_ID_List[i], User_name_List[i]) }); } ``` > > Blockquote > > >
2020/10/15
[ "https://Stackoverflow.com/questions/64366902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14454144/" ]
You *could* try doing a regex replacement here: ``` String input = "\"email_settings\": {\n \"email.starttls.enable\":\"true\",\n \"email.port\":\"111\",\n \"email.host\":\"xxxx\",\n \"email.auth\":\"true\",\n}"; String output = input.replaceAll("([ ]*\"email.host\":\".*?\")", " \"email.name\":\"myTest\",\n$1"); System.out.println(output); ``` This prints: ``` "email_settings": { "email.starttls.enable":"true", "email.port":"111", "email.name":"myTest", "email.host":"xxxx", "email.auth":"true", } ``` However, if you are dealing with proper JSON content, then you should consider using a JSON parser instead. Parse the JSON text into a Java POJO and then write out with the new field.
``` content = content.replace("\"email.host\":", "\"email.name\":\"myTest\",\n" + " \"email.host\":"); ``` Or you could look in to libraries which parse json files.
50,479,400
I'm trying to show my users notifications through my service that checks my database when an item is at it's set date it should send a notification. My problem is that when the date comes it doesn't send a notification. ``` databaseReference = FirebaseDatabase.getInstance().getReference().child("Groups").child(mGroupUid).child("HomeFragment").child("FreezerItems"); childEventListener = databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { HashMap<String, String> value = (HashMap<String, String>) dataSnapshot.getValue(); if (value != null) { String name = value.get("Name"); String date = value.get("Date"); SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy", Locale.US); try { dateFormat = sdf.parse(date); } catch (ParseException e) { Log.wtf("FailedtoChangeDate", "Fail"); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tomorrow = cal.getTime(); if (dateFormat.equals(tomorrow)) { GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext()); if (account != null) { String firstname = account.getGivenName(); mContentTitle = "Your " + name + " is about to be expired!"; mContentText = firstname + ", make sure to cook or eat your " + name + " by " + date; } Intent openApp = new Intent(getApplicationContext(), MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 100, openApp, PendingIntent.FLAG_UPDATE_CURRENT); notification = new NotificationCompat.Builder(getApplicationContext(), "Default") .setSmallIcon(R.drawable.ic_restaurant_black_24dp) .setContentTitle(mContentTitle) .setContentText(mContentText) .setLights(Color.GREEN, 2000, 1000) .setPriority(NotificationCompat.PRIORITY_MAX) .setStyle(new NotificationCompat.BigTextStyle().bigText(mContentText)) .setContentIntent(contentIntent) .setAutoCancel(true); createNotificationChannel(getApplicationContext()); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext()); notificationManager.notify(uniqueID, notification.build()); } } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); ``` I'm sure my notification works because when I remove `if (dateFormat.equals(tomorrow))` it sends a notifciation and works perfectly. This is also a service class and not a normal activity so maybe that has something to do with it.
2018/05/23
[ "https://Stackoverflow.com/questions/50479400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9554176/" ]
Implement the `textFieldDidBeginEditing` text field delegate method and set the text field's text if it doesn't already have a value. ``` func textFieldDidBeginEditing(_ textField: UITextField) { if textField.text!.isEmpty { // set the text as needed } } ```
``` import UIKit class ActivityPersonDetail : UIViewController,UITextFieldDelegate,UIPickerViewDataSource, UIPickerViewDelegate { let salutations = ["1", "2", "3","4","5","6","7","8","9","10","11","12"] func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return salutations.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return salutations[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { pickerTF.text = salutations[row] picker.isHidden = true } func textFieldDidBeginEditing(_ textField: UITextField) { if textField == self.pickerTF { picker.isHidden = false textField.endEditing(true) } } lazy var picker: UIPickerView = { let pickerView = UIPickerView() pickerView.delegate = self pickerView.translatesAutoresizingMaskIntoConstraints = false pickerView.backgroundColor = .white pickerTF.inputView = pickerView return pickerView }() let arrowImage: UIImageView = { let image = UIImageView() image.translatesAutoresizingMaskIntoConstraints = false image.image = #imageLiteral(resourceName: "down_arrow") image.contentMode = .scaleAspectFit return image } () lazy var pickerTF: UITextField = { let tf = UITextField() tf.delegate = self tf.translatesAutoresizingMaskIntoConstraints = false tf.textColor = .black tf.font = .systemFont(ofSize: 24, weight: .medium) tf.placeholder = salutations[0] return tf }() // // MARK :- viewDidLoad ============================================================================ // private var pickerView: UIPickerView! override func viewDidLoad() { super .viewDidLoad() view.backgroundColor = .white setupNavigationBar() setupViews() setupAutoLayout() } // ================ setupNavigationBar ============= func setupNavigationBar(){ title = "" hideBackTitle() navigationController?.navigationBar.barTintColor = .navBar } func hideBackTitle() { let backbarItem = UIBarButtonItem() backbarItem.title = "" navigationItem.backBarButtonItem = backbarItem } // ================ setupViews ============= func setupViews(){ view.addSubview(pickerTF) pickerTF.addSubview(arrowImage) view.addSubview(picker) picker.isHidden = true } // ================ setupAutoLayout ============= func setupAutoLayout() { pickerTF.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 80).isActive = true pickerTF.topAnchor.constraint(equalTo: view.topAnchor, constant: 80).isActive = true pickerTF.heightAnchor.constraint(equalToConstant: 60).isActive = true pickerTF.widthAnchor.constraint(equalToConstant: 70).isActive = true arrowImage.rightAnchor.constraint(equalTo: pickerTF.rightAnchor, constant: -15).isActive = true arrowImage.topAnchor.constraint(equalTo: pickerTF.topAnchor, constant: 16).isActive = true arrowImage.widthAnchor.constraint(equalToConstant: 22).isActive = true arrowImage.heightAnchor.constraint(equalToConstant: 22).isActive = true picker.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true picker.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true picker.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true picker.heightAnchor.constraint(equalToConstant: 100).isActive = true } } ```
50,479,400
I'm trying to show my users notifications through my service that checks my database when an item is at it's set date it should send a notification. My problem is that when the date comes it doesn't send a notification. ``` databaseReference = FirebaseDatabase.getInstance().getReference().child("Groups").child(mGroupUid).child("HomeFragment").child("FreezerItems"); childEventListener = databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { HashMap<String, String> value = (HashMap<String, String>) dataSnapshot.getValue(); if (value != null) { String name = value.get("Name"); String date = value.get("Date"); SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy", Locale.US); try { dateFormat = sdf.parse(date); } catch (ParseException e) { Log.wtf("FailedtoChangeDate", "Fail"); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tomorrow = cal.getTime(); if (dateFormat.equals(tomorrow)) { GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext()); if (account != null) { String firstname = account.getGivenName(); mContentTitle = "Your " + name + " is about to be expired!"; mContentText = firstname + ", make sure to cook or eat your " + name + " by " + date; } Intent openApp = new Intent(getApplicationContext(), MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 100, openApp, PendingIntent.FLAG_UPDATE_CURRENT); notification = new NotificationCompat.Builder(getApplicationContext(), "Default") .setSmallIcon(R.drawable.ic_restaurant_black_24dp) .setContentTitle(mContentTitle) .setContentText(mContentText) .setLights(Color.GREEN, 2000, 1000) .setPriority(NotificationCompat.PRIORITY_MAX) .setStyle(new NotificationCompat.BigTextStyle().bigText(mContentText)) .setContentIntent(contentIntent) .setAutoCancel(true); createNotificationChannel(getApplicationContext()); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext()); notificationManager.notify(uniqueID, notification.build()); } } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); ``` I'm sure my notification works because when I remove `if (dateFormat.equals(tomorrow))` it sends a notifciation and works perfectly. This is also a service class and not a normal activity so maybe that has something to do with it.
2018/05/23
[ "https://Stackoverflow.com/questions/50479400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9554176/" ]
Implement the `textFieldDidBeginEditing` text field delegate method and set the text field's text if it doesn't already have a value. ``` func textFieldDidBeginEditing(_ textField: UITextField) { if textField.text!.isEmpty { // set the text as needed } } ```
I'm going to build on rmaddy's answer and add more nuances and answers to questions in the comments. Main answer lays in the first extension, the rest of the code outlines class structure and components that need to be present for everything to work. ``` class ViewController { private var selectedItem: String = "" private let pickerList = [ "First item", "Second item", "Third item" ] override func viewDidLoad() { super.viewDidLoad() pickerTextField.delegate = self //... // Layout setup //... } private let pickerTextField: UITextField = { let textField = UITextField() textField.tintColor = .clear // hides cursor return textField }() //... // UI Elements including picker //... } extension ViewController: UITextFieldDelegate { internal func textFieldDidBeginEditing(_ textField: UITextField) { if textField == pickerTextField, let textFieldText = textField.text, textFieldText.isEmpty { pickerTextField.text = pickerList.first // fills textfield before any selection is made } } } extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource { //... // PickerView delegate methods //... } ```
50,479,400
I'm trying to show my users notifications through my service that checks my database when an item is at it's set date it should send a notification. My problem is that when the date comes it doesn't send a notification. ``` databaseReference = FirebaseDatabase.getInstance().getReference().child("Groups").child(mGroupUid).child("HomeFragment").child("FreezerItems"); childEventListener = databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { HashMap<String, String> value = (HashMap<String, String>) dataSnapshot.getValue(); if (value != null) { String name = value.get("Name"); String date = value.get("Date"); SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy", Locale.US); try { dateFormat = sdf.parse(date); } catch (ParseException e) { Log.wtf("FailedtoChangeDate", "Fail"); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tomorrow = cal.getTime(); if (dateFormat.equals(tomorrow)) { GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext()); if (account != null) { String firstname = account.getGivenName(); mContentTitle = "Your " + name + " is about to be expired!"; mContentText = firstname + ", make sure to cook or eat your " + name + " by " + date; } Intent openApp = new Intent(getApplicationContext(), MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 100, openApp, PendingIntent.FLAG_UPDATE_CURRENT); notification = new NotificationCompat.Builder(getApplicationContext(), "Default") .setSmallIcon(R.drawable.ic_restaurant_black_24dp) .setContentTitle(mContentTitle) .setContentText(mContentText) .setLights(Color.GREEN, 2000, 1000) .setPriority(NotificationCompat.PRIORITY_MAX) .setStyle(new NotificationCompat.BigTextStyle().bigText(mContentText)) .setContentIntent(contentIntent) .setAutoCancel(true); createNotificationChannel(getApplicationContext()); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext()); notificationManager.notify(uniqueID, notification.build()); } } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); ``` I'm sure my notification works because when I remove `if (dateFormat.equals(tomorrow))` it sends a notifciation and works perfectly. This is also a service class and not a normal activity so maybe that has something to do with it.
2018/05/23
[ "https://Stackoverflow.com/questions/50479400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9554176/" ]
Implement the `textFieldDidBeginEditing` text field delegate method and set the text field's text if it doesn't already have a value. ``` func textFieldDidBeginEditing(_ textField: UITextField) { if textField.text!.isEmpty { // set the text as needed } } ```
``` @IBOutlet weak var tF: UITextField! override func viewDidLoad() { super.viewDidLoad() tF.delegate = self } func textFieldDidEndEditing(_ textField: UITextField) { textField.text = pickOptions[row] } ```
50,479,400
I'm trying to show my users notifications through my service that checks my database when an item is at it's set date it should send a notification. My problem is that when the date comes it doesn't send a notification. ``` databaseReference = FirebaseDatabase.getInstance().getReference().child("Groups").child(mGroupUid).child("HomeFragment").child("FreezerItems"); childEventListener = databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { HashMap<String, String> value = (HashMap<String, String>) dataSnapshot.getValue(); if (value != null) { String name = value.get("Name"); String date = value.get("Date"); SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy", Locale.US); try { dateFormat = sdf.parse(date); } catch (ParseException e) { Log.wtf("FailedtoChangeDate", "Fail"); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tomorrow = cal.getTime(); if (dateFormat.equals(tomorrow)) { GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext()); if (account != null) { String firstname = account.getGivenName(); mContentTitle = "Your " + name + " is about to be expired!"; mContentText = firstname + ", make sure to cook or eat your " + name + " by " + date; } Intent openApp = new Intent(getApplicationContext(), MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 100, openApp, PendingIntent.FLAG_UPDATE_CURRENT); notification = new NotificationCompat.Builder(getApplicationContext(), "Default") .setSmallIcon(R.drawable.ic_restaurant_black_24dp) .setContentTitle(mContentTitle) .setContentText(mContentText) .setLights(Color.GREEN, 2000, 1000) .setPriority(NotificationCompat.PRIORITY_MAX) .setStyle(new NotificationCompat.BigTextStyle().bigText(mContentText)) .setContentIntent(contentIntent) .setAutoCancel(true); createNotificationChannel(getApplicationContext()); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext()); notificationManager.notify(uniqueID, notification.build()); } } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); ``` I'm sure my notification works because when I remove `if (dateFormat.equals(tomorrow))` it sends a notifciation and works perfectly. This is also a service class and not a normal activity so maybe that has something to do with it.
2018/05/23
[ "https://Stackoverflow.com/questions/50479400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9554176/" ]
I'm going to build on rmaddy's answer and add more nuances and answers to questions in the comments. Main answer lays in the first extension, the rest of the code outlines class structure and components that need to be present for everything to work. ``` class ViewController { private var selectedItem: String = "" private let pickerList = [ "First item", "Second item", "Third item" ] override func viewDidLoad() { super.viewDidLoad() pickerTextField.delegate = self //... // Layout setup //... } private let pickerTextField: UITextField = { let textField = UITextField() textField.tintColor = .clear // hides cursor return textField }() //... // UI Elements including picker //... } extension ViewController: UITextFieldDelegate { internal func textFieldDidBeginEditing(_ textField: UITextField) { if textField == pickerTextField, let textFieldText = textField.text, textFieldText.isEmpty { pickerTextField.text = pickerList.first // fills textfield before any selection is made } } } extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource { //... // PickerView delegate methods //... } ```
``` import UIKit class ActivityPersonDetail : UIViewController,UITextFieldDelegate,UIPickerViewDataSource, UIPickerViewDelegate { let salutations = ["1", "2", "3","4","5","6","7","8","9","10","11","12"] func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return salutations.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return salutations[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { pickerTF.text = salutations[row] picker.isHidden = true } func textFieldDidBeginEditing(_ textField: UITextField) { if textField == self.pickerTF { picker.isHidden = false textField.endEditing(true) } } lazy var picker: UIPickerView = { let pickerView = UIPickerView() pickerView.delegate = self pickerView.translatesAutoresizingMaskIntoConstraints = false pickerView.backgroundColor = .white pickerTF.inputView = pickerView return pickerView }() let arrowImage: UIImageView = { let image = UIImageView() image.translatesAutoresizingMaskIntoConstraints = false image.image = #imageLiteral(resourceName: "down_arrow") image.contentMode = .scaleAspectFit return image } () lazy var pickerTF: UITextField = { let tf = UITextField() tf.delegate = self tf.translatesAutoresizingMaskIntoConstraints = false tf.textColor = .black tf.font = .systemFont(ofSize: 24, weight: .medium) tf.placeholder = salutations[0] return tf }() // // MARK :- viewDidLoad ============================================================================ // private var pickerView: UIPickerView! override func viewDidLoad() { super .viewDidLoad() view.backgroundColor = .white setupNavigationBar() setupViews() setupAutoLayout() } // ================ setupNavigationBar ============= func setupNavigationBar(){ title = "" hideBackTitle() navigationController?.navigationBar.barTintColor = .navBar } func hideBackTitle() { let backbarItem = UIBarButtonItem() backbarItem.title = "" navigationItem.backBarButtonItem = backbarItem } // ================ setupViews ============= func setupViews(){ view.addSubview(pickerTF) pickerTF.addSubview(arrowImage) view.addSubview(picker) picker.isHidden = true } // ================ setupAutoLayout ============= func setupAutoLayout() { pickerTF.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 80).isActive = true pickerTF.topAnchor.constraint(equalTo: view.topAnchor, constant: 80).isActive = true pickerTF.heightAnchor.constraint(equalToConstant: 60).isActive = true pickerTF.widthAnchor.constraint(equalToConstant: 70).isActive = true arrowImage.rightAnchor.constraint(equalTo: pickerTF.rightAnchor, constant: -15).isActive = true arrowImage.topAnchor.constraint(equalTo: pickerTF.topAnchor, constant: 16).isActive = true arrowImage.widthAnchor.constraint(equalToConstant: 22).isActive = true arrowImage.heightAnchor.constraint(equalToConstant: 22).isActive = true picker.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true picker.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true picker.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true picker.heightAnchor.constraint(equalToConstant: 100).isActive = true } } ```
50,479,400
I'm trying to show my users notifications through my service that checks my database when an item is at it's set date it should send a notification. My problem is that when the date comes it doesn't send a notification. ``` databaseReference = FirebaseDatabase.getInstance().getReference().child("Groups").child(mGroupUid).child("HomeFragment").child("FreezerItems"); childEventListener = databaseReference.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { HashMap<String, String> value = (HashMap<String, String>) dataSnapshot.getValue(); if (value != null) { String name = value.get("Name"); String date = value.get("Date"); SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy", Locale.US); try { dateFormat = sdf.parse(date); } catch (ParseException e) { Log.wtf("FailedtoChangeDate", "Fail"); } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, 1); Date tomorrow = cal.getTime(); if (dateFormat.equals(tomorrow)) { GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext()); if (account != null) { String firstname = account.getGivenName(); mContentTitle = "Your " + name + " is about to be expired!"; mContentText = firstname + ", make sure to cook or eat your " + name + " by " + date; } Intent openApp = new Intent(getApplicationContext(), MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 100, openApp, PendingIntent.FLAG_UPDATE_CURRENT); notification = new NotificationCompat.Builder(getApplicationContext(), "Default") .setSmallIcon(R.drawable.ic_restaurant_black_24dp) .setContentTitle(mContentTitle) .setContentText(mContentText) .setLights(Color.GREEN, 2000, 1000) .setPriority(NotificationCompat.PRIORITY_MAX) .setStyle(new NotificationCompat.BigTextStyle().bigText(mContentText)) .setContentIntent(contentIntent) .setAutoCancel(true); createNotificationChannel(getApplicationContext()); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext()); notificationManager.notify(uniqueID, notification.build()); } } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); ``` I'm sure my notification works because when I remove `if (dateFormat.equals(tomorrow))` it sends a notifciation and works perfectly. This is also a service class and not a normal activity so maybe that has something to do with it.
2018/05/23
[ "https://Stackoverflow.com/questions/50479400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9554176/" ]
I'm going to build on rmaddy's answer and add more nuances and answers to questions in the comments. Main answer lays in the first extension, the rest of the code outlines class structure and components that need to be present for everything to work. ``` class ViewController { private var selectedItem: String = "" private let pickerList = [ "First item", "Second item", "Third item" ] override func viewDidLoad() { super.viewDidLoad() pickerTextField.delegate = self //... // Layout setup //... } private let pickerTextField: UITextField = { let textField = UITextField() textField.tintColor = .clear // hides cursor return textField }() //... // UI Elements including picker //... } extension ViewController: UITextFieldDelegate { internal func textFieldDidBeginEditing(_ textField: UITextField) { if textField == pickerTextField, let textFieldText = textField.text, textFieldText.isEmpty { pickerTextField.text = pickerList.first // fills textfield before any selection is made } } } extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource { //... // PickerView delegate methods //... } ```
``` @IBOutlet weak var tF: UITextField! override func viewDidLoad() { super.viewDidLoad() tF.delegate = self } func textFieldDidEndEditing(_ textField: UITextField) { textField.text = pickOptions[row] } ```
1,737,108
I am stuck with WIN32 ( no .NET or anything managed )
2009/11/15
[ "https://Stackoverflow.com/questions/1737108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11100/" ]
WM\_CTLCOLORSTATIC was the correct way to control the color of the group box title. However, it no longer works: If your application uses a manifest to include the version 6 comctl library, the Groupbox control no longer sends the `WM_CTLCOLORSTATIC` to its parent to get a brush. If your dialog controls look ugly, square and grey - like the windows 95 controls, then you don't have xp styles enabled and you can control the color of group boxes. But thats a terrible sacrifice to make! :P Next, most of the standard controls send `WM_CTLCOLORxxx` messages to their parent (the dialog) to control their painting. The only way to identify the controls is to look up their control IDs - which is why assigning controls a identifier that indicates that that control needs a specific color or font is a good idea. i.e. Don't use `IDC_STATIC` for controls that need red text. Set them to `IDC_DRAWRED` or some made up id. Dont use `GetDlgItem(hwndDlg,IDC_ID) == hwndCtl` to test if the `WM_CTLCOLOR` message is for the correct control: GetDlgItem will simply return the handle of the first control on the dialog with the specific Id, which means only one control will be painted. ``` case WM_CTLCOLORSTATIC: if(GetWindowLong( (HWND)lParam, GWL_ID) == IDC_RED) return MakeControlRed( (HDC)wParam ); ``` You always\* need to return a HBRUSH from a WM\_CTLCOLORxxx message - even if you really just want to 'tamper' with the HDC being passed in. If you don't return a valid brush from your dialog proc then the dialogs window procedure will think you didn't handle the message at all and pass it on to DefWindowProc - which will reset any changes to the HDC you made. Instead of creating brushes, the system has a cache of brushes on standby to draw standard ui elements: [`GetSysColorBrush`](http://msdn.microsoft.com/en-us/library/dd144927(VS.85).aspx) Of course, you DON'T always need to return an HBRUSH. IF you have the xp theme style enabled in your app, you are sometimes allowed to return null :- because xp theme dialogs have differently colored backgrounds (especially on tab controls) returning a syscolor brush would result in ugly grey boxes on a lighter background :- in those specific cases the dialog manager will allow you to return null and NOT reset your changes in the DC.
I think [WM\_CTLCOLORSTATIC notification](http://msdn.microsoft.com/en-us/library/bb787524(VS.85).aspx) might be what you're after.
1,737,108
I am stuck with WIN32 ( no .NET or anything managed )
2009/11/15
[ "https://Stackoverflow.com/questions/1737108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11100/" ]
WM\_CTLCOLORSTATIC was the correct way to control the color of the group box title. However, it no longer works: If your application uses a manifest to include the version 6 comctl library, the Groupbox control no longer sends the `WM_CTLCOLORSTATIC` to its parent to get a brush. If your dialog controls look ugly, square and grey - like the windows 95 controls, then you don't have xp styles enabled and you can control the color of group boxes. But thats a terrible sacrifice to make! :P Next, most of the standard controls send `WM_CTLCOLORxxx` messages to their parent (the dialog) to control their painting. The only way to identify the controls is to look up their control IDs - which is why assigning controls a identifier that indicates that that control needs a specific color or font is a good idea. i.e. Don't use `IDC_STATIC` for controls that need red text. Set them to `IDC_DRAWRED` or some made up id. Dont use `GetDlgItem(hwndDlg,IDC_ID) == hwndCtl` to test if the `WM_CTLCOLOR` message is for the correct control: GetDlgItem will simply return the handle of the first control on the dialog with the specific Id, which means only one control will be painted. ``` case WM_CTLCOLORSTATIC: if(GetWindowLong( (HWND)lParam, GWL_ID) == IDC_RED) return MakeControlRed( (HDC)wParam ); ``` You always\* need to return a HBRUSH from a WM\_CTLCOLORxxx message - even if you really just want to 'tamper' with the HDC being passed in. If you don't return a valid brush from your dialog proc then the dialogs window procedure will think you didn't handle the message at all and pass it on to DefWindowProc - which will reset any changes to the HDC you made. Instead of creating brushes, the system has a cache of brushes on standby to draw standard ui elements: [`GetSysColorBrush`](http://msdn.microsoft.com/en-us/library/dd144927(VS.85).aspx) Of course, you DON'T always need to return an HBRUSH. IF you have the xp theme style enabled in your app, you are sometimes allowed to return null :- because xp theme dialogs have differently colored backgrounds (especially on tab controls) returning a syscolor brush would result in ugly grey boxes on a lighter background :- in those specific cases the dialog manager will allow you to return null and NOT reset your changes in the DC.
Well you set the font using the normal way of setting control fonts. Send a WM\_SETFONT message in your window initialisation using a HFONT you created with CreateFont. e.g. ``` SendDlgItemMessage(hDlg, IDC_STATIC, WM_SETFONT, (WPARAM)hFont, TRUE); ``` Then as pointed out you need to use the WM\_CTLCOLORSTATIC notification to set the actual color. ``` case WM_CTLCOLORSTATIC: if(GetDlgItem(hDlg, IDC_STATIC) == (HWND)lParam) { HDC hDC = (HDC)wParam; SetBkColor(hDC, GetSysColor(COLOR_BTNFACE)); SetTextColor(hDC, RGB(0, 0xFF, 0)); SetBkMode(hDC, TRANSPARENT); return (INT_PTR)CreateSolidBrush(GetSysColor(COLOR_BTNFACE)); } break; ``` Although you really should only create the solid brush once and delete it when the dialog goes away because you will end up with a leak.
16,402,483
I have an iPhone 4S (running iOS 5.1) & an iPhone 5 (running iOS 6.1). I noticed that when i try to open the `cocos2D` game, on the iPhone 4S running 5.1, the game is able to open perfectly fine in landscape mode. However, when I try to open the same `cocos2D` game on my iPhone 5 running 6.1, the game is opened in portrait mode. Is there any way that I can rotate the `cocos2D` game into landscape mode in the iPhone 5 running iOS 6.1. Some extra notes: * The game is being pushed from a view controller in my test app. * Since I am pushing the game from an iOS app, I have to support portrait mode in the "Support Interface Orientations" section. (If I was just doing the game, I would just easily set the Support Interface Orientation to landscape left/landscape right) I have also tried different methods such as for iOS 6 such as: ``` -(NSUInteger)supportedInterfaceOrientations -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation -(BOOL)shouldAutorotate ``` But it has given me different results when I tried those methods. Ideally, I would like the app to be locked in the Portrait mode and game to be locked into Landscape mode. So, I'm wondering if it is possible to have an app that remains locked in the portrait mode and the game locked in landscape mode (for both iOS 5 & iOS 6) when opened? Here's a link to a sample project I was working on: <http://www.4shared.com/zip/yEAA1D_N/MyNinjaGame.html>
2013/05/06
[ "https://Stackoverflow.com/questions/16402483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/783188/" ]
I just set the orientation modes in Xcode ("Summary" tab on your target) to landscape left and right. Then for every UIViewController I added this: ``` // Autorotation iOS5 + iOS6 - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation { return UIInterfaceOrientationIsLandscape(toInterfaceOrientation); } ```
What I'm doing for landscape in my cocos2d game (on iOS 6.1): ``` //This is in the AppDelegate.m - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return UIInterfaceOrientationIsLandscape(interfaceOrientation); //change to 'return UIInterfaceOrientationIsPortrait(interfaceOrientation);' for portrait } ```
44,680,971
I added a redirection link to the reference numbers in a grid that link back to receipts. I followed the instructions given in T200 to perform the task, except I made the page that opens a popup instead of a new tab. It works for the first reference number I click, but after that it doesn't change the record. Instead the popup displays the record for the first reference number I clicked. Here is my code: ``` protected void RefNbrReceipt() { INRegister row = Receipts.Current; INReceiptEntry graph = PXGraph.CreateInstance<INReceiptEntry>(); graph.receipt.Current = graph.receipt.Search<INRegister.refNbr>(row.RefNbr); if (graph.receipt.Current != null) { throw new PXPopupRedirectException(graph, "Receipt Details"); } } ``` I checked and made sure that the row updates to the selected value (I do have SyncPosition = true on the grid) as well as after the Search that graph.receipt.Current.RefNbr = row.RefNbr. All of the objects in the code when debugging and stepping through it are set to the correct values they should be. Even though these values are showing correctly, when the popup appears, it still has the incorrect record (the first record fetched).
2017/06/21
[ "https://Stackoverflow.com/questions/44680971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7085476/" ]
Pass the index label to `loc` and the col of interest: ``` In[198]: df.loc[diff_row.idxmax(), 'City'] Out[198]: 'Dallas' ```
Taking a step back and using `numpy.ptp` (peak to peak) to do the subtraction of max less min. ``` df.set_index('City').apply(np.ptp, 1).idxmax() 'Dallas' ``` --- We can push more over to `numpy` with ``` df.City.values[np.ptp(df.set_index('City').values, 1).argmax()] 'Dallas' ``` --- **Timing** ``` %timeit df.City.values[np.ptp(df.set_index('City').values, 1).argmax()] %timeit df.set_index('City').apply(np.ptp, 1).idxmax() 1000 loops, best of 3: 399 µs per loop 1000 loops, best of 3: 1.03 ms per loop %%timeit diff_row = df.max(axis=1) - df.min(axis=1) df.loc[diff_row.idxmax(), 'City'] 1000 loops, best of 3: 1.24 ms per loop ```
4,236,395
So my question is: if we have a function f(x, y), how do we know if the curve f(x, y)=0 encloses a finite region or not. As an example, the curve $x^2+y^2-1=0$ encloses a finite region, while the curve $x^2-y^2-1=0$ doesn't.
2021/08/30
[ "https://math.stackexchange.com/questions/4236395", "https://math.stackexchange.com", "https://math.stackexchange.com/users/494803/" ]
Consider the following result from geometric analysis due to [Matthew Grayson (1987)](https://en.wikipedia.org/wiki/Mean_curvature_flow#Convergence_theorems): > > Let $g:\mathbb{S}^1\to\mathbb{R}^2$ be a smooth embedding, then the mean curvature flow with initial data $g$ eventually consists exclusively of embeddings with strictly positive curvature. > > > Mean curvature flow is the process of distorting an embedded smooth curve (or more generally embedded smooth manifold) at every point in the direction of its mean curvature vector. What this says is that if $g$ defines a curve defining a bounded region, then that curve will deform into a circle. Moreover this circle will shrink to a single point in finite time. [![enter image description here](https://i.stack.imgur.com/m7vtQ.png)](https://i.stack.imgur.com/m7vtQ.png) Image: [David Eppstein (CC0)](https://en.wikipedia.org/wiki/Curve-shortening_flow#/media/File:Convex_curve_shortening.png) This if you have a function $f:\mathbb{R}^2\to\mathbb{R}^2$ whose level set is a disjoint union of smoothly embedded curves, you can independently perform mean curvature flow on each component of $f(x,y)=0$. If each component bounds a finite region, then in finite time this will produce a set of points. Thus the set of such functions $f$ is recursively enumerable. (*Remark:* in fact it is the case that if two components of $f(x,y)=0$ are nested embeddings of $\mathbb{S}^1$, then performing mean curvature flow on both simultaneously, the two curves will not intersect at any point (until after the inner curve has shrunk to a point). This doesn't completely answer your question, but hopefully it is somewhat useful.
First of all you can't call a region of $\mathbb{R}^2$ finite unless its cardinal is finite. What you are trying to say it is that the region is bounded (that is, that there is some $D(x\_0,r)$ such that the region is inside the disck) Although this is not a very concrete question, I guess that the best I can offer you is the [Jordan Curve theorem](https://en.wikipedia.org/wiki/Jordan_curve_theorem). It states that if you have a jordan curve $C$ (a simple closed curve) in $\mathbb{R}^2$ then $\mathbb{R}^2\setminus C$ consists of exactly two connected components, one of the components is bounded (called the interior) and the other is unbounded (called the exterior). So every Jordan Curve 'Encloses a finite region of the space'. In your examples $x^2+y^2-1=0$ is a circumference, which is a jordan curve and so the theorem holds. On the other hand $x^2-y^2-1=0$ is not a jordan curve because it is not a closed curve.
6,393,438
So I hoped to figure out the code that would finish this: ``` public List<List<Integer>> create4(List<Integer> dice) { //unknown code return listOf4s; } ``` So dice would always be a List of 5 Integers, from the 5 Integers I would like to create a List every possible permutation using only 4 numbers. I hope I have made this clear enough. I have searched around but have not quite seen anything I could use. Any help would be great!
2011/06/18
[ "https://Stackoverflow.com/questions/6393438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/679413/" ]
I have not tried this out, but hopefully this helps. ``` public List<List<Integer>> createN(List<Integer> dice) { if (dice.size() == 1) { List<List<Integer>> permutations = new ArrayList<List<Integer>>(); permutations.add(dice); return permutations; } else { List<List<Integer>> permuations = new ArrayList<List<Integer>>(); for (int i=0;i<dice.size();i++) { List<Integer> remainingElementsInPermutationSet = new ArrayList<Integer>(); Integer firstElementInPermutationSet = null; for (int j=0;j<dice.size();j++) { if (i==j) { firstElementInPermutationSet = dice.get(j); } else { remainingElementsInPermutationSet.add(dice.get(j)); } } List<List<Integer>> remainderPermutations = createN(remainingElementsInPermutationSet); for (List<Integer> permutationRemainer : remainderPermutations) { List<Integer> permutation = new ArrayList<Integer>(); permutation.add(firstElementInPermutationSet); permutation.addAll(permutationRemainer); permuations.add(permutation); } } return permutations: } } ```
This is what I did using @btreat 's idea and it worked great. ``` public List<List<Integer>> create4(List<Integer> dice) { List<List<Integer>> permutations = new ArrayList<List<Integer>>(); for(int i = 0; i < dice.size(); i++) { List<Integer> includedPermutation = new ArrayList<Integer>(); for(int j = 0; j < dice.size(); j++) { if(i!=j) { includedPermutation.add(dice.get(j)); } } permutations.add(includedPermutation); } return permutations; } ```
6,393,438
So I hoped to figure out the code that would finish this: ``` public List<List<Integer>> create4(List<Integer> dice) { //unknown code return listOf4s; } ``` So dice would always be a List of 5 Integers, from the 5 Integers I would like to create a List every possible permutation using only 4 numbers. I hope I have made this clear enough. I have searched around but have not quite seen anything I could use. Any help would be great!
2011/06/18
[ "https://Stackoverflow.com/questions/6393438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/679413/" ]
I tend to like shorter code ;) ``` public List<List<Integer>> create4(List<Integer> dice) { List<List<Integer>> listOf4s = new ArrayList<List<Integer>>(); for(Integer num : dice) { List<Integer> dice2 = new ArrayList<Integer>(dice); dices2.remove(num); listOf4s.add(dices2); } return listOf4s; } ```
I have not tried this out, but hopefully this helps. ``` public List<List<Integer>> createN(List<Integer> dice) { if (dice.size() == 1) { List<List<Integer>> permutations = new ArrayList<List<Integer>>(); permutations.add(dice); return permutations; } else { List<List<Integer>> permuations = new ArrayList<List<Integer>>(); for (int i=0;i<dice.size();i++) { List<Integer> remainingElementsInPermutationSet = new ArrayList<Integer>(); Integer firstElementInPermutationSet = null; for (int j=0;j<dice.size();j++) { if (i==j) { firstElementInPermutationSet = dice.get(j); } else { remainingElementsInPermutationSet.add(dice.get(j)); } } List<List<Integer>> remainderPermutations = createN(remainingElementsInPermutationSet); for (List<Integer> permutationRemainer : remainderPermutations) { List<Integer> permutation = new ArrayList<Integer>(); permutation.add(firstElementInPermutationSet); permutation.addAll(permutationRemainer); permuations.add(permutation); } } return permutations: } } ```
6,393,438
So I hoped to figure out the code that would finish this: ``` public List<List<Integer>> create4(List<Integer> dice) { //unknown code return listOf4s; } ``` So dice would always be a List of 5 Integers, from the 5 Integers I would like to create a List every possible permutation using only 4 numbers. I hope I have made this clear enough. I have searched around but have not quite seen anything I could use. Any help would be great!
2011/06/18
[ "https://Stackoverflow.com/questions/6393438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/679413/" ]
I tend to like shorter code ;) ``` public List<List<Integer>> create4(List<Integer> dice) { List<List<Integer>> listOf4s = new ArrayList<List<Integer>>(); for(Integer num : dice) { List<Integer> dice2 = new ArrayList<Integer>(dice); dices2.remove(num); listOf4s.add(dices2); } return listOf4s; } ```
This is what I did using @btreat 's idea and it worked great. ``` public List<List<Integer>> create4(List<Integer> dice) { List<List<Integer>> permutations = new ArrayList<List<Integer>>(); for(int i = 0; i < dice.size(); i++) { List<Integer> includedPermutation = new ArrayList<Integer>(); for(int j = 0; j < dice.size(); j++) { if(i!=j) { includedPermutation.add(dice.get(j)); } } permutations.add(includedPermutation); } return permutations; } ```
301,927
So, I'm playing this video game and I came across this sentence that uses "stem from" in an alien way to me. "Their zeal is admirable, but their ideas impractical for a society that must maintain secrecy and organization **to stem** its own genocide **from** coming about." I know that "stem from" means Originate from:(TFD source below) stem from (something) To come, result, or develop from something else. My fear of the water stems from the time my brother nearly drowned me when we were playing in our cousin's pool as kids. But this usage is different. It is as if it means "to prevent". There is one definition on TFD that sort of fits but it would have to be an abbreviated version of it. (TFD def) **stem the tide or stem the flow** COMMON If you stem the tide or stem the flow of something bad which is happening to a large degree, you start to control and stop it. *The authorities seem powerless to stem the rising tide of violence. The cut in interest rates has done nothing to stem the flow of job losses.* is it possible it is that meaning?
2021/11/10
[ "https://ell.stackexchange.com/questions/301927", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/140013/" ]
Both are correct. But how? These sentences both use "unreal" grammar. The reason they're both correct will make more sense if we change them back to real sentences with the same meaning: > > (1) We **have been** able to come here because it isn't raining. > > > (2) We **were** able to come here because it wasn't raining. > > > Sentence (1) refers to the **present** situation of now being at the top of the mountain, and the **present** fact that it's not raining. Sentence (2) refers to the **past** situation of arriving at the top of the mountain with the **past** reason why. So it's two perspectives on the same thing: either (1) *now being* at the top of the mountain, or (2) *having arrived earlier*. I've highlighted the two main verbs. You'll notice they don't have the same tense, even though the original two sentences have the exact same structure\*. This is because when we shift present perfect or simple past into "unreal" grammar, *the result is the same*: *"could have" + past participle*. \*I've also replaced "couldn't" with "be able to" for grammar reasons which are unrelated to this question.
One does not say, "If it was..", but "If it were..." This is the subjunctive mood, used in stating a condition *known* to be false. [Tevye is grammatically correct](https://genius.com/Topol-if-i-were-a-rich-man-lyrics) asking, "If I were a rich man."
301,927
So, I'm playing this video game and I came across this sentence that uses "stem from" in an alien way to me. "Their zeal is admirable, but their ideas impractical for a society that must maintain secrecy and organization **to stem** its own genocide **from** coming about." I know that "stem from" means Originate from:(TFD source below) stem from (something) To come, result, or develop from something else. My fear of the water stems from the time my brother nearly drowned me when we were playing in our cousin's pool as kids. But this usage is different. It is as if it means "to prevent". There is one definition on TFD that sort of fits but it would have to be an abbreviated version of it. (TFD def) **stem the tide or stem the flow** COMMON If you stem the tide or stem the flow of something bad which is happening to a large degree, you start to control and stop it. *The authorities seem powerless to stem the rising tide of violence. The cut in interest rates has done nothing to stem the flow of job losses.* is it possible it is that meaning?
2021/11/10
[ "https://ell.stackexchange.com/questions/301927", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/140013/" ]
Both are correct, it depends on the time. You say the second one, for instance, when you tell this memory to a friend a year later because it's the third conditional. It's explained on British Council Learn English website as; ''The third conditional is used to imagine a different past. We imagine a change in a past situation and the different result of that change.''
One does not say, "If it was..", but "If it were..." This is the subjunctive mood, used in stating a condition *known* to be false. [Tevye is grammatically correct](https://genius.com/Topol-if-i-were-a-rich-man-lyrics) asking, "If I were a rich man."
301,927
So, I'm playing this video game and I came across this sentence that uses "stem from" in an alien way to me. "Their zeal is admirable, but their ideas impractical for a society that must maintain secrecy and organization **to stem** its own genocide **from** coming about." I know that "stem from" means Originate from:(TFD source below) stem from (something) To come, result, or develop from something else. My fear of the water stems from the time my brother nearly drowned me when we were playing in our cousin's pool as kids. But this usage is different. It is as if it means "to prevent". There is one definition on TFD that sort of fits but it would have to be an abbreviated version of it. (TFD def) **stem the tide or stem the flow** COMMON If you stem the tide or stem the flow of something bad which is happening to a large degree, you start to control and stop it. *The authorities seem powerless to stem the rising tide of violence. The cut in interest rates has done nothing to stem the flow of job losses.* is it possible it is that meaning?
2021/11/10
[ "https://ell.stackexchange.com/questions/301927", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/140013/" ]
The simple past ("was") is used to discuss possibilities. The past perfect ("had been") is used to discuss counterfactuals. That is, if you're uncertain about whether something happened, and want to discuss the consequences of it being the case, the simple past is appropriate. For instance, "If it was raining, they will be late". If you know something didn't happen, but want to discuss a hypothetical world in which it did happen, the past perfect is correct.
One does not say, "If it was..", but "If it were..." This is the subjunctive mood, used in stating a condition *known* to be false. [Tevye is grammatically correct](https://genius.com/Topol-if-i-were-a-rich-man-lyrics) asking, "If I were a rich man."
3,533,757
So, that's the problem. I tried factoring the quadratic equation to get something like $2x-y$ but it doesn't work. Dividing by $y^2$ won't work because the right side is $9$, not $0$. The last idea I have is to say that $2x-y=t => y=2x-t$ and replace $y$ in the quadratic equation with $2x-t$ to get a function but then, I get confused.
2020/02/04
[ "https://math.stackexchange.com/questions/3533757", "https://math.stackexchange.com", "https://math.stackexchange.com/users/502482/" ]
$$2x^2-4xy+6y^2=9$$ and let $$k=2x-y\Rightarrow y=2x-k$$ $2x^2-4x(2x-k)+6(2x-k)^2=9$ $2x^2-8x^2+4xk+6(4x^2+k^2-4xk)=9$ $-6x^2+4xk+24x^2+6k^2-24xk-9=0$ $$18x^2-20kx+6k^2-9=0$$ For real roots, Discriminant $\geq 0$ $$400k^2-4\cdot 18(6k^2-9)\geq 0$$ $$100k^2-108k^2+162\geq 0$$ $$-8k^2+162\geq 0\Rightarrow k^2-\frac{81}{4}\leq 0$$ $$-\frac{9}{2}\leq k\leq \frac{9}{2}$$
The trick is to notice that: $$4(2x-y)^2 = 9(2x^2-4xy+6y^2) - 2(x-5y)^2\leq 9(2x^2-4xy+6y^2) = 81$$ It follows that $$-\frac{9}{2} \leq 2x-y \leq \frac{9}{2}$$ The minimum is attained when $(x,y)=\left(-\dfrac{5}{2},-\dfrac{1}{2}\right)$ and the maximum when $(x,y)=\left(\dfrac{5}{2},\dfrac{1}{2}\right)$.
3,533,757
So, that's the problem. I tried factoring the quadratic equation to get something like $2x-y$ but it doesn't work. Dividing by $y^2$ won't work because the right side is $9$, not $0$. The last idea I have is to say that $2x-y=t => y=2x-t$ and replace $y$ in the quadratic equation with $2x-t$ to get a function but then, I get confused.
2020/02/04
[ "https://math.stackexchange.com/questions/3533757", "https://math.stackexchange.com", "https://math.stackexchange.com/users/502482/" ]
$$2x^2-4xy+6y^2=9$$ and let $$k=2x-y\Rightarrow y=2x-k$$ $2x^2-4x(2x-k)+6(2x-k)^2=9$ $2x^2-8x^2+4xk+6(4x^2+k^2-4xk)=9$ $-6x^2+4xk+24x^2+6k^2-24xk-9=0$ $$18x^2-20kx+6k^2-9=0$$ For real roots, Discriminant $\geq 0$ $$400k^2-4\cdot 18(6k^2-9)\geq 0$$ $$100k^2-108k^2+162\geq 0$$ $$-8k^2+162\geq 0\Rightarrow k^2-\frac{81}{4}\leq 0$$ $$-\frac{9}{2}\leq k\leq \frac{9}{2}$$
Let $2x-y=z \implies y=2x-z$, then $$f(x,y)=2x^2-4xy+6y^2-9=0 \implies z)+6(2x-z)=9 \implies 18x^2-20zx+6z^2-9=0 $$ Now for $x$ to be real $B^2\ge 4AC$ Then $$ 648-32 z^2 \ge 0 \implies -9/2 \le z \le 9/2.$$ So the are the maximum and mininumm values of $2x-y$ are $\pm 9/2$ This also means that 2x-y=z will be tangent to the curve (ellipse) $f(x,y)=0$ when $z=\pm 9/2.$
3,533,757
So, that's the problem. I tried factoring the quadratic equation to get something like $2x-y$ but it doesn't work. Dividing by $y^2$ won't work because the right side is $9$, not $0$. The last idea I have is to say that $2x-y=t => y=2x-t$ and replace $y$ in the quadratic equation with $2x-t$ to get a function but then, I get confused.
2020/02/04
[ "https://math.stackexchange.com/questions/3533757", "https://math.stackexchange.com", "https://math.stackexchange.com/users/502482/" ]
$$2x^2-4xy+6y^2=9$$ and let $$k=2x-y\Rightarrow y=2x-k$$ $2x^2-4x(2x-k)+6(2x-k)^2=9$ $2x^2-8x^2+4xk+6(4x^2+k^2-4xk)=9$ $-6x^2+4xk+24x^2+6k^2-24xk-9=0$ $$18x^2-20kx+6k^2-9=0$$ For real roots, Discriminant $\geq 0$ $$400k^2-4\cdot 18(6k^2-9)\geq 0$$ $$100k^2-108k^2+162\geq 0$$ $$-8k^2+162\geq 0\Rightarrow k^2-\frac{81}{4}\leq 0$$ $$-\frac{9}{2}\leq k\leq \frac{9}{2}$$
By C-S: $$3=\sqrt{2x^2-4xy+6y^2}=\frac{2}{3}\sqrt{\left(2(x-y)^2+4y^2\right)\left(2+\frac{1}{4}\right)}\geq$$ $$\geq\frac{2}{3}\sqrt{(2(x-y)+y)^2}=\frac{2}{3}|2x-y|,$$ which gives $$-\frac{9}{2}\leq2x-y\leq\frac{9}{2}.$$ The equality occurs for $$\left(\sqrt2(x-y),y\right)||\left(\sqrt2,\frac{1}{2}\right),$$ which with the condition gives $$(x,y)=\left(\frac{5}{2},\frac{1}{2}\right)$$ for the right inequality and $$(x,y)=\left(-\frac{5}{2},-\frac{1}{2}\right)$$ for the left inequality, which says that we got a maximal and the minimal value.
20,184,852
I am supposed to create a file (done, it's called "factoriales.txt") and print in it the value of 10! (which is 3628800), the thing is, I can't seem to write the value into a file. I already know how to write text, but this wont work.... here's what I have so far. Please help! ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("The file has been created."); int r = 1; for (int i = 1; i<=10; i--) { r = r * i; } FileWriter write = new FileWriter(fac); write.write(""+r); write.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` --- Here's how I solved it thanks to everybody in here, I hope you like this simple method: ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("\n----------------------------------"); System.out.println("The file has been created."); System.out.println("------------------------------------"); int r = 1; FileWriter wr = new FileWriter(fac); for (int i = 1; i<=10; i++) { r = r * i; wr.write(r+System.getProperty( "line.separator" )); } wr.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20184852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029988/" ]
the reason any way is that ``` for (int i = 1; i<=10; i--) ``` runs to infinity since 1 cannot be reduced to 10 it should be ``` for (int i = 1; i<=10; i++) ``` and change data type to long as well
Change the for-loop: From ``` for (int i = 1; i<=10; i--) ``` to ``` for (int i = 1; i<=10; i++) ``` and you will get the right result. have a try and go ahead.
20,184,852
I am supposed to create a file (done, it's called "factoriales.txt") and print in it the value of 10! (which is 3628800), the thing is, I can't seem to write the value into a file. I already know how to write text, but this wont work.... here's what I have so far. Please help! ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("The file has been created."); int r = 1; for (int i = 1; i<=10; i--) { r = r * i; } FileWriter write = new FileWriter(fac); write.write(""+r); write.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` --- Here's how I solved it thanks to everybody in here, I hope you like this simple method: ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("\n----------------------------------"); System.out.println("The file has been created."); System.out.println("------------------------------------"); int r = 1; FileWriter wr = new FileWriter(fac); for (int i = 1; i<=10; i++) { r = r * i; wr.write(r+System.getProperty( "line.separator" )); } wr.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20184852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029988/" ]
the reason any way is that ``` for (int i = 1; i<=10; i--) ``` runs to infinity since 1 cannot be reduced to 10 it should be ``` for (int i = 1; i<=10; i++) ``` and change data type to long as well
If you want to save a number in text format use PrintWriter, it has methods for writing numbers.
20,184,852
I am supposed to create a file (done, it's called "factoriales.txt") and print in it the value of 10! (which is 3628800), the thing is, I can't seem to write the value into a file. I already know how to write text, but this wont work.... here's what I have so far. Please help! ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("The file has been created."); int r = 1; for (int i = 1; i<=10; i--) { r = r * i; } FileWriter write = new FileWriter(fac); write.write(""+r); write.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` --- Here's how I solved it thanks to everybody in here, I hope you like this simple method: ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("\n----------------------------------"); System.out.println("The file has been created."); System.out.println("------------------------------------"); int r = 1; FileWriter wr = new FileWriter(fac); for (int i = 1; i<=10; i++) { r = r * i; wr.write(r+System.getProperty( "line.separator" )); } wr.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20184852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029988/" ]
the reason any way is that ``` for (int i = 1; i<=10; i--) ``` runs to infinity since 1 cannot be reduced to 10 it should be ``` for (int i = 1; i<=10; i++) ``` and change data type to long as well
``` public static void main(String[] args) { try { File fac = new File("c:\\bea\\factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("The file has been created."); int r = 1; FileWriter write = new FileWriter(fac); write.write(""); for (int i = 1; i<=10; i++) { r = r * i; write.append(r + "\n"); } write.flush(); write.close(); } catch (IOException e) { e.printStackTrace(); } } ``` Output: ``` 1 2 6 24 120 720 5040 40320 362880 3628800 ```
20,184,852
I am supposed to create a file (done, it's called "factoriales.txt") and print in it the value of 10! (which is 3628800), the thing is, I can't seem to write the value into a file. I already know how to write text, but this wont work.... here's what I have so far. Please help! ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("The file has been created."); int r = 1; for (int i = 1; i<=10; i--) { r = r * i; } FileWriter write = new FileWriter(fac); write.write(""+r); write.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` --- Here's how I solved it thanks to everybody in here, I hope you like this simple method: ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("\n----------------------------------"); System.out.println("The file has been created."); System.out.println("------------------------------------"); int r = 1; FileWriter wr = new FileWriter(fac); for (int i = 1; i<=10; i++) { r = r * i; wr.write(r+System.getProperty( "line.separator" )); } wr.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20184852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029988/" ]
Change the for-loop: From ``` for (int i = 1; i<=10; i--) ``` to ``` for (int i = 1; i<=10; i++) ``` and you will get the right result. have a try and go ahead.
If you want to save a number in text format use PrintWriter, it has methods for writing numbers.
20,184,852
I am supposed to create a file (done, it's called "factoriales.txt") and print in it the value of 10! (which is 3628800), the thing is, I can't seem to write the value into a file. I already know how to write text, but this wont work.... here's what I have so far. Please help! ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("The file has been created."); int r = 1; for (int i = 1; i<=10; i--) { r = r * i; } FileWriter write = new FileWriter(fac); write.write(""+r); write.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` --- Here's how I solved it thanks to everybody in here, I hope you like this simple method: ``` import java.io.File; import java.io.FileWriter; import java.io.IOException; public class D09T9e2 { public static void main(String[] args) { try { File fac = new File("factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("\n----------------------------------"); System.out.println("The file has been created."); System.out.println("------------------------------------"); int r = 1; FileWriter wr = new FileWriter(fac); for (int i = 1; i<=10; i++) { r = r * i; wr.write(r+System.getProperty( "line.separator" )); } wr.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20184852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3029988/" ]
``` public static void main(String[] args) { try { File fac = new File("c:\\bea\\factoriales.txt"); if (!fac.exists()) { fac.createNewFile(); } System.out.println("The file has been created."); int r = 1; FileWriter write = new FileWriter(fac); write.write(""); for (int i = 1; i<=10; i++) { r = r * i; write.append(r + "\n"); } write.flush(); write.close(); } catch (IOException e) { e.printStackTrace(); } } ``` Output: ``` 1 2 6 24 120 720 5040 40320 362880 3628800 ```
If you want to save a number in text format use PrintWriter, it has methods for writing numbers.
16,469,619
I'm new to WCF. I've created a basic service and engineer tested it with the debugger and WCFTestClient. I've never written my own WCF client. Now I need to build unit tests for the service. My classes: ``` IXService CXService CServiceLauncher ``` (Yes, I know the C prefix does not meet current standards, but it is required by my client's standards.) My service functionality can be tested directly against `XService`, but I need to test `CServiceLauncher` as well. All I want to do is connect to a URI and discover if there is a service running there and what methods it offers. Other questions I read: * [AddressAccessDeniedException "Your process does not have access rights to this namespace" when Unit testing WCF service](https://stackoverflow.com/questions/14563557/unit-test-wcf-service) - starts service host in unit test * [WCF Unit Test](https://stackoverflow.com/questions/152338/wcf-unit-test) - recommends hosting the service in unit test, makes a vague reference to connecting to service via HTTP * [WCF MSMQ Unit testing](https://stackoverflow.com/questions/2691066/wcf-msmq-unit-testing) - references MSMQ, which is more detailed than I need * [Unit test WCF method](https://stackoverflow.com/questions/7929882/unit-test-wcf-method) - I never knew I could auto generate tests, but the system isn't smart enough to know what to assert. Test outline: ``` public void StartUiTest() { Uri baseAddress = new Uri("http://localhost:8080/MyService"); string soapAddress = "soap"; IUserInterface target = new CServiceLauncher(baseAddress, soapAddress); try { Assert.AreEqual(true, target.StartUi()); /// @todo Assert.IsTrue(serviceIsRunning); /// @todo Assert.IsTrue(service.ExposedMethods.Count() > 4); Assert.Inconclusive("This tells us nothing about the service"); } finally { target.StopUi(); } } ```
2013/05/09
[ "https://Stackoverflow.com/questions/16469619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091951/" ]
I just needed to build a simple client. Reference: <http://webbeyond.blogspot.com/2012/11/wcf-simple-wcf-client-example.html> 1. Add Service Reference to test project 2. Add to test file: `using System.ServiceModel;` `using MyTests.ServiceReferenceNamespace;` Code inside try is now: ``` Assert.AreEqual(true, target.StartUi()); XServiceClient client = new XServiceClient(); client.GetSessionID(); Assert.AreEqual(CommunicationState.Opened, client.State, "Wrong communication state after first call"); ```
It's not a real answer so please take it easy. I have been trying to do similar things and what I have learnt that integration testing is difficult. It is difficult because there are many hidden tasks that you need to do, such as: * Make sure you can run the tests regularly * Make sure integration tests can run on the test environment * Maintain different config files, as your environment will be different from the test one * Configure the thing that would automate running of integration tests (CI) * Pray there will be no changes to the paths, test environment, config, hosting platforms etc * Fight security permissions, as usually test thing is not able to host WCF services without admin permissions * Maintain your test harness To me, this was huge headache and little gain. Don't get me wrong, integration testing is a positive thing, it just requires *a lot* of time to develop and support. What have I learnt? Is that do not bother with integration testing of WCF services. Instead I write a lot of unit-tests, to test the contract, state and behaviour. By covering those, I can become sure in a quality of software. And I fight integration of WCF during deployment. This is usually a single battle to configure environment or VM and then next time, deployment goes nice and smooth in an (semi-)automated manner. Most people would also automate deployment with [Chef](http://www.opscode.com/chef/) and alike, those tools can fully configure environment and deploy WCF service.
12,409,813
Ideally I want to be able to write something like: ``` function a( b ) { b.defaultVal( 1 ); return b; } ``` The intention of this is that if `b` is any defined value, `b` will remain as that value; but if `b` is undefined, then `b` will be set to the value specified in the parameter of `defaultVal()`, in this case `1`. Is this even possible? Ive been toying about with something like this: ``` String.prototype.defaultVal=function(valOnUndefined){ if(typeof this==='undefined'){ return valOnUndefined; }else{ return this; } }; ``` But I'm not having any success applying this kind of logic to *any* variable, particularly undefined variables. Does anyone have any thoughts on this? Can it be done? Or am I barking up the wrong tree?
2012/09/13
[ "https://Stackoverflow.com/questions/12409813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037617/" ]
Well the most important thing to learn here is if a variable is `undefined` you, by default, do not have any methods available on it. So you need to use a method that can operate on the variable, but is not a member/method *of* that variable. Try something like: ``` function defaultValue(myVar, defaultVal){ if(typeof myVar === "undefined") myVar = defaultVal; return myVar; } ``` What you're trying to do is the equivalent of this: ``` undefined.prototype.defaultValue = function(val) { } ``` ...Which for obvious reasons, doesn't work.
While the two answers already provided are correct, the language has progressed since then. If your target [browsers support](https://kangax.github.io/compat-table/es6/) it, you can use *default function parameters* like this: ```js function greetMe(greeting = "Hello", name = "World") { console.log(greeting + ", " + name + "!"); } greetMe(); // prints "Hello, World!" greetMe("Howdy", "Tiger"); // prints "Howdy, Tiger!" ``` [Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) are the MDN docs on default function parameters.
12,409,813
Ideally I want to be able to write something like: ``` function a( b ) { b.defaultVal( 1 ); return b; } ``` The intention of this is that if `b` is any defined value, `b` will remain as that value; but if `b` is undefined, then `b` will be set to the value specified in the parameter of `defaultVal()`, in this case `1`. Is this even possible? Ive been toying about with something like this: ``` String.prototype.defaultVal=function(valOnUndefined){ if(typeof this==='undefined'){ return valOnUndefined; }else{ return this; } }; ``` But I'm not having any success applying this kind of logic to *any* variable, particularly undefined variables. Does anyone have any thoughts on this? Can it be done? Or am I barking up the wrong tree?
2012/09/13
[ "https://Stackoverflow.com/questions/12409813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037617/" ]
Why not use the default operator: ``` function someF(b) { b = b || 1; return b; } ``` Job done! Here's [more info](http://javascript.crockford.com/style2.html) about how it works. Just as a side-note: your prototype won't work, because you're augmenting the `String` prototype, whereas if your variable is undefined, the `String` prototype doesn't exactly apply. To be absolutely, super-duper-sure that you're only switching to the default value, when `b` really is undefined, you could do this: ``` var someF = (function(undefined)//get the real undefined value { return function(b) { b = b === undefined ? 1 : b; return b; } })(); // by not passing any arguments ```
While the two answers already provided are correct, the language has progressed since then. If your target [browsers support](https://kangax.github.io/compat-table/es6/) it, you can use *default function parameters* like this: ```js function greetMe(greeting = "Hello", name = "World") { console.log(greeting + ", " + name + "!"); } greetMe(); // prints "Hello, World!" greetMe("Howdy", "Tiger"); // prints "Howdy, Tiger!" ``` [Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) are the MDN docs on default function parameters.
302,472
where i put file of programatically create product ``` <?php use Magento\Framework\App\Bootstrap; include('app/bootstrap.php'); $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $_product = $objectManager->create('Magento\Catalog\Model\Product'); $_product->setName('Test Product'); $_product->setTypeId('simple'); $_product->setAttributeSetId(4); $_product->setSku('test-SKU'); $_product->setWebsiteIds(array(1)); $_product->setVisibility(4); $_product->setPrice(array(1)); $_product->setImage('/testimg/test.jpg'); $_product->setSmallImage('/testimg/test.jpg'); $_product->setThumbnail('/testimg/test.jpg'); $_product->setStockData(array( 'use_config_manage_stock' => 0, //'Use config settings' checkbox 'manage_stock' => 1, //manage stock 'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart 'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart 'is_in_stock' => 1, //Stock Availability 'qty' => 100 //qty ) ); $_product->save(); ?> ```
2020/01/29
[ "https://magento.stackexchange.com/questions/302472", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/85815/" ]
***programmatically create product file put in Magento root directory and run*** example in localhost go to ***var/www/html/magentosmpl233/*** and put your file and run ``` example http://127.0.0.1/magesmpl233/createproduct.php ```
**Method - 1:** Put your file in a Magento root directory and run your url in browser. Example: `www.yourdomain.com/your_file_name.php` *OR* **Method - 2:** Create your custom directory on root and keep your custom file in that directory and run url with your custom directory path in browser. Example: `www.yourdomain.com/your_directorty_name/your_file_name.php`
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
You can install the free 1 month trail version of [Adobe Flash CS4 Professional](https://www.adobe.com/products/flash/), which you can use to edit and create free flash movies. If all you need to do is a one-time editing of the flash (.fla) file, you can get away using just the trial version.
there are no legally free programs that allows full capable editing of Flash source files (.fla). Only Adobe Flash (not Player!) can do it. I suggest you stop wasting time hoping a free program like this comes along, and start using that time saved to work and buy a copy eventually.
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
Check [projects on osflash](http://www.osflash.org/projects). All of these are free. There are IDEs, command line tools, editors, game servers, etc ...and check [tutorials](http://osflash.org/tutorials).
there are no legally free programs that allows full capable editing of Flash source files (.fla). Only Adobe Flash (not Player!) can do it. I suggest you stop wasting time hoping a free program like this comes along, and start using that time saved to work and buy a copy eventually.
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
You can download the 30-day trial version of [Adobe Flash Professional](http://www.adobe.com/products/flash/). I don't know of any free alternative that works as well.
there are no legally free programs that allows full capable editing of Flash source files (.fla). Only Adobe Flash (not Player!) can do it. I suggest you stop wasting time hoping a free program like this comes along, and start using that time saved to work and buy a copy eventually.
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
You can install the free 1 month trail version of [Adobe Flash CS4 Professional](https://www.adobe.com/products/flash/), which you can use to edit and create free flash movies. If all you need to do is a one-time editing of the flash (.fla) file, you can get away using just the trial version.
Check [projects on osflash](http://www.osflash.org/projects). All of these are free. There are IDEs, command line tools, editors, game servers, etc ...and check [tutorials](http://osflash.org/tutorials).
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
You can install the free 1 month trail version of [Adobe Flash CS4 Professional](https://www.adobe.com/products/flash/), which you can use to edit and create free flash movies. If all you need to do is a one-time editing of the flash (.fla) file, you can get away using just the trial version.
You can download the 30-day trial version of [Adobe Flash Professional](http://www.adobe.com/products/flash/). I don't know of any free alternative that works as well.
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
You can install the free 1 month trail version of [Adobe Flash CS4 Professional](https://www.adobe.com/products/flash/), which you can use to edit and create free flash movies. If all you need to do is a one-time editing of the flash (.fla) file, you can get away using just the trial version.
From the command-line, you may try [SWFTools](http://www.swftools.org/) - SWF manipulation and generation utilities You can install SWFTools distribution (which has also a command line program), and use [SWFExtract](http://www.swftools.org/swfextract.html), that can decompile flash files. On OSX, install via: `brew install swftools`.
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
Check [projects on osflash](http://www.osflash.org/projects). All of these are free. There are IDEs, command line tools, editors, game servers, etc ...and check [tutorials](http://osflash.org/tutorials).
From the command-line, you may try [SWFTools](http://www.swftools.org/) - SWF manipulation and generation utilities You can install SWFTools distribution (which has also a command line program), and use [SWFExtract](http://www.swftools.org/swfextract.html), that can decompile flash files. On OSX, install via: `brew install swftools`.
41,786
I have Flash files that I would like to make edits on but I don't know how or with what. Is there some software that can edit a Flash (.fla) file? (Ideally something free.)
2009/09/15
[ "https://superuser.com/questions/41786", "https://superuser.com", "https://superuser.com/users/10319/" ]
You can download the 30-day trial version of [Adobe Flash Professional](http://www.adobe.com/products/flash/). I don't know of any free alternative that works as well.
From the command-line, you may try [SWFTools](http://www.swftools.org/) - SWF manipulation and generation utilities You can install SWFTools distribution (which has also a command line program), and use [SWFExtract](http://www.swftools.org/swfextract.html), that can decompile flash files. On OSX, install via: `brew install swftools`.
27,737,444
I have a table `#TrackPlayedInformation` upon which I am looping. Sample data of `#TrackPlayedInformation` is as follows: ``` ProfileTrackTimeId JukeBoxTrackId ProfileId EndTime SessionId StartTime 14 52 33 2014-08-16 05:47:19.410 23424234 2014-08-16 05:45:19.410 15 51 33 2014-11-16 05:47:19.410 23424234 2014-08-16 05:45:19.410 ``` I am looping through `#TrackPlayedInformation` and splits the time interval between start time and end time on each minute. New time is inserted on a physical table `TempGraph` Structure of TempGraph is ``` TempGraphId AirTime AirCount 170390 2014-08-16 05:46:19.410 0 170391 2014-08-16 05:47:19.410 0 ``` While inserting to `TempGraph` if not exists is checked, if exists it updates aircount incremented by 1 else inserted as new entry. The query execution takes about 20 minutes to complete id the date interval is about 3 month. Is there any faster way to achieve the result? My workout query is as follows: ``` USE [SocialMob] GO /****** Object: StoredProcedure [dbo].[pDeleteTempGraph] Script Date: 01/02/2015 09:00:32 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[pDeleteTempGraph] AS BEGIN print('start') declare @UserId int declare @ProfileTrackTimeId int set @UserId=1048 drop table #TrackPlayedInformation delete from TempGraph declare @loopCount int declare @StartTime datetime declare @LastDate datetime declare @tempCount int declare @EndTime datetime declare @SaveTime datetime declare @checkDate datetime declare @countCheck int --querying input-- --drop table #TrackPlayedInformation --declare @UserId int --set @UserId=33 SELECT ProfileTrackTimeId,ProfileTrackTime.JukeBoxTrackId,ProfileId,EndTime,SessionId,StartTime into #TrackPlayedInformation FROM ProfileTrackTime LEFT JOIN (SELECT JukeBoxTrackId FROM JukeBoxTrack INNER JOIN Album ON JukeBoxTrack.AlbumId=Album.AlbumId WHERE Album.UserId=@UserId) as AllTrackId ON ProfileTrackTime.JukeBoxTrackId=AllTrackId.JukeBoxTrackId set @loopCount=0 declare @count as int select @count=COUNT(ProfileTrackTimeId) from #TrackPlayedInformation set @LastDate=GETDATE()--storing current datetime print('looping starts') while @loopCount<@count begin select @StartTime=StartTime from #TrackPlayedInformation select @EndTime=EndTime from #TrackPlayedInformation select @ProfileTrackTimeId=ProfileTrackTimeId from #TrackPlayedInformation --select @checkDate=AirTime from TempGraph while @StartTime<=@EndTime begin set @StartTime=DATEADD(minute,1,@StartTime) --checking for duplication --SELECT @countCheck= count(TempGraphId) FROM TempGraph WHERE AirTime=@StartTime --select @countCheck --if (@countCheck<1) if not exists(select top 1 TempGraphId from TempGraph where AirTime=@StartTime) begin --print('inserting') insert TempGraph (AirTime,AirCount) values(@StartTime,0) end else begin --print('updating') update TempGraph set AirCount=AirCount+1 where AirTime=@StartTime end set @LastDate=@StartTime end set @LastDate=DATEADD(MINUTE,1,@LastDate); --deleting row from #TrackPlayedInformation --print('deleting') delete from #TrackPlayedInformation where ProfileTrackTimeId=@ProfileTrackTimeId set @loopCount=@loopCount+1 --incrementing looping condition end begin insert TempGraph (AirTime,AirCount) values(@LastDate,0) end begin declare @nowdate datetime set @nowdate=GETDATE() insert TempGraph (AirTime,AirCount) values(@nowdate,0) end select * from TempGraph; delete from TempGraph; END ``` I am trying to split a time interval by minute for eg- consider date 2014 01 01 5.40 as start time and 2014 01 01 5.50 as end time.i need to entry in TempGraph as 2014 01 01 5.41, 2014 01 01 5.42, 2014 01 01 5.43 .....upto 2014 01 01 5.50
2015/01/02
[ "https://Stackoverflow.com/questions/27737444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3079776/" ]
It is not entirely clear to me what you are trying to accomplish. Nevertheless, loops in SQL should be avoided if possible. You might consider an `UPDATE` statement similar to: ``` UPDATE TempGraph SET AirCount = AirCount + 1 WHERE AirTime BETWEEN @StartTime AND @EndTime ``` followed by something that inserts records for the "missing" times. Without more information on the purpose of this code, it is difficult to provide more help.
To create sequence between startTime and EndTime you can use pattern with the [nodes()](http://msdn.microsoft.com/en-us/library/ms188282.aspx) method. To perform insert and update operations you can use [MERGE](http://msdn.microsoft.com/en-us/library/bb510625.aspx) statement. The following example show you how to do this. ``` ALTER PROC [dbo].[pDeleteTempGraph] AS BEGIN IF OBJECT_ID('tempdb..#seq') IS NOT NULL DROP TABLE #seq CREATE TABLE #seq(AirTime datetime, AirCount int) ;WITH cte AS ( SELECT *, CAST(REPLICATE(CAST('<M></M>' AS varchar(MAX)),ISNULL(DATEDIFF(MINUTE, StartTime, EndTime), 1)) AS xml) AS xmlCol FROM #TrackPlayedInformation t1 ),cte2 AS ( SELECT DATEADD(MINUTE, ROW_NUMBER() OVER(PARTITION BY profileTrackTimeId ORDER BY StartTime), StartTime) AS AirTime FROM cte CROSS APPLY xmlCol.nodes ('/M') AS Split(M) ) INSERT #seq SELECT AirTime, COUNT(*) AS AirCount FROM cte2 GROUP BY AirTime MERGE TempGraph AS TARGET USING ( SELECT AirTime, AirCount FROM #seq ) AS SOURCE ON TARGET.AirTime = SOURCE.AirTime WHEN MATCHED THEN UPDATE SET AirCount = TARGET.AirCount + SOURCE.AirCount WHEN NOT MATCHED BY TARGET THEN INSERT(AirTime, AirCount) VALUES(SOURCE.AirTime, SOURCE.AirCount); SELECT * FROM TempGraph DELETE FROM TempGraph END ``` But maybe MERGE statement is excessive in your particular case and will be enough the table #seq. Anyway if you have an additional UPSERT logic it will be good idea to do it with MERGE statement.
27,737,444
I have a table `#TrackPlayedInformation` upon which I am looping. Sample data of `#TrackPlayedInformation` is as follows: ``` ProfileTrackTimeId JukeBoxTrackId ProfileId EndTime SessionId StartTime 14 52 33 2014-08-16 05:47:19.410 23424234 2014-08-16 05:45:19.410 15 51 33 2014-11-16 05:47:19.410 23424234 2014-08-16 05:45:19.410 ``` I am looping through `#TrackPlayedInformation` and splits the time interval between start time and end time on each minute. New time is inserted on a physical table `TempGraph` Structure of TempGraph is ``` TempGraphId AirTime AirCount 170390 2014-08-16 05:46:19.410 0 170391 2014-08-16 05:47:19.410 0 ``` While inserting to `TempGraph` if not exists is checked, if exists it updates aircount incremented by 1 else inserted as new entry. The query execution takes about 20 minutes to complete id the date interval is about 3 month. Is there any faster way to achieve the result? My workout query is as follows: ``` USE [SocialMob] GO /****** Object: StoredProcedure [dbo].[pDeleteTempGraph] Script Date: 01/02/2015 09:00:32 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[pDeleteTempGraph] AS BEGIN print('start') declare @UserId int declare @ProfileTrackTimeId int set @UserId=1048 drop table #TrackPlayedInformation delete from TempGraph declare @loopCount int declare @StartTime datetime declare @LastDate datetime declare @tempCount int declare @EndTime datetime declare @SaveTime datetime declare @checkDate datetime declare @countCheck int --querying input-- --drop table #TrackPlayedInformation --declare @UserId int --set @UserId=33 SELECT ProfileTrackTimeId,ProfileTrackTime.JukeBoxTrackId,ProfileId,EndTime,SessionId,StartTime into #TrackPlayedInformation FROM ProfileTrackTime LEFT JOIN (SELECT JukeBoxTrackId FROM JukeBoxTrack INNER JOIN Album ON JukeBoxTrack.AlbumId=Album.AlbumId WHERE Album.UserId=@UserId) as AllTrackId ON ProfileTrackTime.JukeBoxTrackId=AllTrackId.JukeBoxTrackId set @loopCount=0 declare @count as int select @count=COUNT(ProfileTrackTimeId) from #TrackPlayedInformation set @LastDate=GETDATE()--storing current datetime print('looping starts') while @loopCount<@count begin select @StartTime=StartTime from #TrackPlayedInformation select @EndTime=EndTime from #TrackPlayedInformation select @ProfileTrackTimeId=ProfileTrackTimeId from #TrackPlayedInformation --select @checkDate=AirTime from TempGraph while @StartTime<=@EndTime begin set @StartTime=DATEADD(minute,1,@StartTime) --checking for duplication --SELECT @countCheck= count(TempGraphId) FROM TempGraph WHERE AirTime=@StartTime --select @countCheck --if (@countCheck<1) if not exists(select top 1 TempGraphId from TempGraph where AirTime=@StartTime) begin --print('inserting') insert TempGraph (AirTime,AirCount) values(@StartTime,0) end else begin --print('updating') update TempGraph set AirCount=AirCount+1 where AirTime=@StartTime end set @LastDate=@StartTime end set @LastDate=DATEADD(MINUTE,1,@LastDate); --deleting row from #TrackPlayedInformation --print('deleting') delete from #TrackPlayedInformation where ProfileTrackTimeId=@ProfileTrackTimeId set @loopCount=@loopCount+1 --incrementing looping condition end begin insert TempGraph (AirTime,AirCount) values(@LastDate,0) end begin declare @nowdate datetime set @nowdate=GETDATE() insert TempGraph (AirTime,AirCount) values(@nowdate,0) end select * from TempGraph; delete from TempGraph; END ``` I am trying to split a time interval by minute for eg- consider date 2014 01 01 5.40 as start time and 2014 01 01 5.50 as end time.i need to entry in TempGraph as 2014 01 01 5.41, 2014 01 01 5.42, 2014 01 01 5.43 .....upto 2014 01 01 5.50
2015/01/02
[ "https://Stackoverflow.com/questions/27737444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3079776/" ]
I don't actually understand what you are trying to do. The following may help you ``` SELECT * INTO #TEMP FROM ( SELECT 14 ProfileTrackTimeId,'2014-08-16 05:47:19.410' StartTime, '2014-08-16 05:50:19.410' EndTime UNION ALL SELECT 14 ProfileTrackTimeId,'2014-08-16 10:20:19.410' StartTime, '2014-08-16 10:23:19.410' EndTime UNION ALL SELECT 20 ProfileTrackTimeId,'2014-08-17 08:10:19.410' StartTime, '2014-08-17 08:12:19.410' EndTime UNION ALL SELECT 20 ProfileTrackTimeId,'2014-08-18 13:59:19.410' StartTime, '2014-08-18 14:02:19.410' EndTime )TAB ``` Now you will get every date with minute between `starttime` and `endtime` for every `ProfileTrackTimeId` ``` ;WITH CTE AS ( SELECT ProfileTrackTimeId,CAST(StartTime AS DATETIME) FDATES, CAST(EndTime AS DATETIME) TDATES FROM #TEMP UNION ALL SELECT T.ProfileTrackTimeId,DATEADD(MINUTE,1,FDATES),TDATES FROM #TEMP T JOIN CTE ON CTE.ProfileTrackTimeId = T.ProfileTrackTimeId WHERE FDATES < TDATES ) SELECT DISTINCT ProfileTrackTimeId,FDATES FROM CTE ORDER BY ProfileTrackTimeId,FDATES OPTION (MaxRecursion 0) ``` Please let me know for any change.
To create sequence between startTime and EndTime you can use pattern with the [nodes()](http://msdn.microsoft.com/en-us/library/ms188282.aspx) method. To perform insert and update operations you can use [MERGE](http://msdn.microsoft.com/en-us/library/bb510625.aspx) statement. The following example show you how to do this. ``` ALTER PROC [dbo].[pDeleteTempGraph] AS BEGIN IF OBJECT_ID('tempdb..#seq') IS NOT NULL DROP TABLE #seq CREATE TABLE #seq(AirTime datetime, AirCount int) ;WITH cte AS ( SELECT *, CAST(REPLICATE(CAST('<M></M>' AS varchar(MAX)),ISNULL(DATEDIFF(MINUTE, StartTime, EndTime), 1)) AS xml) AS xmlCol FROM #TrackPlayedInformation t1 ),cte2 AS ( SELECT DATEADD(MINUTE, ROW_NUMBER() OVER(PARTITION BY profileTrackTimeId ORDER BY StartTime), StartTime) AS AirTime FROM cte CROSS APPLY xmlCol.nodes ('/M') AS Split(M) ) INSERT #seq SELECT AirTime, COUNT(*) AS AirCount FROM cte2 GROUP BY AirTime MERGE TempGraph AS TARGET USING ( SELECT AirTime, AirCount FROM #seq ) AS SOURCE ON TARGET.AirTime = SOURCE.AirTime WHEN MATCHED THEN UPDATE SET AirCount = TARGET.AirCount + SOURCE.AirCount WHEN NOT MATCHED BY TARGET THEN INSERT(AirTime, AirCount) VALUES(SOURCE.AirTime, SOURCE.AirCount); SELECT * FROM TempGraph DELETE FROM TempGraph END ``` But maybe MERGE statement is excessive in your particular case and will be enough the table #seq. Anyway if you have an additional UPSERT logic it will be good idea to do it with MERGE statement.
1,803,165
I need to calculate the volume of solid enclosed by the surface $(x^2+y^2+z^2)^2=x$, using only spherical coordinates. My attempt: by changing coordinates to spherical: $x=r\sin\phi\cos\theta~,~y=r\sin\phi\sin\theta~,~z=r\cos\phi$ we obtain the Jacobian $J=r^2\sin\phi$. When $\phi$ and $\theta$ are fixed, $r$ varies from $0$ to $\sqrt[3]{\sin\phi\cos\theta}$ (because $r^4=r\sin\phi\cos\theta$). Keeping $\theta$ fixed, we let $\phi$ vary from $0$ to $\pi$. Thus the volume equals: $$V=\int\limits\_{0}^{\pi}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\phi\cos\theta}}r^2\sin\phi ~dr ~d\phi ~d\theta=0$$ Which is obviously wrong. What am I doing wrong?
2016/05/28
[ "https://math.stackexchange.com/questions/1803165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342907/" ]
It's a solid of revolution. Let $h=\sqrt{y^{2}+z^{2}}$, then $(x^{2}+h^{2})^{2}=x$. $\therefore \; h^{2}=\sqrt{x}-x^{2} \:$ where $\, 0\leq x \leq 1$. \begin{align\*} V &= \int\_{0}^{1} \pi h^{2} dx \\ &= \pi \int\_{0}^{1} \left( \sqrt{x}-x^{2} \right) dx \\ &= \pi \left[ \frac{2}{3} x^{\frac{3}{2}}- \frac{1}{3} x^{3} \right]\_{0}^{1} \\ &= \frac{\pi}{3} \end{align\*}
Byron Schmuland's suggestion is the easiest way to find this volume, but using spherical coordinates and symmetry to find the volume bounded by $(x^2+y^2+z^2)^2=z\;\;$ gives $\;\;\displaystyle V=\int\_0^{2\pi}\int\_0^{\frac{\pi}{2}}\int\_0^{\sqrt[3]{\cos\phi}}\rho^2\sin\phi\;d\rho d\phi d\theta=\frac{\pi}{3}$.
1,803,165
I need to calculate the volume of solid enclosed by the surface $(x^2+y^2+z^2)^2=x$, using only spherical coordinates. My attempt: by changing coordinates to spherical: $x=r\sin\phi\cos\theta~,~y=r\sin\phi\sin\theta~,~z=r\cos\phi$ we obtain the Jacobian $J=r^2\sin\phi$. When $\phi$ and $\theta$ are fixed, $r$ varies from $0$ to $\sqrt[3]{\sin\phi\cos\theta}$ (because $r^4=r\sin\phi\cos\theta$). Keeping $\theta$ fixed, we let $\phi$ vary from $0$ to $\pi$. Thus the volume equals: $$V=\int\limits\_{0}^{\pi}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\phi\cos\theta}}r^2\sin\phi ~dr ~d\phi ~d\theta=0$$ Which is obviously wrong. What am I doing wrong?
2016/05/28
[ "https://math.stackexchange.com/questions/1803165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342907/" ]
We may as well consider the surface $(x^2+y^2+z^2)=z$ which is a rotational surface $S$ around the $z$-axis. Put $x^2+y^2=:\rho^2$. Then $S$ is given by the equation $$(\rho^2+z^2)^2=z\geq0\ .$$ It follows that $$\rho^2(z)=\sqrt{z}-z^2\qquad(0\leq z\leq1)\ ,$$ so that $$V=\pi\int\_0^1\rho^2(z)\>dz=\pi\>\left({2\over3}z^{3/2}-{1\over3}z^3\right)\biggr|\_0^1={\pi\over3}\ .$$
Byron Schmuland's suggestion is the easiest way to find this volume, but using spherical coordinates and symmetry to find the volume bounded by $(x^2+y^2+z^2)^2=z\;\;$ gives $\;\;\displaystyle V=\int\_0^{2\pi}\int\_0^{\frac{\pi}{2}}\int\_0^{\sqrt[3]{\cos\phi}}\rho^2\sin\phi\;d\rho d\phi d\theta=\frac{\pi}{3}$.
1,803,165
I need to calculate the volume of solid enclosed by the surface $(x^2+y^2+z^2)^2=x$, using only spherical coordinates. My attempt: by changing coordinates to spherical: $x=r\sin\phi\cos\theta~,~y=r\sin\phi\sin\theta~,~z=r\cos\phi$ we obtain the Jacobian $J=r^2\sin\phi$. When $\phi$ and $\theta$ are fixed, $r$ varies from $0$ to $\sqrt[3]{\sin\phi\cos\theta}$ (because $r^4=r\sin\phi\cos\theta$). Keeping $\theta$ fixed, we let $\phi$ vary from $0$ to $\pi$. Thus the volume equals: $$V=\int\limits\_{0}^{\pi}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\phi\cos\theta}}r^2\sin\phi ~dr ~d\phi ~d\theta=0$$ Which is obviously wrong. What am I doing wrong?
2016/05/28
[ "https://math.stackexchange.com/questions/1803165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342907/" ]
Succinctly, the bounds of integration on $\theta$ should be $-\pi/2\leq\theta\leq\pi/2$, which yields the very believable value of $\pi/3$. The comments seem to indicate some confusion about this, so let's explore it a bit further. A standard exercise related to spherical coordinates is to show that the graph of $\rho^2=x$ is a sphere. Now we've got $\rho^4=x$ so it makes sense to suppose that we have a slightly distorted sphere - perhaps, an oblate spheroid or close. In both cases, we have $$x=\text{a non-negative expression}.$$ Thus, the graph must lie fully in the half-space on one side of the $yz$-plane. Using some snazzy contour plotter, we see that it looks like so: [![enter image description here](https://i.stack.imgur.com/QA99d.png)](https://i.stack.imgur.com/QA99d.png) The contour line wrapped around the equator is the intersection of the object with the $xy$-plane. If we look at this from the above (along the $z$-axis) we can see how a polar arrow might trace out that contour: [![enter image description here](https://i.stack.imgur.com/99yKw.gif)](https://i.stack.imgur.com/99yKw.gif) From this image, it's pretty clear that we need $\theta$ to sweep from the negative $y$-axis to the positive $y$-axis. A natural way to make that happen is let $\theta$ range over $-\pi/2\leq\theta\leq\pi/2$. To polish the problem off, we rewrite the equation $(x^2+y^2+z^2)^2=x$ in spherical coordinates as $$\rho^4 = \rho\sin(\varphi)\cos(\theta),$$ or $$\rho = \sqrt[3]{\sin(\varphi)\cos(\theta)}.$$ This gives us the upper bound of $\rho$ in the spherical integral: $$ \int\limits\_{-\pi/2}^{\pi/2}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\varphi\cos\theta}}r^2\sin\varphi ~dr ~d\varphi ~d\theta=\frac{\pi}{3}. $$
Byron Schmuland's suggestion is the easiest way to find this volume, but using spherical coordinates and symmetry to find the volume bounded by $(x^2+y^2+z^2)^2=z\;\;$ gives $\;\;\displaystyle V=\int\_0^{2\pi}\int\_0^{\frac{\pi}{2}}\int\_0^{\sqrt[3]{\cos\phi}}\rho^2\sin\phi\;d\rho d\phi d\theta=\frac{\pi}{3}$.
1,803,165
I need to calculate the volume of solid enclosed by the surface $(x^2+y^2+z^2)^2=x$, using only spherical coordinates. My attempt: by changing coordinates to spherical: $x=r\sin\phi\cos\theta~,~y=r\sin\phi\sin\theta~,~z=r\cos\phi$ we obtain the Jacobian $J=r^2\sin\phi$. When $\phi$ and $\theta$ are fixed, $r$ varies from $0$ to $\sqrt[3]{\sin\phi\cos\theta}$ (because $r^4=r\sin\phi\cos\theta$). Keeping $\theta$ fixed, we let $\phi$ vary from $0$ to $\pi$. Thus the volume equals: $$V=\int\limits\_{0}^{\pi}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\phi\cos\theta}}r^2\sin\phi ~dr ~d\phi ~d\theta=0$$ Which is obviously wrong. What am I doing wrong?
2016/05/28
[ "https://math.stackexchange.com/questions/1803165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342907/" ]
Succinctly, the bounds of integration on $\theta$ should be $-\pi/2\leq\theta\leq\pi/2$, which yields the very believable value of $\pi/3$. The comments seem to indicate some confusion about this, so let's explore it a bit further. A standard exercise related to spherical coordinates is to show that the graph of $\rho^2=x$ is a sphere. Now we've got $\rho^4=x$ so it makes sense to suppose that we have a slightly distorted sphere - perhaps, an oblate spheroid or close. In both cases, we have $$x=\text{a non-negative expression}.$$ Thus, the graph must lie fully in the half-space on one side of the $yz$-plane. Using some snazzy contour plotter, we see that it looks like so: [![enter image description here](https://i.stack.imgur.com/QA99d.png)](https://i.stack.imgur.com/QA99d.png) The contour line wrapped around the equator is the intersection of the object with the $xy$-plane. If we look at this from the above (along the $z$-axis) we can see how a polar arrow might trace out that contour: [![enter image description here](https://i.stack.imgur.com/99yKw.gif)](https://i.stack.imgur.com/99yKw.gif) From this image, it's pretty clear that we need $\theta$ to sweep from the negative $y$-axis to the positive $y$-axis. A natural way to make that happen is let $\theta$ range over $-\pi/2\leq\theta\leq\pi/2$. To polish the problem off, we rewrite the equation $(x^2+y^2+z^2)^2=x$ in spherical coordinates as $$\rho^4 = \rho\sin(\varphi)\cos(\theta),$$ or $$\rho = \sqrt[3]{\sin(\varphi)\cos(\theta)}.$$ This gives us the upper bound of $\rho$ in the spherical integral: $$ \int\limits\_{-\pi/2}^{\pi/2}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\varphi\cos\theta}}r^2\sin\varphi ~dr ~d\varphi ~d\theta=\frac{\pi}{3}. $$
It's a solid of revolution. Let $h=\sqrt{y^{2}+z^{2}}$, then $(x^{2}+h^{2})^{2}=x$. $\therefore \; h^{2}=\sqrt{x}-x^{2} \:$ where $\, 0\leq x \leq 1$. \begin{align\*} V &= \int\_{0}^{1} \pi h^{2} dx \\ &= \pi \int\_{0}^{1} \left( \sqrt{x}-x^{2} \right) dx \\ &= \pi \left[ \frac{2}{3} x^{\frac{3}{2}}- \frac{1}{3} x^{3} \right]\_{0}^{1} \\ &= \frac{\pi}{3} \end{align\*}
1,803,165
I need to calculate the volume of solid enclosed by the surface $(x^2+y^2+z^2)^2=x$, using only spherical coordinates. My attempt: by changing coordinates to spherical: $x=r\sin\phi\cos\theta~,~y=r\sin\phi\sin\theta~,~z=r\cos\phi$ we obtain the Jacobian $J=r^2\sin\phi$. When $\phi$ and $\theta$ are fixed, $r$ varies from $0$ to $\sqrt[3]{\sin\phi\cos\theta}$ (because $r^4=r\sin\phi\cos\theta$). Keeping $\theta$ fixed, we let $\phi$ vary from $0$ to $\pi$. Thus the volume equals: $$V=\int\limits\_{0}^{\pi}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\phi\cos\theta}}r^2\sin\phi ~dr ~d\phi ~d\theta=0$$ Which is obviously wrong. What am I doing wrong?
2016/05/28
[ "https://math.stackexchange.com/questions/1803165", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342907/" ]
Succinctly, the bounds of integration on $\theta$ should be $-\pi/2\leq\theta\leq\pi/2$, which yields the very believable value of $\pi/3$. The comments seem to indicate some confusion about this, so let's explore it a bit further. A standard exercise related to spherical coordinates is to show that the graph of $\rho^2=x$ is a sphere. Now we've got $\rho^4=x$ so it makes sense to suppose that we have a slightly distorted sphere - perhaps, an oblate spheroid or close. In both cases, we have $$x=\text{a non-negative expression}.$$ Thus, the graph must lie fully in the half-space on one side of the $yz$-plane. Using some snazzy contour plotter, we see that it looks like so: [![enter image description here](https://i.stack.imgur.com/QA99d.png)](https://i.stack.imgur.com/QA99d.png) The contour line wrapped around the equator is the intersection of the object with the $xy$-plane. If we look at this from the above (along the $z$-axis) we can see how a polar arrow might trace out that contour: [![enter image description here](https://i.stack.imgur.com/99yKw.gif)](https://i.stack.imgur.com/99yKw.gif) From this image, it's pretty clear that we need $\theta$ to sweep from the negative $y$-axis to the positive $y$-axis. A natural way to make that happen is let $\theta$ range over $-\pi/2\leq\theta\leq\pi/2$. To polish the problem off, we rewrite the equation $(x^2+y^2+z^2)^2=x$ in spherical coordinates as $$\rho^4 = \rho\sin(\varphi)\cos(\theta),$$ or $$\rho = \sqrt[3]{\sin(\varphi)\cos(\theta)}.$$ This gives us the upper bound of $\rho$ in the spherical integral: $$ \int\limits\_{-\pi/2}^{\pi/2}\int\limits\_{0}^{\pi}\int\limits\_{0}^{\sqrt[3]{\sin\varphi\cos\theta}}r^2\sin\varphi ~dr ~d\varphi ~d\theta=\frac{\pi}{3}. $$
We may as well consider the surface $(x^2+y^2+z^2)=z$ which is a rotational surface $S$ around the $z$-axis. Put $x^2+y^2=:\rho^2$. Then $S$ is given by the equation $$(\rho^2+z^2)^2=z\geq0\ .$$ It follows that $$\rho^2(z)=\sqrt{z}-z^2\qquad(0\leq z\leq1)\ ,$$ so that $$V=\pi\int\_0^1\rho^2(z)\>dz=\pi\>\left({2\over3}z^{3/2}-{1\over3}z^3\right)\biggr|\_0^1={\pi\over3}\ .$$
499,345
**UPDATE 20th May:** Swapped the analog output regulator for an AZ1117-EH based on Peter Smith's suggestion, removed C1306, so now the 3.3VA output should be ok at least based on the [datasheet](https://www.diodes.com/assets/Datasheets/AZ1117E.pdf). However, no significant improvement. See scope shots and discussion under the section market NEW MAY 20TH. **UPDATE 18th May:** More scope shots below, which do seem to be telling a story. See discussion marked NEW. **UPDATE:** tried adding resistors to the DAC output which had some effect, see below. **EDIT:** tested the dielectric absorption theory: not the culprit (see below). I'm multiplexing a 4 channel 16 -bit DAC to 21 output channels via DG4052 multiplexers (exact part numbers and links to the datasheets below). There's a 10nF hold capacitor after the multiplexer, with the output going to the + -input of a TL074 opamp. The relevant part of the multiplexer schematic: [![MUX schematic](https://i.stack.imgur.com/PDU7a.png)](https://i.stack.imgur.com/PDU7a.png) **updated** and the DAC output schematic (though note below about adding a resistor in series): [![Schematic DAC](https://i.stack.imgur.com/YiwYl.png)](https://i.stack.imgur.com/YiwYl.png) The DACn channels come directly from the DAC outputs (but see below for a test with a resistor in between), and are in the range 0..3.3V. Update rate is 3kHz, and the charge time is about \$\mathrm{40\mu s}\$ **The problem:** The output of a channel, take for example VExpMCU, glitches by about 1.2mV when the enable toggles, and the address of the corresponding channel is selected. In the picture, the yellow trace is VExpMcu, AC coupled, and the blue trace is the MUX enable (which is inverting). The output value is held constant, so the ideal result would be a flat horizontal line: [![Glitch](https://i.stack.imgur.com/lpEff.jpg)](https://i.stack.imgur.com/lpEff.jpg) As a test, I added a 270\$\Omega\$ resistor between the DAC1 output and the MUX input. The result was that the glitch level about halved, but the initial transient is still about the same as before. Note the different time scale, and also the cursors showing that the step is now smaller, at about 660\$\mathrm{\mu V}\$: [![GlitchWith270ohms](https://i.stack.imgur.com/AcTAe.jpg)](https://i.stack.imgur.com/AcTAe.jpg) Interestingly, increasing the resistor to \$1\mathrm{k\Omega}\$ (sorry about the really bad picture here, vertical scale is 1mV/div) about further halved the step, but the initial glitch size remains about the same, with a much longer settling time. This suggests it may nonetheless be something similar to what Andy aka suggested, but there's still a downward step when the enable turns off, which means that somehow the hold cap immediately loses some charge: [![GlitchWith1kOhm](https://i.stack.imgur.com/GyLKk.jpg)](https://i.stack.imgur.com/GyLKk.jpg) **NEW on May 18th:** Setting all the channels to the same output value (so the DAC output would ideally be constant, and it's easy to scope slight glitches there) gives the following scope shot, yellow is enable (active low), blue is directly the DAC output: [![DacOut](https://i.stack.imgur.com/KbR2h.jpg)](https://i.stack.imgur.com/KbR2h.jpg) The big glitch happens while enable is off, so it's irrelevant here. However, there seems to be something on the rising/falling edges. Zooming in on the glitches near the enable signal edges: [![DacOutZoomR](https://i.stack.imgur.com/EUvKB.jpg)](https://i.stack.imgur.com/EUvKB.jpg) [![DacOutZoomL](https://i.stack.imgur.com/rgHi8.jpg)](https://i.stack.imgur.com/rgHi8.jpg) Then a scope shot of the power supply, yellow is still enable, blue is now the 3.3V analog power (AC coupled) measured at C1407: [![SupplyGlitch](https://i.stack.imgur.com/qmewR.jpg)](https://i.stack.imgur.com/qmewR.jpg) which seems to tell us everything: the analog supply sags when the enable toggles, causing the DAC output to glitch, which causes the glitch in the mux output. However, one more scope shot throws a wrench in the works: triggering the scope from the DAC output glitch (the big one that happens while the enable is off) gives the following (Blue is DAC output, yellow is 3.3V analog at C1407): [![Supply and DAC output](https://i.stack.imgur.com/SswUE.jpg)](https://i.stack.imgur.com/SswUE.jpg) Note the absence of the supply glitch. Basically, the scope shots of the 3.3V line are inconsistent, so one of them is wrong. So now I'm thoroughly confused. So how do I check if the problem in the supply is real or a scope artifact? If it's real, how to fix it? There's over 50\$\mathrm{\mu F}\$ of capacitors on the power rail, so just throwing more won't help unless it's *a lot* more. Here's the power section of the board, in case that tells us something (**EDIT: regulator has since been swapped**): [![PSU schematic](https://i.stack.imgur.com/Ci5R5.png)](https://i.stack.imgur.com/Ci5R5.png) **NEW MAY 20TH:** Swapped the analog regulator for an AZ1117-EH, which shouldn't have problems with the 100n caps (removed C1306 which was too close, though). The glitch on the supply still persists, it's now actually a bit bigger though more symmetric: [![GlitchSupplyAZ1117-EH](https://i.stack.imgur.com/aSJKd.jpg)](https://i.stack.imgur.com/aSJKd.jpg) As before, when triggering on the DAC the glitch on the supply line is not present, so that mystery still persists. It's also not on any other power rail when triggering from the DAC. However, it's there on all of them when triggering from the enable signal, for example this time with the yellow trace being +12V at the input to the analog 3.3V regulator: [![Glitch12V](https://i.stack.imgur.com/LpkGQ.jpg)](https://i.stack.imgur.com/LpkGQ.jpg) This is making me think that the glitch on the power rail may be an artifact of my scope grounding, somehow leaking from the neighbouring channel when I'm triggering on the enable (I also tried to use channels 1 and 4 on the scope, just in case, no difference). However, it's always there on the DAC output, so that's probably real. So what now? **EDIT:** Here's the list of potential sources for glitches which I originally considered, most of these appear somewhat irrelevant now in light of the new pictures: 1. mishaps in the timing code, i.e. DAC not having settled, address being selected after the enable, etc etc. However, I believe I've squashed such bugs from the firmware now (there were indeed a few). Also, one would expect those to produce a glitch in the beginning or end of the update cycle, whereas this seems to be a square-like shape for the duration of the enable pulse (although it's hard to be 100% certain since we're at the limits of my modest scope). Anyway, I'm happy to provide scope shots of the address/enable/DAC output signals if you have a hunch it might be something related to that. 2. Charge injection from the mux. However, from the [datasheet](https://www.vishay.com/docs/69685/dg4051e.pdf), the maximum charge injection is... uh... missing from the datasheet in the 12V case, but taking the worst of the cases there is, 0.38pC, which to a 10nF capacitor gives \$0.38\mathrm{pC} / 10 \mathrm{nF} = 38\mathrm{\mu V}\$ change, so about 30 times less. **Update** tried doubling the cap, as suggested by WhatRoughBeast. No change, so it's definitely not charge injection. 3. stray capacitance storing charge somewhere: if there'd be a stray capacitance of about \$1\mathrm{mV} / 3.3V 10 \mathrm{nF} \approx 30 \mathrm{pF}\$, then charge sharing could cause such a glitch (for a full scale voltage difference). However, \$30\mathrm{pF}\$ seems a bit big for stray capacitance here (although admittedly the biggest capacitances mentioned in the datasheet are about 10pF, so not that far off), and besides it's difficult to understand how it would cause the square-like shape, instead of the DAC output buffer correcting it after an initial glitch? **Edit** with the newer picture with the resistor, the squareness of the shape isn't quite that obvious anymore, but then it's difficult to see how increasing the resistance between the DAC and the mux would reduce the error if it's due to stray capacitance. 4. Stray coupling from the address/enable signals: the glitch only happens when that specific channels enable toggles, if it we're parasitic coupling I'd expect to see constant glitches at the enable rate. 5. Capacitor dielectric absorption (DA): I swapped the original X7R cap (specifically a TDK C1608X7R2A103K080AA) for a 10 nF C0G -capacitor (GRM1885C1H103JA01D) in the channel in question, which should have less DA, with no difference in the signal. So I think we can rule out DA. 6. as suggested by Andy aka: the DAC output buffer could be nearly unstable (the datasheet guarantees stability only up to 0.2nF for 0 ohm series resistance, up to 15\$\mathrm{\mu F}\$ for 500 ohms). To test this, I tried decreasing the update rate to 1kHz, which I'd expect to exaggerate the glitch, and potentially see the glitch starting to settle during the longer charge time. However, the glitch size remains exactly the same, and it still appears square-like, without showing signs of settling during the charge time (which has now increased to about 125\$\mathrm{\mu S}\$) **Edit:** however, see the new scope shots above: [![Glitch at 1kHz](https://i.stack.imgur.com/IanJS.jpg)](https://i.stack.imgur.com/IanJS.jpg) **Update:** also tried to add a 10k resistor from DAC output to ground, as suggested by PeterSmith. No change. **Summary this far:** the only change that has had an effect was adding a series resistor after the DAC. Interestingly, doubling the hold cap had no effect either, which means that the step at the end of the charge period is not a fixed amount of *charge* being drawn from the hold cap, but a fixed *voltage* step. However, the glitch seems to be present already at the DAC output, and there's something fishy about the power rails, see discussion above. The promised part numbers and datasheets (don't hesitate to ask for more info, if you need): * DAC: Maxim MAX5134AGTG+, [Datasheet](https://datasheets.maximintegrated.com/en/ds/MAX5134-MAX5137.pdf) * MUX: Vishay DG4052E, [Datasheet](https://www.vishay.com/docs/69685/dg4051e.pdf) * OpAmp: TI TL074, [Datasheet](https://www.ti.com/lit/ds/slos080n/slos080n.pdf?&ts=1589362944238) * hold cap: TDK C1608X7R2A103K080AA, [Datasheet](https://product.tdk.com/info/en/catalog/datasheets/mlcc_commercial_midvoltage_en.pdf) * Analog regulator: replaced an LM1117 with an [AZ1117-EH](https://www.diodes.com/assets/Datasheets/AZ1117E.pdf)
2020/05/13
[ "https://electronics.stackexchange.com/questions/499345", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/54822/" ]
The problem could well be at the 3.3V regulators: [![Power annotated](https://i.stack.imgur.com/SC53A.png)](https://i.stack.imgur.com/SC53A.png) I have circled the output capacitors; the LM1117 [datasheet](https://www.ti.com/lit/ds/symlink/lm1117.pdf?&ts=1589794564554) states: **8.2.2.1.3 Output Capacitor** > > The output capacitor is critical in maintaining regulator stability, > and must meet the required conditions for both minimum amount of > capacitance and equivalent series resistance (ESR). The **minimum** output > capacitance required by the LM1117 is **10 μF**, if a tantalum capacitor > is used. Any increase of the output capacitance will merely improve > the loop stability and transient response. The ESR of the output > capacitor should range between **0.3 Ω to 22 Ω**. In the case of the > adjustable regulator, when the CADJ is used, a larger output > capacitance (22-μF tantalum) is required. > > > A ceramic capacitor will very probably be below this minimum value and the actual minimum value depends on load *and* input voltage which will vary across those conditions. A load step (which does not need to be very much) *can* cause instability at the output which would explain a great deal. In addition to that, the output capacitance of the 3.3V digital rail does not appear to be sufficient (10\$\mu\$F *minimum*). Whether you actually see that instability is going to depend on many things and even attaching a scope probe to the power rail will change those conditions, so it may do one thing without the probe and something different when you *do* probe the power rail. [Update] The usual way of dealing with this sort of issue is to either use a standard tantalum (not the low esr series) which typically have an esr in the required range (although there are [other problems](https://electronics.stackexchange.com/questions/99320/are-tantalum-capacitors-safe-for-use-in-new-designs/99321#99321) with tantalums) or to use a ceramic in series with a low value resistor on the output. Where there are low esr local decouplers, they can sometimes be isolated by using a small inductor or ferrite on the output (we are trying to prevent instability caused by transients). If the devices are far enough away such that track inductance effectively isolates them from the output of the regulator then that may not be required. Sometimes, low esr local decouplers simply cannot be used (I have had this specific problem in the past) and the output capacitance on the regulator has to be relied upon for transient response. The output ESR issue for older LDO devices is well known and many newer parts do not have this problem.
> > *There's a 10nF hold capacitor after the multiplexer* > > > Another possible source might be made worse by a slow refresh time. For instance, the input bias current for the TL074 could be around 1 nA and using the capacitor equation below: - $$I = C\frac{dv}{dt}$$ We find that the rate of change of voltage on the 10 nF capacitor is 100 mV per second. So, if your refresh time is 1 kHz, you might see 1 mV ripple on the storage capacitor feeding the TL074 input. If your refresh time is 10 ms then you'll see 10 mV of ripple. I'm not saying this is the culprit of course but, it's something to look into. The DG4052 has an "off" leakage current of typically up to 1 nA and this may make the issue doubly worse. There's also the problem of maximum capacitive load as specified in the data sheet: - [![enter image description here](https://i.stack.imgur.com/5Y0Rw.png)](https://i.stack.imgur.com/5Y0Rw.png) With 10 nF connected the internal DAC buffer amp may actually be going a little unstable with 10 nF connected.
499,345
**UPDATE 20th May:** Swapped the analog output regulator for an AZ1117-EH based on Peter Smith's suggestion, removed C1306, so now the 3.3VA output should be ok at least based on the [datasheet](https://www.diodes.com/assets/Datasheets/AZ1117E.pdf). However, no significant improvement. See scope shots and discussion under the section market NEW MAY 20TH. **UPDATE 18th May:** More scope shots below, which do seem to be telling a story. See discussion marked NEW. **UPDATE:** tried adding resistors to the DAC output which had some effect, see below. **EDIT:** tested the dielectric absorption theory: not the culprit (see below). I'm multiplexing a 4 channel 16 -bit DAC to 21 output channels via DG4052 multiplexers (exact part numbers and links to the datasheets below). There's a 10nF hold capacitor after the multiplexer, with the output going to the + -input of a TL074 opamp. The relevant part of the multiplexer schematic: [![MUX schematic](https://i.stack.imgur.com/PDU7a.png)](https://i.stack.imgur.com/PDU7a.png) **updated** and the DAC output schematic (though note below about adding a resistor in series): [![Schematic DAC](https://i.stack.imgur.com/YiwYl.png)](https://i.stack.imgur.com/YiwYl.png) The DACn channels come directly from the DAC outputs (but see below for a test with a resistor in between), and are in the range 0..3.3V. Update rate is 3kHz, and the charge time is about \$\mathrm{40\mu s}\$ **The problem:** The output of a channel, take for example VExpMCU, glitches by about 1.2mV when the enable toggles, and the address of the corresponding channel is selected. In the picture, the yellow trace is VExpMcu, AC coupled, and the blue trace is the MUX enable (which is inverting). The output value is held constant, so the ideal result would be a flat horizontal line: [![Glitch](https://i.stack.imgur.com/lpEff.jpg)](https://i.stack.imgur.com/lpEff.jpg) As a test, I added a 270\$\Omega\$ resistor between the DAC1 output and the MUX input. The result was that the glitch level about halved, but the initial transient is still about the same as before. Note the different time scale, and also the cursors showing that the step is now smaller, at about 660\$\mathrm{\mu V}\$: [![GlitchWith270ohms](https://i.stack.imgur.com/AcTAe.jpg)](https://i.stack.imgur.com/AcTAe.jpg) Interestingly, increasing the resistor to \$1\mathrm{k\Omega}\$ (sorry about the really bad picture here, vertical scale is 1mV/div) about further halved the step, but the initial glitch size remains about the same, with a much longer settling time. This suggests it may nonetheless be something similar to what Andy aka suggested, but there's still a downward step when the enable turns off, which means that somehow the hold cap immediately loses some charge: [![GlitchWith1kOhm](https://i.stack.imgur.com/GyLKk.jpg)](https://i.stack.imgur.com/GyLKk.jpg) **NEW on May 18th:** Setting all the channels to the same output value (so the DAC output would ideally be constant, and it's easy to scope slight glitches there) gives the following scope shot, yellow is enable (active low), blue is directly the DAC output: [![DacOut](https://i.stack.imgur.com/KbR2h.jpg)](https://i.stack.imgur.com/KbR2h.jpg) The big glitch happens while enable is off, so it's irrelevant here. However, there seems to be something on the rising/falling edges. Zooming in on the glitches near the enable signal edges: [![DacOutZoomR](https://i.stack.imgur.com/EUvKB.jpg)](https://i.stack.imgur.com/EUvKB.jpg) [![DacOutZoomL](https://i.stack.imgur.com/rgHi8.jpg)](https://i.stack.imgur.com/rgHi8.jpg) Then a scope shot of the power supply, yellow is still enable, blue is now the 3.3V analog power (AC coupled) measured at C1407: [![SupplyGlitch](https://i.stack.imgur.com/qmewR.jpg)](https://i.stack.imgur.com/qmewR.jpg) which seems to tell us everything: the analog supply sags when the enable toggles, causing the DAC output to glitch, which causes the glitch in the mux output. However, one more scope shot throws a wrench in the works: triggering the scope from the DAC output glitch (the big one that happens while the enable is off) gives the following (Blue is DAC output, yellow is 3.3V analog at C1407): [![Supply and DAC output](https://i.stack.imgur.com/SswUE.jpg)](https://i.stack.imgur.com/SswUE.jpg) Note the absence of the supply glitch. Basically, the scope shots of the 3.3V line are inconsistent, so one of them is wrong. So now I'm thoroughly confused. So how do I check if the problem in the supply is real or a scope artifact? If it's real, how to fix it? There's over 50\$\mathrm{\mu F}\$ of capacitors on the power rail, so just throwing more won't help unless it's *a lot* more. Here's the power section of the board, in case that tells us something (**EDIT: regulator has since been swapped**): [![PSU schematic](https://i.stack.imgur.com/Ci5R5.png)](https://i.stack.imgur.com/Ci5R5.png) **NEW MAY 20TH:** Swapped the analog regulator for an AZ1117-EH, which shouldn't have problems with the 100n caps (removed C1306 which was too close, though). The glitch on the supply still persists, it's now actually a bit bigger though more symmetric: [![GlitchSupplyAZ1117-EH](https://i.stack.imgur.com/aSJKd.jpg)](https://i.stack.imgur.com/aSJKd.jpg) As before, when triggering on the DAC the glitch on the supply line is not present, so that mystery still persists. It's also not on any other power rail when triggering from the DAC. However, it's there on all of them when triggering from the enable signal, for example this time with the yellow trace being +12V at the input to the analog 3.3V regulator: [![Glitch12V](https://i.stack.imgur.com/LpkGQ.jpg)](https://i.stack.imgur.com/LpkGQ.jpg) This is making me think that the glitch on the power rail may be an artifact of my scope grounding, somehow leaking from the neighbouring channel when I'm triggering on the enable (I also tried to use channels 1 and 4 on the scope, just in case, no difference). However, it's always there on the DAC output, so that's probably real. So what now? **EDIT:** Here's the list of potential sources for glitches which I originally considered, most of these appear somewhat irrelevant now in light of the new pictures: 1. mishaps in the timing code, i.e. DAC not having settled, address being selected after the enable, etc etc. However, I believe I've squashed such bugs from the firmware now (there were indeed a few). Also, one would expect those to produce a glitch in the beginning or end of the update cycle, whereas this seems to be a square-like shape for the duration of the enable pulse (although it's hard to be 100% certain since we're at the limits of my modest scope). Anyway, I'm happy to provide scope shots of the address/enable/DAC output signals if you have a hunch it might be something related to that. 2. Charge injection from the mux. However, from the [datasheet](https://www.vishay.com/docs/69685/dg4051e.pdf), the maximum charge injection is... uh... missing from the datasheet in the 12V case, but taking the worst of the cases there is, 0.38pC, which to a 10nF capacitor gives \$0.38\mathrm{pC} / 10 \mathrm{nF} = 38\mathrm{\mu V}\$ change, so about 30 times less. **Update** tried doubling the cap, as suggested by WhatRoughBeast. No change, so it's definitely not charge injection. 3. stray capacitance storing charge somewhere: if there'd be a stray capacitance of about \$1\mathrm{mV} / 3.3V 10 \mathrm{nF} \approx 30 \mathrm{pF}\$, then charge sharing could cause such a glitch (for a full scale voltage difference). However, \$30\mathrm{pF}\$ seems a bit big for stray capacitance here (although admittedly the biggest capacitances mentioned in the datasheet are about 10pF, so not that far off), and besides it's difficult to understand how it would cause the square-like shape, instead of the DAC output buffer correcting it after an initial glitch? **Edit** with the newer picture with the resistor, the squareness of the shape isn't quite that obvious anymore, but then it's difficult to see how increasing the resistance between the DAC and the mux would reduce the error if it's due to stray capacitance. 4. Stray coupling from the address/enable signals: the glitch only happens when that specific channels enable toggles, if it we're parasitic coupling I'd expect to see constant glitches at the enable rate. 5. Capacitor dielectric absorption (DA): I swapped the original X7R cap (specifically a TDK C1608X7R2A103K080AA) for a 10 nF C0G -capacitor (GRM1885C1H103JA01D) in the channel in question, which should have less DA, with no difference in the signal. So I think we can rule out DA. 6. as suggested by Andy aka: the DAC output buffer could be nearly unstable (the datasheet guarantees stability only up to 0.2nF for 0 ohm series resistance, up to 15\$\mathrm{\mu F}\$ for 500 ohms). To test this, I tried decreasing the update rate to 1kHz, which I'd expect to exaggerate the glitch, and potentially see the glitch starting to settle during the longer charge time. However, the glitch size remains exactly the same, and it still appears square-like, without showing signs of settling during the charge time (which has now increased to about 125\$\mathrm{\mu S}\$) **Edit:** however, see the new scope shots above: [![Glitch at 1kHz](https://i.stack.imgur.com/IanJS.jpg)](https://i.stack.imgur.com/IanJS.jpg) **Update:** also tried to add a 10k resistor from DAC output to ground, as suggested by PeterSmith. No change. **Summary this far:** the only change that has had an effect was adding a series resistor after the DAC. Interestingly, doubling the hold cap had no effect either, which means that the step at the end of the charge period is not a fixed amount of *charge* being drawn from the hold cap, but a fixed *voltage* step. However, the glitch seems to be present already at the DAC output, and there's something fishy about the power rails, see discussion above. The promised part numbers and datasheets (don't hesitate to ask for more info, if you need): * DAC: Maxim MAX5134AGTG+, [Datasheet](https://datasheets.maximintegrated.com/en/ds/MAX5134-MAX5137.pdf) * MUX: Vishay DG4052E, [Datasheet](https://www.vishay.com/docs/69685/dg4051e.pdf) * OpAmp: TI TL074, [Datasheet](https://www.ti.com/lit/ds/slos080n/slos080n.pdf?&ts=1589362944238) * hold cap: TDK C1608X7R2A103K080AA, [Datasheet](https://product.tdk.com/info/en/catalog/datasheets/mlcc_commercial_midvoltage_en.pdf) * Analog regulator: replaced an LM1117 with an [AZ1117-EH](https://www.diodes.com/assets/Datasheets/AZ1117E.pdf)
2020/05/13
[ "https://electronics.stackexchange.com/questions/499345", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/54822/" ]
The problem could well be at the 3.3V regulators: [![Power annotated](https://i.stack.imgur.com/SC53A.png)](https://i.stack.imgur.com/SC53A.png) I have circled the output capacitors; the LM1117 [datasheet](https://www.ti.com/lit/ds/symlink/lm1117.pdf?&ts=1589794564554) states: **8.2.2.1.3 Output Capacitor** > > The output capacitor is critical in maintaining regulator stability, > and must meet the required conditions for both minimum amount of > capacitance and equivalent series resistance (ESR). The **minimum** output > capacitance required by the LM1117 is **10 μF**, if a tantalum capacitor > is used. Any increase of the output capacitance will merely improve > the loop stability and transient response. The ESR of the output > capacitor should range between **0.3 Ω to 22 Ω**. In the case of the > adjustable regulator, when the CADJ is used, a larger output > capacitance (22-μF tantalum) is required. > > > A ceramic capacitor will very probably be below this minimum value and the actual minimum value depends on load *and* input voltage which will vary across those conditions. A load step (which does not need to be very much) *can* cause instability at the output which would explain a great deal. In addition to that, the output capacitance of the 3.3V digital rail does not appear to be sufficient (10\$\mu\$F *minimum*). Whether you actually see that instability is going to depend on many things and even attaching a scope probe to the power rail will change those conditions, so it may do one thing without the probe and something different when you *do* probe the power rail. [Update] The usual way of dealing with this sort of issue is to either use a standard tantalum (not the low esr series) which typically have an esr in the required range (although there are [other problems](https://electronics.stackexchange.com/questions/99320/are-tantalum-capacitors-safe-for-use-in-new-designs/99321#99321) with tantalums) or to use a ceramic in series with a low value resistor on the output. Where there are low esr local decouplers, they can sometimes be isolated by using a small inductor or ferrite on the output (we are trying to prevent instability caused by transients). If the devices are far enough away such that track inductance effectively isolates them from the output of the regulator then that may not be required. Sometimes, low esr local decouplers simply cannot be used (I have had this specific problem in the past) and the output capacitance on the regulator has to be relied upon for transient response. The output ESR issue for older LDO devices is well known and many newer parts do not have this problem.
I suggest you look into charge injection. The edges of the hold signal are capacitively coupled to the output, resulting in a step change in the output when feeding a cap. The quick test is to change the value of the buffer cap, and see what happens to your step size. If it's charge injection, a smaller cap will give a larger step, and vice-versa.
3,814,277
I'm working on a PHP project that has a lot of hard coded paths in it. I'm not the main developer, just working on a small part of the project. I'd like to be able to test my changes locally before committing them, but my directory structure is completely different. For example, there's a lot of this in the code: ``` require_once("/home/clientx/htdocs/include.php") ``` Which doesn't work on my local WAMP server because the path is different. Is there a way to tell either WAMP or XP that "/home/clientx/htdocs/" really means "c:/shared/clients/clientx"?
2010/09/28
[ "https://Stackoverflow.com/questions/3814277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222374/" ]
Always use `$_SERVER['DOCUMENT_ROOT']` instead of hardcoded path. ``` require_once($_SERVER['DOCUMENT_ROOT']."/include.php") ``` as for your wamb environment, you will need a dedicated drive to simulate file structure. You can use NTFS tools or simple `subst` command to map some directory to a drive. Create `/home/clientx/htdocs/` folder on this drive and change your httpd.conf to reflect it. But again, you will do yourself a huge favor by convincing your coworkers to stop using hardcoded paths
**WARNING: ONLY USE THIS SOLUTION FOR EMERGENCY REPAIRS, NEVER FOR LONGER PRODUCTION CODE** Define a class with rewriting methods, see <http://php.net/manual/en/class.streamwrapper.php> ``` <?php class YourEmergencyWrapper { static $from = '/home/clientx/htdocs/'; static $to = 'c:/shared/clients/client'; private $resource = null; //...some example stream_* functions, be sure to implement them all function stream_open($path,$mode,$options=null,&$opened_path){ $path = self::rewrite($path); self::restore(); $this->resource = fopen($path,$mode,$options); self::reenable(); $opened_path = $path; return is_resource($this->resource); } function stream_read($count){ self::restore(); $ret = fread($this->resource,$count); self::reenable(); return $ret; } function stream_eof(){ self::restore(); $ret = feof($this->resource); self::reenable(); return $ret; } function stream_stat(){ self::restore(); $ret = fstat($this->resource); self::reenable(); return $ret; } static function rewrite($path){ if(strpos($path,self::$from)===0) $path = self::$to.substr($path,strlen(self::$from)); return $path; } //... other functions private static function restore(){ stream_wrapper_restore('file'); } private static function reenable(){ stream_wrapper_unregister('file'); stream_wrapper_register('file',__CLASS__); } } stream_wrapper_unregister('file'); stream_wrapper_register('file','YourEmergencyWrapper'); ``` Seriously, only some local debugging on your own dev-server. You can force it as an auto\_prepend on almost any code. Left some function yet be implemented ;P
3,814,277
I'm working on a PHP project that has a lot of hard coded paths in it. I'm not the main developer, just working on a small part of the project. I'd like to be able to test my changes locally before committing them, but my directory structure is completely different. For example, there's a lot of this in the code: ``` require_once("/home/clientx/htdocs/include.php") ``` Which doesn't work on my local WAMP server because the path is different. Is there a way to tell either WAMP or XP that "/home/clientx/htdocs/" really means "c:/shared/clients/clientx"?
2010/09/28
[ "https://Stackoverflow.com/questions/3814277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222374/" ]
If its a local copy, do a search and replace on the whole directory , Please don't forget trailing slash. And when you commit the code, do reverse. This is the solution, if you don't want to add extra variables and stuff (because that would change other developers' code/work/dependencies (if any) search "/home/clientx/htdocs/" and replace to this: "c:/shared/clients/clientx/"
**WARNING: ONLY USE THIS SOLUTION FOR EMERGENCY REPAIRS, NEVER FOR LONGER PRODUCTION CODE** Define a class with rewriting methods, see <http://php.net/manual/en/class.streamwrapper.php> ``` <?php class YourEmergencyWrapper { static $from = '/home/clientx/htdocs/'; static $to = 'c:/shared/clients/client'; private $resource = null; //...some example stream_* functions, be sure to implement them all function stream_open($path,$mode,$options=null,&$opened_path){ $path = self::rewrite($path); self::restore(); $this->resource = fopen($path,$mode,$options); self::reenable(); $opened_path = $path; return is_resource($this->resource); } function stream_read($count){ self::restore(); $ret = fread($this->resource,$count); self::reenable(); return $ret; } function stream_eof(){ self::restore(); $ret = feof($this->resource); self::reenable(); return $ret; } function stream_stat(){ self::restore(); $ret = fstat($this->resource); self::reenable(); return $ret; } static function rewrite($path){ if(strpos($path,self::$from)===0) $path = self::$to.substr($path,strlen(self::$from)); return $path; } //... other functions private static function restore(){ stream_wrapper_restore('file'); } private static function reenable(){ stream_wrapper_unregister('file'); stream_wrapper_register('file',__CLASS__); } } stream_wrapper_unregister('file'); stream_wrapper_register('file','YourEmergencyWrapper'); ``` Seriously, only some local debugging on your own dev-server. You can force it as an auto\_prepend on almost any code. Left some function yet be implemented ;P
63,313,509
For my work, we are trying to spin up a docker swarm cluster with Puppet. We use puppetlabs-docker for this, which has a module `docker::swarm`. This module allows you to instantiate a docker swarm manager on your master node. This works so far. On the docker workers you can join to docker swarm manager with exported resources: ``` node 'manager' { @@docker::swarm {'cluster_worker': join => true, advertise_addr => '192.168.1.2', listen_addr => '192.168.1.2', manager_ip => '192.168.1.1', token => 'your_join_token' tag => 'docker-join' } } ``` However, the `your_join_token` needs to be retrieved from the docker swarm manager with `docker swarm join-token worker -q`. This is possible with `Exec`. My question is: is there a way (without breaking Puppet philosophy on idempotent and convergence) to get the output from the join-token `Exec` and pass this along to the exported resource, so that my workers can join master?
2020/08/08
[ "https://Stackoverflow.com/questions/63313509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3419197/" ]
> > My question is: is there a way (without breaking Puppet philosophy on > idempotent and convergence) to get the output from the join-token Exec > and pass this along to the exported resource, so that my workers can > join master? > > > No, because the properties of resource declarations, exported or otherwise, are determined when the target node's catalog is built (on the master), whereas the command of an `Exec` resource is run only later, when the fully-built catalog is applied to the target node. I'm uncertain about the detailed requirements for token generation, but possibly you could use Puppet's [generate()](https://puppet.com/docs/puppet/6.17/function.html#generate) function to obtain one at need, during catalog building on the master. **Update** Another alternative would be an external (or custom) fact. This is the conventional mechanism for gathering information from a node to be used during catalog building for that node, and as such, it might be more suited to your particular needs. There are some potential issues with this, but I'm unsure how many actually apply: * The fact has to know for which nodes to generate join tokens. This might be easier / more robust or trickier / more brittle depending on factors including + whether join tokens are node-specific (harder if they are) + whether it is important to avoid generating multiple join tokens for the same node (over multiple Puppet runs; harder if this is important) + notwithstanding the preceding, whether there is ever a need to generate a new join token for a node for which one was already generated (harder if this is a requirement) * If implemented as a dynamically-generated external fact -- which seems a reasonable option -- then when a new node is added to the list, the fact implementation will be updated on the manager's next puppet run, but the data will not be available until the following one. This is not necessarily a big deal, however, as it is a one-time delay with respect to each new node, and you can always manually perform a catalog run on the manager node to move things along more quickly. * It has more moving parts, with more complex relationships among them, hence there is a larger cross-section for bugs and unexpected behavior.
Thanks to @John Bollinger I seem to have fixed my issue. In the end, it was a bit more worked than I envisioned, but this is the idea: 1. My puppet setup now uses PuppetDB for storing facts and sharing exported resources. 2. I have added an additional custom fact to the code base of Docker (in `./lib/facter/docker.rb`). 3. The bare minimum in the `site.pp` file, now contains: ``` node 'manager' { docker::swarm {'cluster_manager': init => true, advertise_addr => "${::ipaddress}", listen_addr => "${::ipaddress}", require => Class['docker'], } @@docker::swarm {'cluster_worker': join => true, manager_ip => "${::ipaddress}", token => "${worker_join_token}", tag => "cluster_join_command", require => Class['docker'], } } node 'worker' { Docker::Swarm<<| tag == 'cluster_join_command' |>> { advertise_addr => "${::ipaddress}", listen_addr => "${::ipaddress}", } } ``` Do keep in mind that for this to work, `puppet agent -t` has to be run twice on the `manager` node, and once (after this) on the `worker` node. The first run on the manager will start the `cluster_manager`, while the second one will fetch the `worker_join_token` and upload it to PuppetDB. After this fact is set, the manifest for the worker can be properly compiled and run. In the case of a different module, you have to add a custom fact yourself. When I was researching how to do this, I added the custom fact to the `LOAD_PATH` of ruby, but was unable to find it in my PuppetDB. After some browsing I found that facts from a module are uploaded to PuppetDB, which is the reason that I tweaked the upstream Docker module.
40,161,673
The problem I am trying to solve. I want to use jQuery to dynamically add content to a div depending on which class is being used. I am not sure why the alerts aren't working. It could be my html or the jquery itself. I want to solve this so that I can have different text appear depending on which class shows up. Here is the HTML ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> ``` Here is the jQuery ``` $(document).ready(function() { if ($(this).hasClass("size5")) { $("div.p-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(this).hasClass("size4")) { alert('TEST!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(this).hasClass("size3")) { alert('TEST 3!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
2016/10/20
[ "https://Stackoverflow.com/questions/40161673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174713/" ]
Your usage of `$(this)` won't work because you haven't made a selection. In JQuery `this` is always bound to the context the previous selector or method, it's a JQuery object containing the results of the selection or filter. Additionally, your selector for finding the child element to insert HTML into is too broad. ``` $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); ``` It will select every single `<div>` with a class of `p-accessible-alt` and insert the same HTML block into all of them. You can replace your entire if block with the following selectors (one for each size). ``` $(".size3").siblings(".p-accessible-alt").html("<p> Blah Blah Size3</p>"); $(".size4").siblings(".p-accessible-alt").html("<p> Blah Blah Size4</p>"); $(".size5").siblings(".p-accessible-alt").html("<p> Blah Blah Size5</p>"); ``` This works by finding the element with the class `.sizeX` and then traverses up to it's parent container, then back down the hierarchy to find it's descendant with the class `.p-accessible-alt` and then apply the html to that.
You don't need the conditional at all. You should just do the following: ``` $(document).ready(function() { $(".size3").nextAll(".p-accessible-alt").html("Your HTML here"); $(".size4").nextAll(".p-accessible-alt").html("Your HTML here"); $(".size5").nextAll(".p-accessible-alt").html("Your HTML here"); }); ``` <http://codepen.io/bradevans/pen/yaGyZQ?editors=1111>
40,161,673
The problem I am trying to solve. I want to use jQuery to dynamically add content to a div depending on which class is being used. I am not sure why the alerts aren't working. It could be my html or the jquery itself. I want to solve this so that I can have different text appear depending on which class shows up. Here is the HTML ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> ``` Here is the jQuery ``` $(document).ready(function() { if ($(this).hasClass("size5")) { $("div.p-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(this).hasClass("size4")) { alert('TEST!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(this).hasClass("size3")) { alert('TEST 3!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
2016/10/20
[ "https://Stackoverflow.com/questions/40161673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174713/" ]
Your usage of `$(this)` won't work because you haven't made a selection. In JQuery `this` is always bound to the context the previous selector or method, it's a JQuery object containing the results of the selection or filter. Additionally, your selector for finding the child element to insert HTML into is too broad. ``` $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); ``` It will select every single `<div>` with a class of `p-accessible-alt` and insert the same HTML block into all of them. You can replace your entire if block with the following selectors (one for each size). ``` $(".size3").siblings(".p-accessible-alt").html("<p> Blah Blah Size3</p>"); $(".size4").siblings(".p-accessible-alt").html("<p> Blah Blah Size4</p>"); $(".size5").siblings(".p-accessible-alt").html("<p> Blah Blah Size5</p>"); ``` This works by finding the element with the class `.sizeX` and then traverses up to it's parent container, then back down the hierarchy to find it's descendant with the class `.p-accessible-alt` and then apply the html to that.
here is little more generic solution with some suggestions: * Use classes only for CSS or JavaScript and [prefix your JavaScript-classes with "js-"](http://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/) * I would choose a generic approach. So you can add or delete items without changing your JavaScript-code all the time. And in this case it would be a good idea to use an attribute to store item data instead of adding it to the classes ```js $('.js-add-size').each(function() { var jThis = $(this); var itemHtml = 'Blah Blah ' + jThis.attr('data-size'); jThis.find('.js-size-item').html(itemHtml); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="js-add-size" data-size="size3"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> <td class="js-add-size" data-size="size4"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> <td class="js-add-size" data-size="size5"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> </tr> </table> ``` And one last thing. Maybe you wanne be even more flexible and use some little template engine, like [mustache](https://github.com/janl/mustache.js/), instead of doing things like: ``` var itemHtml = 'Blah Blah ' + jThis.attr('data-size'); ```
40,161,673
The problem I am trying to solve. I want to use jQuery to dynamically add content to a div depending on which class is being used. I am not sure why the alerts aren't working. It could be my html or the jquery itself. I want to solve this so that I can have different text appear depending on which class shows up. Here is the HTML ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> ``` Here is the jQuery ``` $(document).ready(function() { if ($(this).hasClass("size5")) { $("div.p-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(this).hasClass("size4")) { alert('TEST!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(this).hasClass("size3")) { alert('TEST 3!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
2016/10/20
[ "https://Stackoverflow.com/questions/40161673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174713/" ]
Your usage of `$(this)` won't work because you haven't made a selection. In JQuery `this` is always bound to the context the previous selector or method, it's a JQuery object containing the results of the selection or filter. Additionally, your selector for finding the child element to insert HTML into is too broad. ``` $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); ``` It will select every single `<div>` with a class of `p-accessible-alt` and insert the same HTML block into all of them. You can replace your entire if block with the following selectors (one for each size). ``` $(".size3").siblings(".p-accessible-alt").html("<p> Blah Blah Size3</p>"); $(".size4").siblings(".p-accessible-alt").html("<p> Blah Blah Size4</p>"); $(".size5").siblings(".p-accessible-alt").html("<p> Blah Blah Size5</p>"); ``` This works by finding the element with the class `.sizeX` and then traverses up to it's parent container, then back down the hierarchy to find it's descendant with the class `.p-accessible-alt` and then apply the html to that.
The code works once you take out (this) and reference the selector .po because ,as other's have stated, (this) is actually referencing the document. ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> $(document).ready(function() { if ($(".po").hasClass("size5")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(".po").hasClass("size4")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(".po").hasClass("size3")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
40,161,673
The problem I am trying to solve. I want to use jQuery to dynamically add content to a div depending on which class is being used. I am not sure why the alerts aren't working. It could be my html or the jquery itself. I want to solve this so that I can have different text appear depending on which class shows up. Here is the HTML ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> ``` Here is the jQuery ``` $(document).ready(function() { if ($(this).hasClass("size5")) { $("div.p-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(this).hasClass("size4")) { alert('TEST!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(this).hasClass("size3")) { alert('TEST 3!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
2016/10/20
[ "https://Stackoverflow.com/questions/40161673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174713/" ]
You don't need the conditional at all. You should just do the following: ``` $(document).ready(function() { $(".size3").nextAll(".p-accessible-alt").html("Your HTML here"); $(".size4").nextAll(".p-accessible-alt").html("Your HTML here"); $(".size5").nextAll(".p-accessible-alt").html("Your HTML here"); }); ``` <http://codepen.io/bradevans/pen/yaGyZQ?editors=1111>
here is little more generic solution with some suggestions: * Use classes only for CSS or JavaScript and [prefix your JavaScript-classes with "js-"](http://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/) * I would choose a generic approach. So you can add or delete items without changing your JavaScript-code all the time. And in this case it would be a good idea to use an attribute to store item data instead of adding it to the classes ```js $('.js-add-size').each(function() { var jThis = $(this); var itemHtml = 'Blah Blah ' + jThis.attr('data-size'); jThis.find('.js-size-item').html(itemHtml); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="js-add-size" data-size="size3"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> <td class="js-add-size" data-size="size4"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> <td class="js-add-size" data-size="size5"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> </tr> </table> ``` And one last thing. Maybe you wanne be even more flexible and use some little template engine, like [mustache](https://github.com/janl/mustache.js/), instead of doing things like: ``` var itemHtml = 'Blah Blah ' + jThis.attr('data-size'); ```
40,161,673
The problem I am trying to solve. I want to use jQuery to dynamically add content to a div depending on which class is being used. I am not sure why the alerts aren't working. It could be my html or the jquery itself. I want to solve this so that I can have different text appear depending on which class shows up. Here is the HTML ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> ``` Here is the jQuery ``` $(document).ready(function() { if ($(this).hasClass("size5")) { $("div.p-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(this).hasClass("size4")) { alert('TEST!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(this).hasClass("size3")) { alert('TEST 3!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
2016/10/20
[ "https://Stackoverflow.com/questions/40161673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174713/" ]
You don't need the conditional at all. You should just do the following: ``` $(document).ready(function() { $(".size3").nextAll(".p-accessible-alt").html("Your HTML here"); $(".size4").nextAll(".p-accessible-alt").html("Your HTML here"); $(".size5").nextAll(".p-accessible-alt").html("Your HTML here"); }); ``` <http://codepen.io/bradevans/pen/yaGyZQ?editors=1111>
The code works once you take out (this) and reference the selector .po because ,as other's have stated, (this) is actually referencing the document. ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> $(document).ready(function() { if ($(".po").hasClass("size5")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(".po").hasClass("size4")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(".po").hasClass("size3")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
40,161,673
The problem I am trying to solve. I want to use jQuery to dynamically add content to a div depending on which class is being used. I am not sure why the alerts aren't working. It could be my html or the jquery itself. I want to solve this so that I can have different text appear depending on which class shows up. Here is the HTML ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> ``` Here is the jQuery ``` $(document).ready(function() { if ($(this).hasClass("size5")) { $("div.p-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(this).hasClass("size4")) { alert('TEST!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(this).hasClass("size3")) { alert('TEST 3!!!'); $("div.p-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
2016/10/20
[ "https://Stackoverflow.com/questions/40161673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174713/" ]
The code works once you take out (this) and reference the selector .po because ,as other's have stated, (this) is actually referencing the document. ``` <td> <div class="po size3"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size4"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> <td> <div class="po size5"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt"></div> </td> $(document).ready(function() { if ($(".po").hasClass("size5")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size5</p>"); } else if ($(".po").hasClass("size4")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size4</p>"); } else if ($(".po").hasClass("size3")) { $("div.plan-accessible-alt").html("<p> Blah Blah Size3</p>"); } }); ```
here is little more generic solution with some suggestions: * Use classes only for CSS or JavaScript and [prefix your JavaScript-classes with "js-"](http://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/) * I would choose a generic approach. So you can add or delete items without changing your JavaScript-code all the time. And in this case it would be a good idea to use an attribute to store item data instead of adding it to the classes ```js $('.js-add-size').each(function() { var jThis = $(this); var itemHtml = 'Blah Blah ' + jThis.attr('data-size'); jThis.find('.js-size-item').html(itemHtml); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="js-add-size" data-size="size3"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> <td class="js-add-size" data-size="size4"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> <td class="js-add-size" data-size="size5"> <div class="po"></div> <a class="external">Find your doctor</a> <div class="p-accessible-alt js-size-item"></div> </td> </tr> </table> ``` And one last thing. Maybe you wanne be even more flexible and use some little template engine, like [mustache](https://github.com/janl/mustache.js/), instead of doing things like: ``` var itemHtml = 'Blah Blah ' + jThis.attr('data-size'); ```
1,723,227
I have a table of a couple of million records. During production, we find that there is a particular type of query that is taking a few seconds to complete. When I try to reproduce the issue on my machine which has replicated production data, I ran the exact query (as obtained from the slow query log) in the mysql client, it took a few seconds as expected. If I then press up and enter to repeat it, it takes 0.01 seconds subsequently. I have looked up the docs to find out how to turn off caching, so that I can consistently reproduce the issue, and want to test if adding an index will help. Here is what I tried: RESET QUERY CACHE; FLUSH TABLES; However, after the above commands, running the same query again still only takes 0.01 seconds. I must be missing something. Any ideas?
2009/11/12
[ "https://Stackoverflow.com/questions/1723227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209731/" ]
You can tell the server not to place the result in the query cache by including [SQL\_NO\_CACHE](http://dev.mysql.com/doc/refman/5.1/en/query-cache-in-select.html) in the query: ``` SELECT SQL_NO_CACHE id, name FROM customer; ``` Aside from the query cache though, there's a lot more going on inside MySQL to speed things up, it caches other information about tables and indexes to speed up future queries. The first execution of the query will also warm up operating system file caches too. What you really need to do is [EXPLAIN](http://dev.mysql.com/doc/refman/5.1/en/explain.html) the query, and look at the number of rows the database engine needs to analyse. By exploring how it uses your table indexes (or not) you will be better informed as to what indexes might be missing, or alternative ways of structuring the query.
Once the table is loaded into memory, the query should take drastically less time. If the production box takes a long time to run the query every time, I'd start looking at memory usage. If you find that your production box is swapping a lot, I'd look at upgrading its RAM.
1,723,227
I have a table of a couple of million records. During production, we find that there is a particular type of query that is taking a few seconds to complete. When I try to reproduce the issue on my machine which has replicated production data, I ran the exact query (as obtained from the slow query log) in the mysql client, it took a few seconds as expected. If I then press up and enter to repeat it, it takes 0.01 seconds subsequently. I have looked up the docs to find out how to turn off caching, so that I can consistently reproduce the issue, and want to test if adding an index will help. Here is what I tried: RESET QUERY CACHE; FLUSH TABLES; However, after the above commands, running the same query again still only takes 0.01 seconds. I must be missing something. Any ideas?
2009/11/12
[ "https://Stackoverflow.com/questions/1723227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209731/" ]
You can tell the server not to place the result in the query cache by including [SQL\_NO\_CACHE](http://dev.mysql.com/doc/refman/5.1/en/query-cache-in-select.html) in the query: ``` SELECT SQL_NO_CACHE id, name FROM customer; ``` Aside from the query cache though, there's a lot more going on inside MySQL to speed things up, it caches other information about tables and indexes to speed up future queries. The first execution of the query will also warm up operating system file caches too. What you really need to do is [EXPLAIN](http://dev.mysql.com/doc/refman/5.1/en/explain.html) the query, and look at the number of rows the database engine needs to analyse. By exploring how it uses your table indexes (or not) you will be better informed as to what indexes might be missing, or alternative ways of structuring the query.
The have\_query\_cache server system variable indicates whether the query cache is available: ``` mysql> SHOW VARIABLES LIKE 'have_query_cache'; +------------------+-------+ | Variable_name | Value | +------------------+-------+ | have_query_cache | YES | +------------------+-------+ ``` When using a standard MySQL binary, this value is always YES, even if query caching is disabled. Several other system variables control query cache operation. These can be set in an option file or on the command line when starting mysqld. The query cache system variables all have names that begin with query\_cache\_. They are described briefly in Section 5.1.3, “Server System Variables”, with additional configuration information given here. <http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html>
1,723,227
I have a table of a couple of million records. During production, we find that there is a particular type of query that is taking a few seconds to complete. When I try to reproduce the issue on my machine which has replicated production data, I ran the exact query (as obtained from the slow query log) in the mysql client, it took a few seconds as expected. If I then press up and enter to repeat it, it takes 0.01 seconds subsequently. I have looked up the docs to find out how to turn off caching, so that I can consistently reproduce the issue, and want to test if adding an index will help. Here is what I tried: RESET QUERY CACHE; FLUSH TABLES; However, after the above commands, running the same query again still only takes 0.01 seconds. I must be missing something. Any ideas?
2009/11/12
[ "https://Stackoverflow.com/questions/1723227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209731/" ]
You can tell the server not to place the result in the query cache by including [SQL\_NO\_CACHE](http://dev.mysql.com/doc/refman/5.1/en/query-cache-in-select.html) in the query: ``` SELECT SQL_NO_CACHE id, name FROM customer; ``` Aside from the query cache though, there's a lot more going on inside MySQL to speed things up, it caches other information about tables and indexes to speed up future queries. The first execution of the query will also warm up operating system file caches too. What you really need to do is [EXPLAIN](http://dev.mysql.com/doc/refman/5.1/en/explain.html) the query, and look at the number of rows the database engine needs to analyse. By exploring how it uses your table indexes (or not) you will be better informed as to what indexes might be missing, or alternative ways of structuring the query.
If you're unable to turn it off you could invalidate the query by issuing a simple set of update statements swapping around a peice of data that'd have been selected by the query. So if you did. ``` update table set column = tmpval where id = 100; update table set column = originalval where id = 100; ``` Then when you query again it'll take a while. Also make sure you do an explain on the original query, it'll help you diagnose what's wrong faster than most things.
36,196,409
I am getting values in a format like this 00-C6 (Hex). It complains when I try to convert it to double (format execption). What to do? ``` public void check() { double low; double high; percentageCalculator(4095, 5, out low, out high); Dictionary[] A_1 = {Max_1, Min_1}; for (int i = 0; i < A_1.Length; i++) { if ((Convert.ToDouble(A_1[i].CurrentValue) <= low) || ((Convert.ToDouble(A_1[i].CurrentValue) >= high)) { Fault++; } } } ```
2016/03/24
[ "https://Stackoverflow.com/questions/36196409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6013907/" ]
Assuming the `Hex` `00-C6` `string` represents `Integer` value (because if it represents `floating-point` value like `float` or `double`, it must consists of `4-byte` or `8-byte`), then one way to process it is to split the `Hex string`: ``` string hexString = "00-C6"; string[] hexes = hexString.Split('-'); ``` Then you process each element in the `hexes` like this: ``` int hex0 = Convert.ToInt32(hexes[0], 16); int hex1 = Convert.ToInt32(hexes[1], 16); ``` If the hex is little endian, then your `double` value would be: ``` double d = hex0 << 8 + hex1; ``` And if it is big endtion, your `double` will be: ``` double d = hex1 << 8 + hex0; ``` The key here is to know that you can convert hex string representation to `Int` by using `Convert.ToInt32` with second argument as `16`. You can combine all the steps above into one liner if you feel like. Here I purposely break them down for the sake of presentation clarity.
Take a look at this piece of code: ``` string hexnumber = "00-c6"; double doubleValue = (double)Convert.ToInt32(hexnumber.Replace("-", ""), 16); ```
60,536,035
I am facing an issue with shopping cart. Unable to increase quantity of existing item in cart or add another item. On button click the addToCart function executes which takes a product. ``` const [cartItems, setCartItems] = useState([]) const addToCart = product => { console.log(product) // here I am getting the entire product const index = cartItems.findIndex(item => item._id === product._id); if (index === -1) { const updateCart = cartItems.concat({ ...product, quantity: 1 }); setCartItems(updateCart); } else { const updateCart = [...cartItems]; updateCart[index].quantity += 1; setCartItems(updateCart); } }; ``` I am getting only 1 quantity of product and if I add another product or increase quantity, it overwrites.
2020/03/04
[ "https://Stackoverflow.com/questions/60536035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13008960/" ]
Your else logic is wrong. You want to update your item quantity from carItems, before you spread it. Change: ``` const updateCart = [...cartItems]; updateCart[index].quantity += 1; setCartItems(updateCart); ``` to ``` cartItems[index].quantity += 1; const updateCart = [...cartItems]; setCartItems(updateCart); ``` Edit: See it in action below: ```js let cartItems = [{ _id: "1", name: "shoe", quantity: 1 }]; const addToCart = product => { console.log(product) // here I am getting the entire product const index = cartItems.findIndex(item => item._id === product._id); if (index === -1) { cartItems.push({ ...product, quantity: 1 }); const updateCart = [...cartItems]; console.log(updateCart); } else { cartItems[index].quantity += 1; const updateCart = [...cartItems]; console.log(updateCart); } }; var product1 = { _id: "1", name: "shoe" }; var product2 = { _id: "2", name: "apple" }; addToCart(product1); addToCart(product2); ```
Your code should work, is quite good ==================================== * probably testing method failed * problems were related to different parts of code ```js let cartItems = [ { _id: "1", name: "shoe", quantity: 1 } ]; console.log("START", JSON.stringify(cartItems), Array.isArray(cartItems)); const addToCart = product => { console.log(product); // here I am getting the entire product const index = cartItems.findIndex(item => item._id === product._id); if (index === -1) { const updateCart = cartItems.concat({ ...product, quantity: 1 }); cartItems = updateCart; console.log("ADD", JSON.stringify(cartItems), Array.isArray(cartItems)); } else { // original ... just works ... // const updateCart = [...cartItems]; // updateCart[index].quantity += 1; // ... this works, too // cartItems[index].quantity += 1; // const updateCart = [...cartItems]; // ... but this is safer (in react) as it replaces item with a new object const updateCart = [...cartItems]; // new object for replace existing one updateCart[index] = { ...updateCart[index], quantity: updateCart[index].quantity + 1 }; cartItems = updateCart; console.log("INC", JSON.stringify(cartItems), Array.isArray(cartItems)); } }; var product1 = { _id: "1", name: "shoe" }; var product2 = { _id: "2", name: "apple" }; addToCart(product1); addToCart(product2); addToCart(product1); console.log("END", JSON.stringify(cartItems), Array.isArray(cartItems)); ``` [working example](https://codesandbox.io/s/wild-cherry-to4p8) Is good enough? Not for react ----------------------------- Replacing item [-line] in cart with a new object can be required in react when you're rendering cart using components. f.e.: ``` cartItems.map( item => <CartOrderLine key={item._id} data={item} /> ) ``` `<CartOrderLine />` with the same `data` object ref (mutated `quantity` prop only, not replaced) won't be rerendered!
47,771,494
My Android app `webview` works fine with chrome version 61 or 62, but when I update to version 63. My `webview`does not store the history and `webView.canGoBack()` always returns `false`. But previous versions of chrome work fine. How to solve?
2017/12/12
[ "https://Stackoverflow.com/questions/47771494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5702991/" ]
This issue should be chromium's bug. We find out the same issue in our apps. the reason of this issue is we invoke Webview's loadUrl methond in shouldOverrideUrlLoading method, when we do that , webview can't go back in some version of chromium. The code below is my workaround: ``` public class WebViewBugFixDemo extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // todo : set your content layout final WebView webView = (WebView) findViewById(R.id.webview); final String indexUrl = "http://www.yourhost.com"; final String indexHost = Uri.parse(indexUrl).getHost(); webView.loadUrl(indexUrl); webView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { if (isSameWithIndexHost(url, indexHost)) { return false; } view.loadUrl(url); return true; } @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && request != null && request.getUrl() != null) { String url = request.getUrl().toString(); if (isSameWithIndexHost(url, indexHost)) { return false; } view.loadUrl(url); return true; } return super.shouldOverrideUrlLoading(view, request); } }); } /** * if the loadUrl's host is same with your index page's host, DON'T LOAD THE URL YOURSELF ! * @param loadUrl the new url to be loaded * @param indexHost Index page's host * @return */ private boolean isSameWithIndexHost(String loadUrl, String indexHost) { if (TextUtils.isEmpty(loadUrl)) { return false ; } Uri uri = Uri.parse(loadUrl) ; Log.e("", "### uri " + uri) ; return uri != null && !TextUtils.isEmpty(uri.getHost()) ? uri.getHost().equalsIgnoreCase(indexHost) : false ; } } ```
Even I was facing this issue. For now You can use intent in ouldOverrideUrlLoading(WebView view, String url){} function and super.onbackpressed() will do its job to maintain history. ``` public boolean shouldOverrideUrlLoading(WebView view, String url) { Intent intent = new Intent(MainActivity.this, MainActivity.class); intent.putExtra("postUrl", url); startActivity(intent); return true; } ```
69,725,727
Below comparison is giving false result in PowerShell , Want it to be true. ` operator is causing it to be false whereas for any other special character it is returning true. ``` > 'abc`@01' -like 'abc`@01' False ```
2021/10/26
[ "https://Stackoverflow.com/questions/69725727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17251840/" ]
`-like` is a wildcard comparison operator and ``` is a wildcard escape sequence. ``` PS ~> 'abc`@01' -like 'abc``@01' True ``` Use `-eq` if you want an exact string comparison without having to worry about escaping the reference string: ``` PS ~> 'abc`@01' -eq 'abc`@01' True ```
To *add to* [Mathias R. Jessen's helpful answer](https://stackoverflow.com/a/69725831/45375): On occasion you may be dealing with strings that should become *part* of a [wildcard expression](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Wildcards), but *themselves* should be treated *literally*, which requires *escaping* the wildcard metacharacters, `* ? [ ] ``, with ```. **[`[WildcardPattern]::Escape()`](https://learn.microsoft.com/en-US/dotnet/api/System.Management.Automation.WildcardPattern.Escape)** allows you to perform this escaping *programmatically* (which is especially helpful if the string was passed from the outside), as shown in the following example: ``` # The value to use *literally* as part of a wildcard expression below. $literalValue = '[1]' # Escape it for use in the wildcard expression. # -> '`[1`]' $escapedValue = [WildcardPattern]::Escape($literalValue) 'file[1]' -like ('*' + $escapedValue) # -> $true ``` Regrettably, as of PowerShell Core 7.2.0-rc.1, there is a **bug**: ``` itself, even thought it should be escaped as ````, is *not* escaped, which Mathias has reported in [GitHub issue #16306](https://github.com/PowerShell/PowerShell/issues/16306). In other words: with the specific wildcard pattern in your question, this technique wouldn't work.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
First, look into a UPS (un-interuptable power supply) Second, look into creating persistent transactions, transactions that will save early and often, but not commit until you tell it to. This goes a little beyond the typical transactions in TSQL.
If it's a hard power-cut (like the battery removed on a laptop while unplugged), then there's not much you can do other than write to disk every. step. of. the. way. (Talk about a performance hit.) And also make sure that you have something recorded to let the application know when it starts back up what it was in the middle of doing before, so it can either continue, or retry the operation. If it's a power-cut, like the power button being pressed to shutdown/sleep/hibernate the computer, then listen for the SystemEvents.PowerModeChanged event and act accordingly. Lastly, make sure that if your data would be corrupted if halfway written to a database, make sure your database writes are atomic (either all the changes happen and are accepted, or none of them are).
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
First, look into a UPS (un-interuptable power supply) Second, look into creating persistent transactions, transactions that will save early and often, but not commit until you tell it to. This goes a little beyond the typical transactions in TSQL.
PowerFailureException class will solve this. Actually just maintain power with a UPS. The only other option really is to maintain atomicity for database transactions.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
You can append the current information being received to the file system. It will be a performance hit, but will allow you to get back to the last item being captured. When the application starts detect if there is a pending file, and provide the option to recover. Load the data saved in the file appropriately. Once you have all the information, when you are doing the process that happens when paying, make sure to record any significant changes in the process atomically. If you are hitting external systems, record when you are initiating the operation and when it comes back right away. In the above there is always a window of time when it can fail, but you want to keep it as short as possible and to have enough information for the recovery processes. Worst case if the system can't automatically recover, you want it to have enough information to determine where in the process it stopped.
You might want to consider having your application use [SQLite](http://www.sqlite.org). They have some great info on their [when to use page](http://www.sqlite.org/whentouse.html). Some points that stand out are: > > * Updates happen atomically as application content is revised > * Content is updated continuously and atomically so that there is no work lost in the event of a power failure or crash. > > > I'm looking for a similar option for an application I am going to implement which will be used in a third world country where the power goes out frequently throughout the day....so far SQLite seems to stand out as a good possible choice. But at the end of the day, your choice will depend on your individual circumstances and requirements.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
If it's a hard power-cut (like the battery removed on a laptop while unplugged), then there's not much you can do other than write to disk every. step. of. the. way. (Talk about a performance hit.) And also make sure that you have something recorded to let the application know when it starts back up what it was in the middle of doing before, so it can either continue, or retry the operation. If it's a power-cut, like the power button being pressed to shutdown/sleep/hibernate the computer, then listen for the SystemEvents.PowerModeChanged event and act accordingly. Lastly, make sure that if your data would be corrupted if halfway written to a database, make sure your database writes are atomic (either all the changes happen and are accepted, or none of them are).
You might want to consider having your application use [SQLite](http://www.sqlite.org). They have some great info on their [when to use page](http://www.sqlite.org/whentouse.html). Some points that stand out are: > > * Updates happen atomically as application content is revised > * Content is updated continuously and atomically so that there is no work lost in the event of a power failure or crash. > > > I'm looking for a similar option for an application I am going to implement which will be used in a third world country where the power goes out frequently throughout the day....so far SQLite seems to stand out as a good possible choice. But at the end of the day, your choice will depend on your individual circumstances and requirements.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
If it's a hard power-cut (like the battery removed on a laptop while unplugged), then there's not much you can do other than write to disk every. step. of. the. way. (Talk about a performance hit.) And also make sure that you have something recorded to let the application know when it starts back up what it was in the middle of doing before, so it can either continue, or retry the operation. If it's a power-cut, like the power button being pressed to shutdown/sleep/hibernate the computer, then listen for the SystemEvents.PowerModeChanged event and act accordingly. Lastly, make sure that if your data would be corrupted if halfway written to a database, make sure your database writes are atomic (either all the changes happen and are accepted, or none of them are).
PowerFailureException class will solve this. Actually just maintain power with a UPS. The only other option really is to maintain atomicity for database transactions.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
If it's a hard power-cut (like the battery removed on a laptop while unplugged), then there's not much you can do other than write to disk every. step. of. the. way. (Talk about a performance hit.) And also make sure that you have something recorded to let the application know when it starts back up what it was in the middle of doing before, so it can either continue, or retry the operation. If it's a power-cut, like the power button being pressed to shutdown/sleep/hibernate the computer, then listen for the SystemEvents.PowerModeChanged event and act accordingly. Lastly, make sure that if your data would be corrupted if halfway written to a database, make sure your database writes are atomic (either all the changes happen and are accepted, or none of them are).
What you really want are atomic on disk transactions. There are many ways to perform these, but often times if you are using an existing database product it will be done for you. If you rolled your own database or file formats, you have some work cut our for you depending on your file format.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
You can append the current information being received to the file system. It will be a performance hit, but will allow you to get back to the last item being captured. When the application starts detect if there is a pending file, and provide the option to recover. Load the data saved in the file appropriately. Once you have all the information, when you are doing the process that happens when paying, make sure to record any significant changes in the process atomically. If you are hitting external systems, record when you are initiating the operation and when it comes back right away. In the above there is always a window of time when it can fail, but you want to keep it as short as possible and to have enough information for the recovery processes. Worst case if the system can't automatically recover, you want it to have enough information to determine where in the process it stopped.
What you really want are atomic on disk transactions. There are many ways to perform these, but often times if you are using an existing database product it will be done for you. If you rolled your own database or file formats, you have some work cut our for you depending on your file format.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
First, look into a UPS (un-interuptable power supply) Second, look into creating persistent transactions, transactions that will save early and often, but not commit until you tell it to. This goes a little beyond the typical transactions in TSQL.
You can append the current information being received to the file system. It will be a performance hit, but will allow you to get back to the last item being captured. When the application starts detect if there is a pending file, and provide the option to recover. Load the data saved in the file appropriately. Once you have all the information, when you are doing the process that happens when paying, make sure to record any significant changes in the process atomically. If you are hitting external systems, record when you are initiating the operation and when it comes back right away. In the above there is always a window of time when it can fail, but you want to keep it as short as possible and to have enough information for the recovery processes. Worst case if the system can't automatically recover, you want it to have enough information to determine where in the process it stopped.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
You can append the current information being received to the file system. It will be a performance hit, but will allow you to get back to the last item being captured. When the application starts detect if there is a pending file, and provide the option to recover. Load the data saved in the file appropriately. Once you have all the information, when you are doing the process that happens when paying, make sure to record any significant changes in the process atomically. If you are hitting external systems, record when you are initiating the operation and when it comes back right away. In the above there is always a window of time when it can fail, but you want to keep it as short as possible and to have enough information for the recovery processes. Worst case if the system can't automatically recover, you want it to have enough information to determine where in the process it stopped.
PowerFailureException class will solve this. Actually just maintain power with a UPS. The only other option really is to maintain atomicity for database transactions.
736,712
We are developing an RetailPOS .net (windows) application. One of the customer asks 'What will happen to current data being processed in the application when a power went off suddenly?', 'Will the application able to recover the unsaved data?' I am wondering, how this feature can be included in the .net application? Can some help me, what needs to be done for this?
2009/04/10
[ "https://Stackoverflow.com/questions/736712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53262/" ]
First, look into a UPS (un-interuptable power supply) Second, look into creating persistent transactions, transactions that will save early and often, but not commit until you tell it to. This goes a little beyond the typical transactions in TSQL.
What you really want are atomic on disk transactions. There are many ways to perform these, but often times if you are using an existing database product it will be done for you. If you rolled your own database or file formats, you have some work cut our for you depending on your file format.
42,207,975
this type of question has been asked many times. So apologies; I have searched hard to get an answer - but have not found anything that is close enough to my needs (and I am not sufficiently advanced **(I am a total newbie)** to customize an existing answer). So thanks in advance for any help. Here's my query: * I have 30 or so csv files and each contains between 500 and 15,000 rows. * Within each of them (in the 1st column) - are rows of alphabetical IDs (some contain underscores and some also have numbers). * I don't care about the unique IDs - but I would like to identify the duplicate IDs and the number of times they appear in all the different csv files. * Ideally I'd like the output for each duped ID to appear in a new csv file and be listed in 2 columns **("ID", "times\_seen")** It may be that I need to compile just 1 csv with all the IDs for your code to run properly - so please let me know if I need to do that I am using python 2.7 (a crawling script that I run needs this version, apparently). Thanks again
2017/02/13
[ "https://Stackoverflow.com/questions/42207975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7557229/" ]
It seems the most easy way to achieve want you want would make use of dictionaries. ``` import csv import os # Assuming all your csv are in a single directory we will iterate on the # files in this directory, selecting only those ending with .csv # to list files in the directory we will use the walk function in the # os module. os.walk(path_to_dir) returns a generator (a lazy iterator) # this generator generates tuples of the form root_directory, # list_of_directories, list_of_files. # So: declare the generator file_generator = os.walk("/path/to/csv/dir") # get the first values, as we won't recurse in subdirectories, we # only ned this one root_dir, list_of_dir, list_of_files = file_generator.next() # Now, we only keep the files ending with .csv. Let me break that down csv_list = [] for f in list_of_files: if f.endswith(".csv"): csv_list.append(f) # That's what was contained in the line # csv_list = [f for _, _, f in os.walk("/path/to/csv/dir").next() if f.endswith(".csv")] # The dictionary (key value map) that will contain the id count. ref_count = {} # We loop on all the csv filenames... for csv_file in csv_list: # open the files in read mode with open(csv_file, "r") as _: # build a csv reader around the file csv_reader = csv.reader(_) # loop on all the lines of the file, transformed to lists by the # csv reader for row in csv_reader: # If we haven't encountered this id yet, create # the corresponding entry in the dictionary. if not row[0] in ref_count: ref_count[row[0]] = 0 # increment the number of occurrences associated with # this id ref_count[row[0]]+=1 # now write to csv output with open("youroutput.csv", "w") as _: writer = csv.writer(_) for k, v in ref_count.iteritems(): # as requested we only take duplicates if v > 1: # use the writer to write the list to the file # the delimiters will be added by it. writer.writerow([k, v]) ``` You may need to tweek a little csv reader and writer options to fit your needs but this should do the trick. You'll find the documentation here <https://docs.python.org/2/library/csv.html>. I haven't tested it though. Correcting the little mistakes that may have occurred is left as a practicing exercise :).
Check out the pandas package. You can read an write csv files quite easily with it. <http://pandas.pydata.org/pandas-docs/stable/10min.html#csv> Then, when having the csv-content as a dataframe you convert it with the `as_matrix` function. Use the answers to this question to get the duplicates as a list. [Find and list duplicates in a list?](https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-python-list) I hope this helps
42,207,975
this type of question has been asked many times. So apologies; I have searched hard to get an answer - but have not found anything that is close enough to my needs (and I am not sufficiently advanced **(I am a total newbie)** to customize an existing answer). So thanks in advance for any help. Here's my query: * I have 30 or so csv files and each contains between 500 and 15,000 rows. * Within each of them (in the 1st column) - are rows of alphabetical IDs (some contain underscores and some also have numbers). * I don't care about the unique IDs - but I would like to identify the duplicate IDs and the number of times they appear in all the different csv files. * Ideally I'd like the output for each duped ID to appear in a new csv file and be listed in 2 columns **("ID", "times\_seen")** It may be that I need to compile just 1 csv with all the IDs for your code to run properly - so please let me know if I need to do that I am using python 2.7 (a crawling script that I run needs this version, apparently). Thanks again
2017/02/13
[ "https://Stackoverflow.com/questions/42207975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7557229/" ]
That's rather easy to achieve. It would look something like: ``` import os # Set to what kind of separator you have. '\t' for TAB delimiter = ',' # Dictionary to keep count of ids ids = {} # Iterate over files in a dir for in_file in os.listdir(os.curdir): # Check whether it is csv file (dummy way but it shall work for you) if in_file.endswith('.csv'): with open(in_file, 'r') as ifile: for line in ifile: my_id = line.strip().split(delimiter)[0] # If id does not exist in a dict = set count to 0 if my_id not in ids: ids[my_id] = 0 # Increment the count ids[my_id] += 1 # saves ids and counts to a file with open('ids_counts.csv', 'w') as ofile: for key, val in ids.iteritems(): # write down counts to a file using same column delimiter ofile.write('{}{}{}\n'.format(key, delimiter, value)) ```
Check out the pandas package. You can read an write csv files quite easily with it. <http://pandas.pydata.org/pandas-docs/stable/10min.html#csv> Then, when having the csv-content as a dataframe you convert it with the `as_matrix` function. Use the answers to this question to get the duplicates as a list. [Find and list duplicates in a list?](https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-python-list) I hope this helps
42,207,975
this type of question has been asked many times. So apologies; I have searched hard to get an answer - but have not found anything that is close enough to my needs (and I am not sufficiently advanced **(I am a total newbie)** to customize an existing answer). So thanks in advance for any help. Here's my query: * I have 30 or so csv files and each contains between 500 and 15,000 rows. * Within each of them (in the 1st column) - are rows of alphabetical IDs (some contain underscores and some also have numbers). * I don't care about the unique IDs - but I would like to identify the duplicate IDs and the number of times they appear in all the different csv files. * Ideally I'd like the output for each duped ID to appear in a new csv file and be listed in 2 columns **("ID", "times\_seen")** It may be that I need to compile just 1 csv with all the IDs for your code to run properly - so please let me know if I need to do that I am using python 2.7 (a crawling script that I run needs this version, apparently). Thanks again
2017/02/13
[ "https://Stackoverflow.com/questions/42207975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7557229/" ]
It seems the most easy way to achieve want you want would make use of dictionaries. ``` import csv import os # Assuming all your csv are in a single directory we will iterate on the # files in this directory, selecting only those ending with .csv # to list files in the directory we will use the walk function in the # os module. os.walk(path_to_dir) returns a generator (a lazy iterator) # this generator generates tuples of the form root_directory, # list_of_directories, list_of_files. # So: declare the generator file_generator = os.walk("/path/to/csv/dir") # get the first values, as we won't recurse in subdirectories, we # only ned this one root_dir, list_of_dir, list_of_files = file_generator.next() # Now, we only keep the files ending with .csv. Let me break that down csv_list = [] for f in list_of_files: if f.endswith(".csv"): csv_list.append(f) # That's what was contained in the line # csv_list = [f for _, _, f in os.walk("/path/to/csv/dir").next() if f.endswith(".csv")] # The dictionary (key value map) that will contain the id count. ref_count = {} # We loop on all the csv filenames... for csv_file in csv_list: # open the files in read mode with open(csv_file, "r") as _: # build a csv reader around the file csv_reader = csv.reader(_) # loop on all the lines of the file, transformed to lists by the # csv reader for row in csv_reader: # If we haven't encountered this id yet, create # the corresponding entry in the dictionary. if not row[0] in ref_count: ref_count[row[0]] = 0 # increment the number of occurrences associated with # this id ref_count[row[0]]+=1 # now write to csv output with open("youroutput.csv", "w") as _: writer = csv.writer(_) for k, v in ref_count.iteritems(): # as requested we only take duplicates if v > 1: # use the writer to write the list to the file # the delimiters will be added by it. writer.writerow([k, v]) ``` You may need to tweek a little csv reader and writer options to fit your needs but this should do the trick. You'll find the documentation here <https://docs.python.org/2/library/csv.html>. I haven't tested it though. Correcting the little mistakes that may have occurred is left as a practicing exercise :).
That's rather easy to achieve. It would look something like: ``` import os # Set to what kind of separator you have. '\t' for TAB delimiter = ',' # Dictionary to keep count of ids ids = {} # Iterate over files in a dir for in_file in os.listdir(os.curdir): # Check whether it is csv file (dummy way but it shall work for you) if in_file.endswith('.csv'): with open(in_file, 'r') as ifile: for line in ifile: my_id = line.strip().split(delimiter)[0] # If id does not exist in a dict = set count to 0 if my_id not in ids: ids[my_id] = 0 # Increment the count ids[my_id] += 1 # saves ids and counts to a file with open('ids_counts.csv', 'w') as ofile: for key, val in ids.iteritems(): # write down counts to a file using same column delimiter ofile.write('{}{}{}\n'.format(key, delimiter, value)) ```
42,207,975
this type of question has been asked many times. So apologies; I have searched hard to get an answer - but have not found anything that is close enough to my needs (and I am not sufficiently advanced **(I am a total newbie)** to customize an existing answer). So thanks in advance for any help. Here's my query: * I have 30 or so csv files and each contains between 500 and 15,000 rows. * Within each of them (in the 1st column) - are rows of alphabetical IDs (some contain underscores and some also have numbers). * I don't care about the unique IDs - but I would like to identify the duplicate IDs and the number of times they appear in all the different csv files. * Ideally I'd like the output for each duped ID to appear in a new csv file and be listed in 2 columns **("ID", "times\_seen")** It may be that I need to compile just 1 csv with all the IDs for your code to run properly - so please let me know if I need to do that I am using python 2.7 (a crawling script that I run needs this version, apparently). Thanks again
2017/02/13
[ "https://Stackoverflow.com/questions/42207975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7557229/" ]
It seems the most easy way to achieve want you want would make use of dictionaries. ``` import csv import os # Assuming all your csv are in a single directory we will iterate on the # files in this directory, selecting only those ending with .csv # to list files in the directory we will use the walk function in the # os module. os.walk(path_to_dir) returns a generator (a lazy iterator) # this generator generates tuples of the form root_directory, # list_of_directories, list_of_files. # So: declare the generator file_generator = os.walk("/path/to/csv/dir") # get the first values, as we won't recurse in subdirectories, we # only ned this one root_dir, list_of_dir, list_of_files = file_generator.next() # Now, we only keep the files ending with .csv. Let me break that down csv_list = [] for f in list_of_files: if f.endswith(".csv"): csv_list.append(f) # That's what was contained in the line # csv_list = [f for _, _, f in os.walk("/path/to/csv/dir").next() if f.endswith(".csv")] # The dictionary (key value map) that will contain the id count. ref_count = {} # We loop on all the csv filenames... for csv_file in csv_list: # open the files in read mode with open(csv_file, "r") as _: # build a csv reader around the file csv_reader = csv.reader(_) # loop on all the lines of the file, transformed to lists by the # csv reader for row in csv_reader: # If we haven't encountered this id yet, create # the corresponding entry in the dictionary. if not row[0] in ref_count: ref_count[row[0]] = 0 # increment the number of occurrences associated with # this id ref_count[row[0]]+=1 # now write to csv output with open("youroutput.csv", "w") as _: writer = csv.writer(_) for k, v in ref_count.iteritems(): # as requested we only take duplicates if v > 1: # use the writer to write the list to the file # the delimiters will be added by it. writer.writerow([k, v]) ``` You may need to tweek a little csv reader and writer options to fit your needs but this should do the trick. You'll find the documentation here <https://docs.python.org/2/library/csv.html>. I haven't tested it though. Correcting the little mistakes that may have occurred is left as a practicing exercise :).
As you are a newbie, Ill try to give some directions instead of posting an answer. Mainly because this is not a "code this for me" platform. Python has a library called [csv](https://docs.python.org/2/library/csv.html), that allows to read data from CSV files (Boom!, surprised?). This library allows you to read the file. Start by reading the file (preferably an example file that you create with just 10 or so rows and then increase the amount of rows or use a for loop to iterate over different files). The examples in the bottom of the page that I linked will help you printing this info. As you will see, the output you get from this library is a list with all the elements of each row. Your next step should be extracting just the ID that you are interested in. Next logical step is counting the amount of appearances. There is also a class from the standard library called [counter](https://docs.python.org/2/library/collections.html#collections.Counter). They have a method called `update` that you can use as follows: ``` from collections import Counter c = Counter() c.update(['safddsfasdf']) c # Counter({'safddsfasdf': 1}) c['safddsfasdf'] # 1 c.update(['safddsfasdf']) c # Counter({'safddsfasdf': 2}) c['safddsfasdf'] # 2 c.update(['fdf']) c # Counter({'safddsfasdf': 2, 'fdf': 1}) c['fdf'] # 1 ``` So basically you will have to pass it a list with the elements you want to count (you could have more than 1 id in the list, for exampling reading 10 IDs before inserting them, for improved efficiency, but remember not constructing a thousands of elements list if you are seeking good memory behaviour). If you try this and get into some trouble come back and we will help further. Edit ---- **Spoiler alert:** *I decided to give a full answer to the problem, please avoid it if you want to find your own solution and learn Python in the progress.* ``` # The csv module will help us read and write to the files from csv import reader, writer # The collections module has a useful type called Counter that fulfills our needs from collections import Counter # Getting the names/paths of the files is not this question goal, # so I'll just have them in a list files = [ "file_1.csv", "file_2.csv", ] # The output file name/path will also be stored in a variable output = "output.csv" # We create the item that is gonna count for us appearances = Counter() # Now we will loop each file for file in files: # We open the file in reading mode and get a handle with open(file, "r") as file_h: # We create a csv parser from the handle file_reader = reader(file_h) # Here you may need to do something if your first row is a header # We loop over all the rows for row in file_reader: # We insert the id into the counter appearances.update(row[:1]) # row[:1] will get explained afterwards, it is the first column of the row in list form # Now we will open/create the output file and get a handle with open(output, "w") as file_h: # We create a csv parser for the handle, this time to write file_writer = writer(file_h) # If you want to insert a header to the output file this is the place # We loop through our Counter object to write them: # here we have different options, if you want them sorted # by number of appearances Counter.most_common() is your friend, # if you dont care about the order you can use the Counter object # as if it was a normal dict # Option 1: ordered for id_and_times in apearances.most_common(): # id_and_times is a tuple with the id and the times it appears, # so we check the second element (they start at 0) if id_and_times[1] == 1: # As they are ordered, we can stop the loop when we reach # the first 1 to finish the earliest possible. break # As we have ended the loop if it appears once, # only duplicate IDs will reach to this point file_writer.writerow(id_and_times) # Option 2: unordered for id_and_times in apearances.iteritems(): # This time we can not stop the loop as they are unordered, # so we must check them all if id_and_times[1] > 1: file_writer.writerow(id_and_times) ``` I offered 2 options, printing them ordered (based on [Counter.most\_common() doc](https://docs.python.org/2/library/collections.html#collections.Counter.most_common)) and unoredered (based on normal dict method dict.iteritems()). Choose one. From a speed point of view I'm not sure which one would be faster, as one first needs to order the Counter but also stops looping when finding the first element non-duplicated while the second doesn't need to order the elements but needs to loop every ID. The speed will probably be dependant on your data. About the `row[:1]` thingy: * `row` is a list * You can get a subset of a list telling the initial and final positions * In this case the initial position is omited, so it defaults to the start * The final position is 1, so just the first element gets selected * So the output is another list with just the first element * `row[:1] == [row[0]]` They have the same output, getting a sublist of only the same element is the same that constructing a new list with only the first element
42,207,975
this type of question has been asked many times. So apologies; I have searched hard to get an answer - but have not found anything that is close enough to my needs (and I am not sufficiently advanced **(I am a total newbie)** to customize an existing answer). So thanks in advance for any help. Here's my query: * I have 30 or so csv files and each contains between 500 and 15,000 rows. * Within each of them (in the 1st column) - are rows of alphabetical IDs (some contain underscores and some also have numbers). * I don't care about the unique IDs - but I would like to identify the duplicate IDs and the number of times they appear in all the different csv files. * Ideally I'd like the output for each duped ID to appear in a new csv file and be listed in 2 columns **("ID", "times\_seen")** It may be that I need to compile just 1 csv with all the IDs for your code to run properly - so please let me know if I need to do that I am using python 2.7 (a crawling script that I run needs this version, apparently). Thanks again
2017/02/13
[ "https://Stackoverflow.com/questions/42207975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7557229/" ]
That's rather easy to achieve. It would look something like: ``` import os # Set to what kind of separator you have. '\t' for TAB delimiter = ',' # Dictionary to keep count of ids ids = {} # Iterate over files in a dir for in_file in os.listdir(os.curdir): # Check whether it is csv file (dummy way but it shall work for you) if in_file.endswith('.csv'): with open(in_file, 'r') as ifile: for line in ifile: my_id = line.strip().split(delimiter)[0] # If id does not exist in a dict = set count to 0 if my_id not in ids: ids[my_id] = 0 # Increment the count ids[my_id] += 1 # saves ids and counts to a file with open('ids_counts.csv', 'w') as ofile: for key, val in ids.iteritems(): # write down counts to a file using same column delimiter ofile.write('{}{}{}\n'.format(key, delimiter, value)) ```
As you are a newbie, Ill try to give some directions instead of posting an answer. Mainly because this is not a "code this for me" platform. Python has a library called [csv](https://docs.python.org/2/library/csv.html), that allows to read data from CSV files (Boom!, surprised?). This library allows you to read the file. Start by reading the file (preferably an example file that you create with just 10 or so rows and then increase the amount of rows or use a for loop to iterate over different files). The examples in the bottom of the page that I linked will help you printing this info. As you will see, the output you get from this library is a list with all the elements of each row. Your next step should be extracting just the ID that you are interested in. Next logical step is counting the amount of appearances. There is also a class from the standard library called [counter](https://docs.python.org/2/library/collections.html#collections.Counter). They have a method called `update` that you can use as follows: ``` from collections import Counter c = Counter() c.update(['safddsfasdf']) c # Counter({'safddsfasdf': 1}) c['safddsfasdf'] # 1 c.update(['safddsfasdf']) c # Counter({'safddsfasdf': 2}) c['safddsfasdf'] # 2 c.update(['fdf']) c # Counter({'safddsfasdf': 2, 'fdf': 1}) c['fdf'] # 1 ``` So basically you will have to pass it a list with the elements you want to count (you could have more than 1 id in the list, for exampling reading 10 IDs before inserting them, for improved efficiency, but remember not constructing a thousands of elements list if you are seeking good memory behaviour). If you try this and get into some trouble come back and we will help further. Edit ---- **Spoiler alert:** *I decided to give a full answer to the problem, please avoid it if you want to find your own solution and learn Python in the progress.* ``` # The csv module will help us read and write to the files from csv import reader, writer # The collections module has a useful type called Counter that fulfills our needs from collections import Counter # Getting the names/paths of the files is not this question goal, # so I'll just have them in a list files = [ "file_1.csv", "file_2.csv", ] # The output file name/path will also be stored in a variable output = "output.csv" # We create the item that is gonna count for us appearances = Counter() # Now we will loop each file for file in files: # We open the file in reading mode and get a handle with open(file, "r") as file_h: # We create a csv parser from the handle file_reader = reader(file_h) # Here you may need to do something if your first row is a header # We loop over all the rows for row in file_reader: # We insert the id into the counter appearances.update(row[:1]) # row[:1] will get explained afterwards, it is the first column of the row in list form # Now we will open/create the output file and get a handle with open(output, "w") as file_h: # We create a csv parser for the handle, this time to write file_writer = writer(file_h) # If you want to insert a header to the output file this is the place # We loop through our Counter object to write them: # here we have different options, if you want them sorted # by number of appearances Counter.most_common() is your friend, # if you dont care about the order you can use the Counter object # as if it was a normal dict # Option 1: ordered for id_and_times in apearances.most_common(): # id_and_times is a tuple with the id and the times it appears, # so we check the second element (they start at 0) if id_and_times[1] == 1: # As they are ordered, we can stop the loop when we reach # the first 1 to finish the earliest possible. break # As we have ended the loop if it appears once, # only duplicate IDs will reach to this point file_writer.writerow(id_and_times) # Option 2: unordered for id_and_times in apearances.iteritems(): # This time we can not stop the loop as they are unordered, # so we must check them all if id_and_times[1] > 1: file_writer.writerow(id_and_times) ``` I offered 2 options, printing them ordered (based on [Counter.most\_common() doc](https://docs.python.org/2/library/collections.html#collections.Counter.most_common)) and unoredered (based on normal dict method dict.iteritems()). Choose one. From a speed point of view I'm not sure which one would be faster, as one first needs to order the Counter but also stops looping when finding the first element non-duplicated while the second doesn't need to order the elements but needs to loop every ID. The speed will probably be dependant on your data. About the `row[:1]` thingy: * `row` is a list * You can get a subset of a list telling the initial and final positions * In this case the initial position is omited, so it defaults to the start * The final position is 1, so just the first element gets selected * So the output is another list with just the first element * `row[:1] == [row[0]]` They have the same output, getting a sublist of only the same element is the same that constructing a new list with only the first element
43,538,049
Why does block with text shift to the bottom? I know how to fix this issue (need to add "overflow: hidden" to the box), but I don't understand why it shift to the bottom, text inside the box is short, margins in browser-inspector are same as margins of example without text. [Example of the problem](https://codepen.io/AzatKaumov/pen/ZKQpOR/) HTML: ``` <div class="with-text"> <div class="box1"> SIMPLE TEXT </div> <div class="box2"> </div> </div> <div class="without-text"> <div class="box1"> </div> <div class="box2"> </div> </div> ``` CSS: ``` html, body { font-size: 10px; margin: 0; height: 100%; } .box1 { display: inline-block; margin: 5px; width: 50px; height: 50px; background: blue; /* Fix the problem */ /* overflow: hidden; */ color: white; } .box2 { display: inline-block; margin: 5px; width: 50px; height: 50px; background: red; } .with-text:before { display: block; content: "with-text"; text-transform: uppercase; margin: 1rem; } .with-text { box-sizing: border-box; height: 50%; border: 1px solid; } .without-text:before { display: block; content: "without text"; text-transform: uppercase; margin: 1rem; } .without-text { box-sizing: border-box; height: 50%; border: 2px solid black; } ```
2017/04/21
[ "https://Stackoverflow.com/questions/43538049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6151870/" ]
The problem is that by default vertical alignment of **inline elements** – **baseline**, The text inside element affects it and pushes div to the bottom. Use `vertical-align: top` to solve issue.
You can try to add vertical-align: ``` .box1 { display: inline-block; margin: 5px; width: 50px; height: 50px; background: blue; /* overflow: hidden; */ color: white; vertical-align:top; } ```
6,944
Occasionally, I see a question for which I don't know enough to write a good answer, but I happen to know something that I think would be useful for someone asking that question to know. * **[Example 1](https://rpg.stackexchange.com/questions/94633/how-to-create-a-custom-lycanthrope-in-heroforge-anew#comment218859_94633):** Arthaban wants to know how to do something in HeroForge. I don't know how to do the thing they want to do in HeroForge, so I can't write a good answer. But I *do* know the developer of HeroForge, who probably knows the answer. So I comment with a link to where they could get in touch with her. * **[Example 2](https://rpg.stackexchange.com/questions/98082/how-should-a-substitution-level-be-read#comment230523_98082):** HeyICanChan wants to know what exactly gets replaced when you take a substitution level. I can't find satisfactory rules text that would tell us what *actually* happens - but I have noticed a regularity that might help them out in ruling on these things in a way that makes sense, so I post a comment briefly mentioning it. --- On the one hand, these smell a little bit like [partial-answers-in-comments](https://rpg.meta.stackexchange.com/questions/6533/should-users-refrain-from-answers-or-partial-answers-in-comments/6534#6534). On the other hand, they're not really answers - they're just things that the question makes me think the asker would probably want to know. Are such comments acceptable? If not, is there a different venue by which it would be more appropriate to communicate this kind of information?
2017/04/13
[ "https://rpg.meta.stackexchange.com/questions/6944", "https://rpg.meta.stackexchange.com", "https://rpg.meta.stackexchange.com/users/30299/" ]
No, these aren't acceptable. These are partial answers in comments. A "lead", an "idea", and something that starts with "not an answer but..." are all answers in comments. Your options are: 1. Take the time to find out and write an answer. 2. Hit them up in chat. 3. Let it lie. Usually #3 is the best, because usually the helpful tip isn't really that helpful. Most of them are some variant on "LMGTFY". Your example of "you could go here and contact the developer" - realistically, they know that, or could with a token bit of research. But they're asking here. Everyone knows they could Google or go ask the author/designer on Twitter or go post on some other forum for thing X and ask there. But that's not an answer. Someone with the wherewithal to actually contact the developer and find out - *they* deserve to post an answer. Your second example - so there's a 50% chance the lead is wrong and deceptive as to an approach, because you don't really know the answer. I totally know everyone throwing out "tips" is doing it to be helpful. I am certainly not questioning any motives. But the fact is, these "tips" in comments are often a) wrong, b) pointless, and/or c) lead to comment arguments when people try to rebut them since comments don't have downvotes and their own comments like a proper answer does. In general, don't do it. The likelihood you have the critical piece of information some real answerer doesn't have is slight. And by posting a piece, you disincentivize someone from writing an actual answer around that, since "Well... It's there in a comment and they've already read it... I'll go spend my time somewhere else."
You do *technically* have a fourth option. If you actually have a good, substantial partial-answer but can't finish it off for whatever reason, consider posting it as a community wiki answer in its incomplete form. Community wiki answers should be rare, because we can generally answer a question without needing multiple different experts specialized in different areas, but they are there if you want to use them and posting partial answers is still officially okay. I don't think either of the test cases you mention pass muster for that, though.
41,493,243
I'm trying to remove a layout with the click of a button. I have this method in my MainActivity.java file: ``` public void goBack(View view) { TableLayout parent = (TableLayout) findViewById(R.id.activity_main); RelativeLayout child = (RelativeLayout) findViewById(R.id.activity_displayMessage); parent.removeView(child); } ``` It is fired when this button is clicked in the view I want to remove: ``` <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_removeView" android:onClick="goBack" /> ``` But it gives me this message: > > java.lang.IllegalStateException: Could not find method goBack(View) in > a parent or ancestor Context for android:onClick > > > But MainActivity is my main file for all my methods, so I'm not sure why it can't find it. Where should I put it so that it can be found? Thanks!
2017/01/05
[ "https://Stackoverflow.com/questions/41493243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/880874/" ]
You can do this by rebinding `sys.stdout`: ``` >>> def foo(): ... print('potato') ... >>> import sys, io >>> sys.stdout = io.StringIO() >>> foo() >>> val = sys.stdout.getvalue() >>> sys.stdout = sys.__stdout__ # restores original stdout >>> print(val) potato ``` For a nicer way to do it, consider writing a context manager. If you're on Python 3.4+, it's [already been written for you](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout). ``` >>> from contextlib import redirect_stdout >>> f = io.StringIO() >>> with redirect_stdout(f): ... foo() ... >>> print(f.getvalue()) potato ``` In the case that you are able to modify the function itself, it may be cleaner to allow a dependency injection of the output stream (this is just a fancy way of saying "passing arguments"): ``` def foo(file=sys.stdout): print('potato', file=file) ```
The sensible solution is simple and obvious: fix the function so that it returns the correct data instead of printing it. Else you *can* use the hack posted by wim but assuming you have the hand on the faulty function resorting to such a convoluted solution falls into the "WTF" category. NB of course if you don't have the hand on the function's code or it's just for a 5 minutes one-shot script, capturing `sys.stdout` is a handy fallback.
3,910,625
I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria? I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete. Any suggestions/ideas will be grately appreciated.
2010/10/11
[ "https://Stackoverflow.com/questions/3910625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/472777/" ]
Thats a apples to oranges question in my book. C/c++ don't have memory management at least not in the language thats your job. That being said java will allocate and destroy memory for you all the live long day but at the cost of control. For the standard business app this is not at issue. You are going to load some bloated 3rd party code either way, but when it counts you have more power in c/c++. You also have more power to shoot yourself in the foot.
As for internal memory management, Java has the best of the three, since it automates disposing of objects. If your question aims at performance, C or C++ would be a better bet. You would have to do all of the memory management yourself, but at the same time wouldn't have to wait for a Garbage Collector to do it's job. IMO it all depends on your approach: If you want to optimize your Application for Performance, go C or C++. If you don't want to worry about memory management yourself, use Java.
3,910,625
I just wanted to know which language has better memory management among C,C++ and Java,why is it so and it is based on what criteria? I know that Java uses garbage collection for freeing memory and C uses DMA functions.Does this make java better at memory management since it's handled automatically? I do not know C++ so I don't have much idea there,though I know it uses destructors and delete. Any suggestions/ideas will be grately appreciated.
2010/10/11
[ "https://Stackoverflow.com/questions/3910625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/472777/" ]
Java has memory management. C and C++ don't, so it's memory management is a function of the programmer.
Programmer managed memory in c and c++ is the root cause of many software bugs in programs written in those languages. This is one of the main reasons modern languages like Java and C# have garbage collection.