qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
7,852,466
How do I change `width` value assigned in `#center`? (I don't want to switch between CSS files just because 1 changed `width` value.) How do I dynamically change the value using Javascript? ```html <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <style type="text/css"> #main #center { width: 600px; // change width to 700 on click float: left; } #main #center .send { background: #fff; padding: 10px; position: relative; } #main #center .send .music { text-align: center; margin-bottom: 10px; } #main #center .send .write { font-family: georgia, serif; font-size: 150px; opacity: 0.2; } //....etc. </style> </head> <body> // change #center width to 700 <a href="#go2" onclick="how to change width of #center ???" ></a> </body> </html> ```
2011/10/21
[ "https://Stackoverflow.com/questions/7852466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007481/" ]
``` document.getElementById( 'center' ).style.width = "700px"; ```
``` <div onclick="changeWidth()" id="main"> Stuff </div> <div onclick="changeWidth()" id="center"> More Stuff </div> function changeWidth(){ this.style.width = "700px"; } ```
12,828,421
I need it because I recently made an app that saves an object containing all the user-generated data to `localStorage`, and encodes/decodes it with `JSON`. The bizarre thing is that for some reason, Internet Explorer has poor, if not zero, support for JSON ("JSON is not defined"), and I'm not up to trying to re-create the entire function. ``` stringify:function(x){ y='{' for(i in x){ reg=RegExp('\'','g') y+=',\''+i.replace(reg,'\\\'')+'\':\''+x[i].replace(reg,'\\\'')+'\'' } y=y.replace(',','') y+='}' return y } ``` This was my first attempt, but I had forgotten that the object has other objects inside it, which themselves contain objects, and kept getting an error which basically stemmed from trying to call the method `String.prototype.replace()` of an Object. Since I was kinda OCD with my code at the time, I actually do have the structure of the object saved in the source code: ``` /* Link Engine.data: Object: { X: Object: { [Each is a Paradigm, contains links] link.0:{ link:[link], title:[title], removed:[true/false], starred:[true/false] }, ... }, LSPAR: [Reserved] Object: { [Paradigm list and pointer contained here] key:[key], (this controls X) list:{ [listitem]:[listitem], ... } }, #CONFIG: [Reserved] Object: { [contains miscellaneous Config data] property:boolean/number/string, ... } */ ``` That's the basic data structure, `...` represents a repeating pattern. --- Edit 2019 --------- This whole question is an abomination, but I want to at least attempt to fix the bothersome documentation I wrote for my poorly-designed data structure so that it's more coherent: ``` Link { string link string title boolean removed boolean starred } Config { ... /* Just has a bunch of arbitrary fields; not important */ } WArray { string... [paradigm-name] /* Wasteful Array; an object of the form * { "a":"a", "b":"b", ... } */ } Paradigm { /* analogous to above "X: Object: {..." nonsense */ Link... [paradigm-name].[id] /* each key is of the form [paradigm-name].[id] and stores a Link * e.g. the first link in the "Example" paradigm would * be identified by the key "Example.0" */ } ParadigmList { string key /* name of selected paradigm */ WArray list /* list of paradigm names */ } LinkEngineData { Paradigm... [paradigm-name] ParadigmList LSPAR Config #CONFIG /* actual field name */ } ``` Hopefully now you can sort of parse what's going on. This syntax: ``` type... format ``` is meant to convey that objects of type `type` appear many times, like an array, except it isn't an array. As such, the fields don't have a name that is set-in-stone, hence ``` format: [descriptor1]text[descriptor2]text... ``` a format is used in place of an actual field name. This is what happens when you try to create a data structure without knowing what a data structure is. I did use the words "data" and "structure" adjacently in the original question, but it was pure coincidence. I didn't mean it like "this is the data structure I used"; I meant it like "this is the structure of my data". Anyways, here's how I would design it today: ``` Link { string url string title boolean starred } LinkGroup { string name Link[] links } Config { ... /* has whatever it needs to have */ } Data { int selGroup LinkGroup[] groups Config config } ``` That is all. --- If someone has the sourcecode of the actual JSON.stringify function, or knows a way to replicate it, then please put your answer. --- **EDIT (2013, probably)** I ended up dropping IE support and completely redesigning the app from the ground up; the new version is hosted [here](http://b1kmusic.koding.com/Misc/WebApps/Link_Saver.html). And it works with IE9 out of the box!
2012/10/10
[ "https://Stackoverflow.com/questions/12828421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175714/" ]
I think this is the best replacement: <http://bestiejs.github.com/json3/> It claims to be better than Crockford's JSON 2 for the following reasons (from their site): JSON 3... * Correctly serializes primitive wrapper objects ([Issue #28](https://github.com/douglascrockford/JSON-js/issues/28)). * Throws a TypeError when serializing cyclic structures (JSON 2 recurses until the call stack overflows). * Utilizes feature tests to detect broken or incomplete native JSON implementations (JSON 2 only checks for the presence of the native functions). The tests are only executed once at runtime, so there is no additional performance cost when parsing or serializing values. In contrast to JSON 2, JSON 3 does not... * Add toJSON() methods to the Boolean, Number, and String prototypes. These are not part of any standard, and are made redundant by the design of the stringify() implementation. * Add toJSON() or toISOString() methods to Date.prototype. See the note about date serialization below.
Try <https://github.com/douglascrockford/JSON-js>
12,828,421
I need it because I recently made an app that saves an object containing all the user-generated data to `localStorage`, and encodes/decodes it with `JSON`. The bizarre thing is that for some reason, Internet Explorer has poor, if not zero, support for JSON ("JSON is not defined"), and I'm not up to trying to re-create the entire function. ``` stringify:function(x){ y='{' for(i in x){ reg=RegExp('\'','g') y+=',\''+i.replace(reg,'\\\'')+'\':\''+x[i].replace(reg,'\\\'')+'\'' } y=y.replace(',','') y+='}' return y } ``` This was my first attempt, but I had forgotten that the object has other objects inside it, which themselves contain objects, and kept getting an error which basically stemmed from trying to call the method `String.prototype.replace()` of an Object. Since I was kinda OCD with my code at the time, I actually do have the structure of the object saved in the source code: ``` /* Link Engine.data: Object: { X: Object: { [Each is a Paradigm, contains links] link.0:{ link:[link], title:[title], removed:[true/false], starred:[true/false] }, ... }, LSPAR: [Reserved] Object: { [Paradigm list and pointer contained here] key:[key], (this controls X) list:{ [listitem]:[listitem], ... } }, #CONFIG: [Reserved] Object: { [contains miscellaneous Config data] property:boolean/number/string, ... } */ ``` That's the basic data structure, `...` represents a repeating pattern. --- Edit 2019 --------- This whole question is an abomination, but I want to at least attempt to fix the bothersome documentation I wrote for my poorly-designed data structure so that it's more coherent: ``` Link { string link string title boolean removed boolean starred } Config { ... /* Just has a bunch of arbitrary fields; not important */ } WArray { string... [paradigm-name] /* Wasteful Array; an object of the form * { "a":"a", "b":"b", ... } */ } Paradigm { /* analogous to above "X: Object: {..." nonsense */ Link... [paradigm-name].[id] /* each key is of the form [paradigm-name].[id] and stores a Link * e.g. the first link in the "Example" paradigm would * be identified by the key "Example.0" */ } ParadigmList { string key /* name of selected paradigm */ WArray list /* list of paradigm names */ } LinkEngineData { Paradigm... [paradigm-name] ParadigmList LSPAR Config #CONFIG /* actual field name */ } ``` Hopefully now you can sort of parse what's going on. This syntax: ``` type... format ``` is meant to convey that objects of type `type` appear many times, like an array, except it isn't an array. As such, the fields don't have a name that is set-in-stone, hence ``` format: [descriptor1]text[descriptor2]text... ``` a format is used in place of an actual field name. This is what happens when you try to create a data structure without knowing what a data structure is. I did use the words "data" and "structure" adjacently in the original question, but it was pure coincidence. I didn't mean it like "this is the data structure I used"; I meant it like "this is the structure of my data". Anyways, here's how I would design it today: ``` Link { string url string title boolean starred } LinkGroup { string name Link[] links } Config { ... /* has whatever it needs to have */ } Data { int selGroup LinkGroup[] groups Config config } ``` That is all. --- If someone has the sourcecode of the actual JSON.stringify function, or knows a way to replicate it, then please put your answer. --- **EDIT (2013, probably)** I ended up dropping IE support and completely redesigning the app from the ground up; the new version is hosted [here](http://b1kmusic.koding.com/Misc/WebApps/Link_Saver.html). And it works with IE9 out of the box!
2012/10/10
[ "https://Stackoverflow.com/questions/12828421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175714/" ]
I think this is the best replacement: <http://bestiejs.github.com/json3/> It claims to be better than Crockford's JSON 2 for the following reasons (from their site): JSON 3... * Correctly serializes primitive wrapper objects ([Issue #28](https://github.com/douglascrockford/JSON-js/issues/28)). * Throws a TypeError when serializing cyclic structures (JSON 2 recurses until the call stack overflows). * Utilizes feature tests to detect broken or incomplete native JSON implementations (JSON 2 only checks for the presence of the native functions). The tests are only executed once at runtime, so there is no additional performance cost when parsing or serializing values. In contrast to JSON 2, JSON 3 does not... * Add toJSON() methods to the Boolean, Number, and String prototypes. These are not part of any standard, and are made redundant by the design of the stringify() implementation. * Add toJSON() or toISOString() methods to Date.prototype. See the note about date serialization below.
I think you should use the json2.js library: <https://github.com/douglascrockford/JSON-js>
12,828,421
I need it because I recently made an app that saves an object containing all the user-generated data to `localStorage`, and encodes/decodes it with `JSON`. The bizarre thing is that for some reason, Internet Explorer has poor, if not zero, support for JSON ("JSON is not defined"), and I'm not up to trying to re-create the entire function. ``` stringify:function(x){ y='{' for(i in x){ reg=RegExp('\'','g') y+=',\''+i.replace(reg,'\\\'')+'\':\''+x[i].replace(reg,'\\\'')+'\'' } y=y.replace(',','') y+='}' return y } ``` This was my first attempt, but I had forgotten that the object has other objects inside it, which themselves contain objects, and kept getting an error which basically stemmed from trying to call the method `String.prototype.replace()` of an Object. Since I was kinda OCD with my code at the time, I actually do have the structure of the object saved in the source code: ``` /* Link Engine.data: Object: { X: Object: { [Each is a Paradigm, contains links] link.0:{ link:[link], title:[title], removed:[true/false], starred:[true/false] }, ... }, LSPAR: [Reserved] Object: { [Paradigm list and pointer contained here] key:[key], (this controls X) list:{ [listitem]:[listitem], ... } }, #CONFIG: [Reserved] Object: { [contains miscellaneous Config data] property:boolean/number/string, ... } */ ``` That's the basic data structure, `...` represents a repeating pattern. --- Edit 2019 --------- This whole question is an abomination, but I want to at least attempt to fix the bothersome documentation I wrote for my poorly-designed data structure so that it's more coherent: ``` Link { string link string title boolean removed boolean starred } Config { ... /* Just has a bunch of arbitrary fields; not important */ } WArray { string... [paradigm-name] /* Wasteful Array; an object of the form * { "a":"a", "b":"b", ... } */ } Paradigm { /* analogous to above "X: Object: {..." nonsense */ Link... [paradigm-name].[id] /* each key is of the form [paradigm-name].[id] and stores a Link * e.g. the first link in the "Example" paradigm would * be identified by the key "Example.0" */ } ParadigmList { string key /* name of selected paradigm */ WArray list /* list of paradigm names */ } LinkEngineData { Paradigm... [paradigm-name] ParadigmList LSPAR Config #CONFIG /* actual field name */ } ``` Hopefully now you can sort of parse what's going on. This syntax: ``` type... format ``` is meant to convey that objects of type `type` appear many times, like an array, except it isn't an array. As such, the fields don't have a name that is set-in-stone, hence ``` format: [descriptor1]text[descriptor2]text... ``` a format is used in place of an actual field name. This is what happens when you try to create a data structure without knowing what a data structure is. I did use the words "data" and "structure" adjacently in the original question, but it was pure coincidence. I didn't mean it like "this is the data structure I used"; I meant it like "this is the structure of my data". Anyways, here's how I would design it today: ``` Link { string url string title boolean starred } LinkGroup { string name Link[] links } Config { ... /* has whatever it needs to have */ } Data { int selGroup LinkGroup[] groups Config config } ``` That is all. --- If someone has the sourcecode of the actual JSON.stringify function, or knows a way to replicate it, then please put your answer. --- **EDIT (2013, probably)** I ended up dropping IE support and completely redesigning the app from the ground up; the new version is hosted [here](http://b1kmusic.koding.com/Misc/WebApps/Link_Saver.html). And it works with IE9 out of the box!
2012/10/10
[ "https://Stackoverflow.com/questions/12828421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175714/" ]
Try <https://github.com/douglascrockford/JSON-js>
I think you should use the json2.js library: <https://github.com/douglascrockford/JSON-js>
170,286
A changeling's Change Appearance states: > > You also can't appear as a creature of a different size than you, and your basic shape stays the same; if you’re bipedal, you can’t use this trait to become quadrupedal, for instance. > > > But seeing that with a druid's Wild Shape can change you into a creature that is quadrupedal and a differerent size than yourself, does this mean that after that you can change into another quadrupedal creature of that same size? Let's say you are a normal 2 legged medium changeling and you Wild Shape into a 4 legged large [saber-toothed tiger](https://www.dndbeyond.com/monsters/saber-toothed-tiger). Does that mean that you could use the Change Appearance feature of the changeling to change into another 4 legged walking large creature like a [dire wolf](https://www.dndbeyond.com/monsters/dire-wolf)? Could you also Change Appearance into a creature outside of the possible druid Wild Shapes? For example a creature with a higher CR?
2020/06/11
[ "https://rpg.stackexchange.com/questions/170286", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/45589/" ]
According to RAW, you can't Change Appearance while Wild Shaped =============================================================== The rules for Wild Shape states concerning racial features is: > > You retain the benefit of any features from your class, race, or other source and can use them *if the new form is physically capable of doing so*. However, you can’t use any of your special senses, such as darkvision, unless your new form also has that sense. [Emphasis mine] > > > The crux is the highlighted clause: The creature assumed by Wild Shape is usually not physically capable of changing its appearance in the same way a Changeling can. This would mean the racial ability can't be used simultaneously with Wild Shape.
It is at the GM's discretion. ============================= The rules are somewhat unclear on this. While it is rather clear that *basic shape* was meant to refer to the changeling's, the part you cite somewhat contradicts this, by suggesting that a transformation quadruped -> quadruped works, especially so, since a changeling will by default never be a quadruped. I'd rule against the latter because RAI seems clear to me. If you rule otherwise, there is no reason to restrict the possibilities to wild shape forms so long as shape and size conform to the changeling's rules, such as one large quadruped to another one. **The CR is irrelevant when using change appearance** However you decide, the changeling's trait does not change any mechanics, only the appearance. If you decide that quadrupeds can be interchanged, you can transform from a riding horse to an owlbear for example, but the statistics then are still those of the horse.
170,286
A changeling's Change Appearance states: > > You also can't appear as a creature of a different size than you, and your basic shape stays the same; if you’re bipedal, you can’t use this trait to become quadrupedal, for instance. > > > But seeing that with a druid's Wild Shape can change you into a creature that is quadrupedal and a differerent size than yourself, does this mean that after that you can change into another quadrupedal creature of that same size? Let's say you are a normal 2 legged medium changeling and you Wild Shape into a 4 legged large [saber-toothed tiger](https://www.dndbeyond.com/monsters/saber-toothed-tiger). Does that mean that you could use the Change Appearance feature of the changeling to change into another 4 legged walking large creature like a [dire wolf](https://www.dndbeyond.com/monsters/dire-wolf)? Could you also Change Appearance into a creature outside of the possible druid Wild Shapes? For example a creature with a higher CR?
2020/06/11
[ "https://rpg.stackexchange.com/questions/170286", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/45589/" ]
It is at the GM's discretion. ============================= The rules are somewhat unclear on this. While it is rather clear that *basic shape* was meant to refer to the changeling's, the part you cite somewhat contradicts this, by suggesting that a transformation quadruped -> quadruped works, especially so, since a changeling will by default never be a quadruped. I'd rule against the latter because RAI seems clear to me. If you rule otherwise, there is no reason to restrict the possibilities to wild shape forms so long as shape and size conform to the changeling's rules, such as one large quadruped to another one. **The CR is irrelevant when using change appearance** However you decide, the changeling's trait does not change any mechanics, only the appearance. If you decide that quadrupeds can be interchanged, you can transform from a riding horse to an owlbear for example, but the statistics then are still those of the horse.
I would argue that there is no restriction from a Changeling using Shapechanger while in Wild Shape. If the verbiage that is italicized above is relevant, then it would also prevent the druid from using a second use of Wild Shape while in a wild shape form, and it has already been clarified that this is possible: [https://rpg.stackexchange.com/questions/96375/can-a-druid-wildshape-again-whilst-still-in-animal-form#:~:text=A%20druid%20can%20Wild%20Shape%20to%20a%20new%20form%20without%20reverting](https://rpg.stackexchange.com/questions/96375/can-a-druid-wildshape-again-whilst-still-in-animal-form#:%7E:text=A%20druid%20can%20Wild%20Shape%20to%20a%20new%20form%20without%20reverting). Also, Keith Baker (who created Eberron) speaks about a Changeling Druid here: <http://keith-baker.com/faq-changelings/>
170,286
A changeling's Change Appearance states: > > You also can't appear as a creature of a different size than you, and your basic shape stays the same; if you’re bipedal, you can’t use this trait to become quadrupedal, for instance. > > > But seeing that with a druid's Wild Shape can change you into a creature that is quadrupedal and a differerent size than yourself, does this mean that after that you can change into another quadrupedal creature of that same size? Let's say you are a normal 2 legged medium changeling and you Wild Shape into a 4 legged large [saber-toothed tiger](https://www.dndbeyond.com/monsters/saber-toothed-tiger). Does that mean that you could use the Change Appearance feature of the changeling to change into another 4 legged walking large creature like a [dire wolf](https://www.dndbeyond.com/monsters/dire-wolf)? Could you also Change Appearance into a creature outside of the possible druid Wild Shapes? For example a creature with a higher CR?
2020/06/11
[ "https://rpg.stackexchange.com/questions/170286", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/45589/" ]
According to RAW, you can't Change Appearance while Wild Shaped =============================================================== The rules for Wild Shape states concerning racial features is: > > You retain the benefit of any features from your class, race, or other source and can use them *if the new form is physically capable of doing so*. However, you can’t use any of your special senses, such as darkvision, unless your new form also has that sense. [Emphasis mine] > > > The crux is the highlighted clause: The creature assumed by Wild Shape is usually not physically capable of changing its appearance in the same way a Changeling can. This would mean the racial ability can't be used simultaneously with Wild Shape.
I would argue that there is no restriction from a Changeling using Shapechanger while in Wild Shape. If the verbiage that is italicized above is relevant, then it would also prevent the druid from using a second use of Wild Shape while in a wild shape form, and it has already been clarified that this is possible: [https://rpg.stackexchange.com/questions/96375/can-a-druid-wildshape-again-whilst-still-in-animal-form#:~:text=A%20druid%20can%20Wild%20Shape%20to%20a%20new%20form%20without%20reverting](https://rpg.stackexchange.com/questions/96375/can-a-druid-wildshape-again-whilst-still-in-animal-form#:%7E:text=A%20druid%20can%20Wild%20Shape%20to%20a%20new%20form%20without%20reverting). Also, Keith Baker (who created Eberron) speaks about a Changeling Druid here: <http://keith-baker.com/faq-changelings/>
43,501,652
I have an app which creates several surveys with random survey ids. As the ids are generated in the backend they are set in the controller. I read the documentation on that, however I do not really understand how to set the routeparams in order to always reach the page /survey/:surveryID. Here is my code so far: App Config: ``` ... .when('/survey/:surveyId', { templateUrl: 'views/survey.html', controller: 'SurveyCtrl', controllerAs: 'survey' }) ``` Controller: ``` function SurveyCtrl($scope, RequestService, _, $location, $routeParams) { $scope.go = function () { $location.path('/#/survey/' + Math.random()); }; } ``` View with the link to /survey/:surveyId: ``` <div> <md-button ng-click="go()">Enter Survey</md-button> </div> ``` I know that this is not the right way and it is not even working. Can someone tell me how to dynamically create these params and set them in the controller so I can access the link with a button and then when clicked reach the survey/:surveyId page?
2017/04/19
[ "https://Stackoverflow.com/questions/43501652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4415232/" ]
To get your work done, ``` $location.path('/survey/' + Math.random()); ``` You can use search method to pass params as well, ``` $location.path('/myURL/').search({param: 'value'}); ``` $location methods are chainable. this produce : ``` /myURL/?param=value ```
You could also use the `updateParams` method for that: `$route.updateParams({'surveryID': Math.random()});` And access the data using `$routeParams.surveryID`
57,988,960
I'm just starting with `node.js` and `express.js` and trying to create a listener with port 3000 using `app.listen(3000)`. The problem I'm having is when I first load the app, the browser loads it just fine, but when I make some changes, save the file and reload the browser, it doesn't show any changes. Mean it is just showing the first loaded version. I have read many Q/A but none provide the specific solution. I don't know what I'm missing or doing wrong. Any help would be much appreciated, or please let me know if I explained my question properly.
2019/09/18
[ "https://Stackoverflow.com/questions/57988960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10045025/" ]
You are looking for a tool like [nodemon](https://github.com/remy/nodemon) which does the server reloading. Unfortunately, nodemon doesn't reload the page itself, you still have to do it manually. Perhaps [browsersync](https://browsersync.io/) can help with that: it can be used for frontend development with live reloading, but I'm not sure if it works for fullstack reloading. The setup may depend on your pipeline (gulp/webpack/...), see for instance, [this post](https://stackoverflow.com/q/37014942/3995261) for nodemon + gulp + browsersync combination.
you have to restart the server or install nodemon
57,988,960
I'm just starting with `node.js` and `express.js` and trying to create a listener with port 3000 using `app.listen(3000)`. The problem I'm having is when I first load the app, the browser loads it just fine, but when I make some changes, save the file and reload the browser, it doesn't show any changes. Mean it is just showing the first loaded version. I have read many Q/A but none provide the specific solution. I don't know what I'm missing or doing wrong. Any help would be much appreciated, or please let me know if I explained my question properly.
2019/09/18
[ "https://Stackoverflow.com/questions/57988960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10045025/" ]
You are looking for a tool like [nodemon](https://github.com/remy/nodemon) which does the server reloading. Unfortunately, nodemon doesn't reload the page itself, you still have to do it manually. Perhaps [browsersync](https://browsersync.io/) can help with that: it can be used for frontend development with live reloading, but I'm not sure if it works for fullstack reloading. The setup may depend on your pipeline (gulp/webpack/...), see for instance, [this post](https://stackoverflow.com/q/37014942/3995261) for nodemon + gulp + browsersync combination.
This might be a problem with your computer console, probably be an old mac, because I face the same problem as well, try and destroy all node action by using `killall node` for mac and for window computer `taskkill /im node.exe /F` this will terminate all node action on your computer, after restart the node server this should work if it doesn't kindly comment below
57,988,960
I'm just starting with `node.js` and `express.js` and trying to create a listener with port 3000 using `app.listen(3000)`. The problem I'm having is when I first load the app, the browser loads it just fine, but when I make some changes, save the file and reload the browser, it doesn't show any changes. Mean it is just showing the first loaded version. I have read many Q/A but none provide the specific solution. I don't know what I'm missing or doing wrong. Any help would be much appreciated, or please let me know if I explained my question properly.
2019/09/18
[ "https://Stackoverflow.com/questions/57988960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10045025/" ]
you have to restart the server or install nodemon
This might be a problem with your computer console, probably be an old mac, because I face the same problem as well, try and destroy all node action by using `killall node` for mac and for window computer `taskkill /im node.exe /F` this will terminate all node action on your computer, after restart the node server this should work if it doesn't kindly comment below
3,446,208
I have just started web development.I want to make a screen to do basic add modify and delete operation. The screen I've designed will have 3 tabs which will be add , display and delete.When I click on any of this tab a sub-screen should open for doing the operation accordingly. Another I thing I want to do is , I've a text field when I enter a number in it , I want to check for validation and tell him immediately if he's correct or not. What controls I need to know to do this or how should I go about doing this?
2010/08/10
[ "https://Stackoverflow.com/questions/3446208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415477/" ]
Follow this tutorial on ASP.NET MVC to get started in ASP.NET web development. <http://nerddinnerbook.s3.amazonaws.com/Intro.htm> The tutorial will show you how to create a database for your application and how to interact with it in code. It shows how to create views (web pages) and actions for Add, Read, Update and Delete operations.
Hmmm... Controls to use. How about a [FormView](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.formview.aspx) or [DetailsView](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsview.aspx), possibly a [DataGrid](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datagrid.aspx) and definitely some validators.. [RegularExpression](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.regularexpressionvalidator.aspx) and [Required](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.requiredfieldvalidator.aspx)... And maybe watch some Asp.Net vidos... There are plenty here: <http://www.asp.net/web-forms> <--- This is where you should start. Or you could use [MVC](http://www.asp.net/mvc) or [Dynamic Data](http://www.asp.net/dynamicdata) Lots of choices...
511,214
I'm looking for a word to refer to the visual appearance of a word only. I'll use an example to help explain what I mean: "bow" can refer to the action of bowing to someone, or to a bow that I add when wrapping a gift. "bow" and "bow" are homographs because they are spelled the same way, though they have different meanings and pronunciations, and we consider them two different words. Then, define a "qword" as an ordered set of letters (and diacritical marks) combined according to the conventions of English. "bow" and "bow" are two different words, but the same qword, since they are both "b", "o", and "w" combined in the same way and in the same order. And "résumé" and "resume" are different qwords since they appear differently in written English, though people often write "resume" when they mean "résumé", and we have no trouble understanding what they mean. Is there an existing English noun that means the same thing as "qword"? If there is none, a compound word or phrase would also be fine.
2019/09/11
[ "https://english.stackexchange.com/questions/511214", "https://english.stackexchange.com", "https://english.stackexchange.com/users/57530/" ]
*bow* is a "string", to start with. We are looking at "meaningful strings" in the context of the English language. A "meaningful string" *can* have more than one meaning. To be precise we could say a "meaningful character string".
Homograph is what you want: > > What are homonyms, homophones, and homographs? > Homonym can be troublesome because it may refer to three distinct classes of words. Homonyms may be words with identical pronunciations but different spellings and meanings, such as to, too, and two. Or they may be words with both identical pronunciations and identical spellings but different meanings, such as quail (the bird) and quail (to cringe). Finally, they may be words that are spelled alike but are different in pronunciation and meaning, such as the bow of a ship and bow that shoots arrows. The first and second types are sometimes called homophones, and the second and third types are sometimes called homographs--which makes naming the second type a bit confusing. Some language scholars prefer to limit homonym to the third type. > > > <https://www.merriam-webster.com/dictionary/homograph> From MW
25,275,308
This problem involves three Sheets (A, B, C) Sheet A contains a data table and in Column A has a list of Names Sheet B contains a data table (Similar not the same as B) and in Column A has a list of Names Sheet C is a sheet called Name Matching. I already have a Macro that copies the names in Column A from both Sheet A and B and pastes them in Column A of Sheet C. There are several duplicates after this is done due to the nature of the data from Sheet A and Sheet B. Currently I have to manually find the Duplicates in Sheet C and then go into Sheet B and delete the row that has the Duplicate Name. I would like any formulas that may help solve this. Specifically, a formula that finds the duplicate value on Sheet C and then goes to Sheet B and deletes the entire row of Data. UPDATE: SEE COMMENT BELOW
2014/08/12
[ "https://Stackoverflow.com/questions/25275308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3935336/" ]
``` $("h3 a:contains('Skin')").remove(); ``` You need to target the links within the h3. The link will contain the text.
What about changing the h3:contains to a:contains?
5,602,645
I'm creating a very simple PInvoke sample: ``` extern "C" __declspec(dllexport) int Add(int a, int b) { return a + b; } [DllImport("CommonNativeLib.dll")] extern public static int Add(int a, int b); return NativeMethods.Add(a, b); ``` But whenever I call the above `NativeMethods.Add` method I get the following managed debug assistant: > > PInvokeStackImbalance was detected > Message: A call to PInvoke function 'CommonManagedLib!CommonManagedLib.NativeMethods::Add' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature. > > > The call then completes with the expected return value, but having the MDA message appear is both annoying and worrying - I don't fully understand PInvoke yet, but from what I've read I'm pretty sure that my signature is correct - what am I doing wrong? This is all on a 32-bit OS.
2011/04/09
[ "https://Stackoverflow.com/questions/5602645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/113141/" ]
You need to instead use *either* ``` [DllImport("CommonNativeLib.dll", CallingConvention = CallingConvention.Cdecl)] ``` **or** ``` extern "C" __declspec(dllexport) int __stdcall Add(int a, int b) ... ``` because regular C functions work differently than the Windows API functions; their "calling conventions" are different, meaning how they pass around parameters is different. (This was hinted at in the error.)
The Stack Imbalance reasons are either the signature is not matching else Calling Convention by default calling convention is stdcall. When your calling convention is stdcall callee cleans the stack if you want caller to clean the stack us cdecl calling convention. you can find more [Here](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention(v=vs.100).aspx) But if you are facing because of signature, just go through above link [Solve Signature based Stack Imbalance issues using PInvoke extension](https://stackoverflow.com/a/25662985/3583859)
20,758,380
I have some images that I want to use in my application ( 150 - 200 of them ). What's the best place to store them? * assets folder * drawable * why there
2013/12/24
[ "https://Stackoverflow.com/questions/20758380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/677024/" ]
if you must put these images into your application pack, choose drawable that images will be compressed. if you can download when required, store them in sd card is recommend.
You should read the Android article about [Supporting Different Screen Sizes](http://developer.android.com/training/multiscreen/screensizes.html), they show you the benefits of using the Android frame work for that task. If you wish to use assets folder or other solutions like dynamically download the images from your site, it's up to you to write your own implementation to handle all the problems that are describe in the article.
20,758,380
I have some images that I want to use in my application ( 150 - 200 of them ). What's the best place to store them? * assets folder * drawable * why there
2013/12/24
[ "https://Stackoverflow.com/questions/20758380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/677024/" ]
**I don't think so there is bit difference in performance of using these two folders**, I think using drawable folder you can get easily images (All will be indexed in the R file, which makes it much faster (and much easier!) to load them.), and If you want to use it from asset then you have to use AssetManager then using AssetFileDescriptor you have to get those images. 1. Assets can also be organized into a folder hierarchy, which is not supported by resources. It's a different way of managing data. Although resources cover most of the cases, assets have their occasional use. 2. In the res/drawable directory each file is given a pre-compiled ID which can be accessed easily through R.id.[res id]. This is useful to quickly and easily access images, sounds, icons... and for more details go to this link:[Resources-vs-assets-in-android](http://www.gani.com.au/2010/06/resources-vs-assets-in-android/)
if you must put these images into your application pack, choose drawable that images will be compressed. if you can download when required, store them in sd card is recommend.
20,758,380
I have some images that I want to use in my application ( 150 - 200 of them ). What's the best place to store them? * assets folder * drawable * why there
2013/12/24
[ "https://Stackoverflow.com/questions/20758380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/677024/" ]
**I don't think so there is bit difference in performance of using these two folders**, I think using drawable folder you can get easily images (All will be indexed in the R file, which makes it much faster (and much easier!) to load them.), and If you want to use it from asset then you have to use AssetManager then using AssetFileDescriptor you have to get those images. 1. Assets can also be organized into a folder hierarchy, which is not supported by resources. It's a different way of managing data. Although resources cover most of the cases, assets have their occasional use. 2. In the res/drawable directory each file is given a pre-compiled ID which can be accessed easily through R.id.[res id]. This is useful to quickly and easily access images, sounds, icons... and for more details go to this link:[Resources-vs-assets-in-android](http://www.gani.com.au/2010/06/resources-vs-assets-in-android/)
You should read the Android article about [Supporting Different Screen Sizes](http://developer.android.com/training/multiscreen/screensizes.html), they show you the benefits of using the Android frame work for that task. If you wish to use assets folder or other solutions like dynamically download the images from your site, it's up to you to write your own implementation to handle all the problems that are describe in the article.
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
You can use python library resource to get memory usage. ``` import resource resource.getrusage(resource.RUSAGE_SELF).ru_maxrss ``` It will give memory usage in kilobytes, to convert in MB divide by 1000.
Reading the source of `free`'s information, `/proc/meminfo` on a linux system: ``` ~ head /proc/meminfo MemTotal: 4039168 kB MemFree: 2567392 kB MemAvailable: 3169436 kB Buffers: 81756 kB Cached: 712808 kB SwapCached: 0 kB Active: 835276 kB Inactive: 457436 kB Active(anon): 499080 kB Inactive(anon): 17968 kB ``` I have created a decorator class to measure memory consumption of a function. ``` class memoryit: def FreeMemory(): with open('/proc/meminfo') as file: for line in file: if 'MemFree' in line: free_memKB = line.split()[1] return (float(free_memKB)/(1024*1024)) # returns GBytes float def __init__(self, function): # Decorator class to print the memory consumption of a self.function = function # function/method after calling it a number of iterations def __call__(self, *args, iterations = 1, **kwargs): before = memoryit.FreeMemory() for i in range (iterations): result = self.function(*args, **kwargs) after = memoryit.FreeMemory() print ('%r memory used: %2.3f GB' % (self.function.__name__, (before - after) / iterations)) return result ``` Function to measure consumption: ``` @memoryit def MakeMatrix (dim): matrix = [] for i in range (dim): matrix.append([j for j in range (dim)]) return (matrix) ``` Usage: ``` print ("Starting memory:", memoryit.FreeMemory()) m = MakeMatrix(10000) print ("Ending memory:", memoryit.FreeMemory() ) ``` Printout: ``` Starting memory: 10.58599853515625 'MakeMatrix' memory used: 3.741 GB Ending memory: 6.864116668701172 ```
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
It is possible to do this with [memory\_profiler](https://pypi.python.org/pypi/memory_profiler). The function `memory_usage` returns a list of values, these represent the memory usage over time (by default over chunks of .1 second). If you need the maximum, just take the max of that list. Little example: ``` from memory_profiler import memory_usage from time import sleep def f(): # a function that with growing # memory consumption a = [0] * 1000 sleep(.1) b = a * 100 sleep(.1) c = b * 100 return a mem_usage = memory_usage(f) print('Memory usage (in chunks of .1 seconds): %s' % mem_usage) print('Maximum memory usage: %s' % max(mem_usage)) ``` In my case (memory\_profiler 0.25) if prints the following output: ``` Memory usage (in chunks of .1 seconds): [45.65625, 45.734375, 46.41015625, 53.734375] Maximum memory usage: 53.734375 ```
This appears to work under Windows. Don't know about other operating systems. ``` In [50]: import os In [51]: import psutil In [52]: process = psutil.Process(os.getpid()) In [53]: process.get_ext_memory_info().peak_wset Out[53]: 41934848 ```
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
You can use python library resource to get memory usage. ``` import resource resource.getrusage(resource.RUSAGE_SELF).ru_maxrss ``` It will give memory usage in kilobytes, to convert in MB divide by 1000.
Have been struggling with this task as well. After experimenting with psutil and methods from Adam, I wrote a function (credits to Adam Lewis) to measure the memory used by a specific function. People may find it easier to grab and use. 1) [measure\_memory\_usage](https://gist.github.com/ds7711/bd2f817090eca8f66b9b23f4805f7cd6) 2) [test measure\_memory\_usage](https://gist.github.com/ds7711/85261bf1f484cb79e65b3fb27f153d91) I found that materials about threading and overriding superclass are really helpful in understanding what Adam is doing in his scripts. Sorry I cannot post the links due to my "2 links" maximum limitation.
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
Improvement of the answer of @Vader B (as it did not work for me out of box): ``` $ /usr/bin/time --verbose ./myscript.py Command being timed: "./myscript.py" User time (seconds): 16.78 System time (seconds): 2.74 Percent of CPU this job got: 117% Elapsed (wall clock) time (h:mm:ss or m:ss): 0:16.58 Average shared text size (kbytes): 0 Average unshared data size (kbytes): 0 Average stack size (kbytes): 0 Average total size (kbytes): 0 Maximum resident set size (kbytes): 616092 # WE NEED THIS!!! Average resident set size (kbytes): 0 Major (requiring I/O) page faults: 0 Minor (reclaiming a frame) page faults: 432750 Voluntary context switches: 1075 Involuntary context switches: 118503 Swaps: 0 File system inputs: 0 File system outputs: 800 Socket messages sent: 0 Socket messages received: 0 Signals delivered: 0 Page size (bytes): 4096 Exit status: 0 ```
Reading the source of `free`'s information, `/proc/meminfo` on a linux system: ``` ~ head /proc/meminfo MemTotal: 4039168 kB MemFree: 2567392 kB MemAvailable: 3169436 kB Buffers: 81756 kB Cached: 712808 kB SwapCached: 0 kB Active: 835276 kB Inactive: 457436 kB Active(anon): 499080 kB Inactive(anon): 17968 kB ``` I have created a decorator class to measure memory consumption of a function. ``` class memoryit: def FreeMemory(): with open('/proc/meminfo') as file: for line in file: if 'MemFree' in line: free_memKB = line.split()[1] return (float(free_memKB)/(1024*1024)) # returns GBytes float def __init__(self, function): # Decorator class to print the memory consumption of a self.function = function # function/method after calling it a number of iterations def __call__(self, *args, iterations = 1, **kwargs): before = memoryit.FreeMemory() for i in range (iterations): result = self.function(*args, **kwargs) after = memoryit.FreeMemory() print ('%r memory used: %2.3f GB' % (self.function.__name__, (before - after) / iterations)) return result ``` Function to measure consumption: ``` @memoryit def MakeMatrix (dim): matrix = [] for i in range (dim): matrix.append([j for j in range (dim)]) return (matrix) ``` Usage: ``` print ("Starting memory:", memoryit.FreeMemory()) m = MakeMatrix(10000) print ("Ending memory:", memoryit.FreeMemory() ) ``` Printout: ``` Starting memory: 10.58599853515625 'MakeMatrix' memory used: 3.741 GB Ending memory: 6.864116668701172 ```
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
This question seemed rather interesting and it gave me a reason to look into Guppy / Heapy, for that I thank you. I tried for about 2 hours to get Heapy to do monitor a function call / process without modifying its source with *zero* luck. I did find a way to accomplish your task using the built in Python library [`resource`](http://docs.python.org/library/resource.html#resource-usage). Note that the documentation does not indicate what the `RU_MAXRSS` value returns. Another SO user [noted](https://stackoverflow.com/a/7669482/157744) that it was in kB. Running Mac OSX 7.3 and watching my system resources climb up during the test code below, I believe the returned values to be in **Bytes**, not kBytes. A 10000ft view on how I used the `resource` library to monitor the library call was to launch the function in a separate (monitor-able) thread and track the system resources for that process in the main thread. Below I have the two files that you'd need to run to test it out. **Library Resource Monitor** - [whatever\_you\_want.py](https://gist.github.com/raw/b54fafd87634f017d50d/e101d619bfbc9054ad129fe5141e0c584ac35577/whatever_you_want.py) ``` import resource import time from stoppable_thread import StoppableThread class MyLibrarySniffingClass(StoppableThread): def __init__(self, target_lib_call, arg1, arg2): super(MyLibrarySniffingClass, self).__init__() self.target_function = target_lib_call self.arg1 = arg1 self.arg2 = arg2 self.results = None def startup(self): # Overload the startup function print "Calling the Target Library Function..." def cleanup(self): # Overload the cleanup function print "Library Call Complete" def mainloop(self): # Start the library Call self.results = self.target_function(self.arg1, self.arg2) # Kill the thread when complete self.stop() def SomeLongRunningLibraryCall(arg1, arg2): max_dict_entries = 2500 delay_per_entry = .005 some_large_dictionary = {} dict_entry_count = 0 while(1): time.sleep(delay_per_entry) dict_entry_count += 1 some_large_dictionary[dict_entry_count]=range(10000) if len(some_large_dictionary) > max_dict_entries: break print arg1 + " " + arg2 return "Good Bye World" if __name__ == "__main__": # Lib Testing Code mythread = MyLibrarySniffingClass(SomeLongRunningLibraryCall, "Hello", "World") mythread.start() start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss delta_mem = 0 max_memory = 0 memory_usage_refresh = .005 # Seconds while(1): time.sleep(memory_usage_refresh) delta_mem = (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) - start_mem if delta_mem > max_memory: max_memory = delta_mem # Uncomment this line to see the memory usuage during run-time # print "Memory Usage During Call: %d MB" % (delta_mem / 1000000.0) # Check to see if the library call is complete if mythread.isShutdown(): print mythread.results break; print "\nMAX Memory Usage in MB: " + str(round(max_memory / 1000.0, 3)) ``` **Stoppable Thread** - [stoppable\_thread.py](https://gist.github.com/raw/b54fafd87634f017d50d/bed2a7c2eafed67f05ee3dce926e73ac0f8e2f9c/stoppable_thread.py) ``` import threading import time class StoppableThread(threading.Thread): def __init__(self): super(StoppableThread, self).__init__() self.daemon = True self.__monitor = threading.Event() self.__monitor.set() self.__has_shutdown = False def run(self): '''Overloads the threading.Thread.run''' # Call the User's Startup functions self.startup() # Loop until the thread is stopped while self.isRunning(): self.mainloop() # Clean up self.cleanup() # Flag to the outside world that the thread has exited # AND that the cleanup is complete self.__has_shutdown = True def stop(self): self.__monitor.clear() def isRunning(self): return self.__monitor.isSet() def isShutdown(self): return self.__has_shutdown ############################### ### User Defined Functions #### ############################### def mainloop(self): ''' Expected to be overwritten in a subclass!! Note that Stoppable while(1) is handled in the built in "run". ''' pass def startup(self): '''Expected to be overwritten in a subclass!!''' pass def cleanup(self): '''Expected to be overwritten in a subclass!!''' pass ```
Have been struggling with this task as well. After experimenting with psutil and methods from Adam, I wrote a function (credits to Adam Lewis) to measure the memory used by a specific function. People may find it easier to grab and use. 1) [measure\_memory\_usage](https://gist.github.com/ds7711/bd2f817090eca8f66b9b23f4805f7cd6) 2) [test measure\_memory\_usage](https://gist.github.com/ds7711/85261bf1f484cb79e65b3fb27f153d91) I found that materials about threading and overriding superclass are really helpful in understanding what Adam is doing in his scripts. Sorry I cannot post the links due to my "2 links" maximum limitation.
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
You can use python library resource to get memory usage. ``` import resource resource.getrusage(resource.RUSAGE_SELF).ru_maxrss ``` It will give memory usage in kilobytes, to convert in MB divide by 1000.
Standard Unix utility `time` tracks maximum memory usage of the process as well as other useful statistics for your program. Example output (`maxresident` is max memory usage, in Kilobytes.): ``` > time python ./scalabilty_test.py 45.31user 1.86system 0:47.23elapsed 99%CPU (0avgtext+0avgdata 369824maxresident)k 0inputs+100208outputs (0major+99494minor)pagefaults 0swaps ```
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
This question seemed rather interesting and it gave me a reason to look into Guppy / Heapy, for that I thank you. I tried for about 2 hours to get Heapy to do monitor a function call / process without modifying its source with *zero* luck. I did find a way to accomplish your task using the built in Python library [`resource`](http://docs.python.org/library/resource.html#resource-usage). Note that the documentation does not indicate what the `RU_MAXRSS` value returns. Another SO user [noted](https://stackoverflow.com/a/7669482/157744) that it was in kB. Running Mac OSX 7.3 and watching my system resources climb up during the test code below, I believe the returned values to be in **Bytes**, not kBytes. A 10000ft view on how I used the `resource` library to monitor the library call was to launch the function in a separate (monitor-able) thread and track the system resources for that process in the main thread. Below I have the two files that you'd need to run to test it out. **Library Resource Monitor** - [whatever\_you\_want.py](https://gist.github.com/raw/b54fafd87634f017d50d/e101d619bfbc9054ad129fe5141e0c584ac35577/whatever_you_want.py) ``` import resource import time from stoppable_thread import StoppableThread class MyLibrarySniffingClass(StoppableThread): def __init__(self, target_lib_call, arg1, arg2): super(MyLibrarySniffingClass, self).__init__() self.target_function = target_lib_call self.arg1 = arg1 self.arg2 = arg2 self.results = None def startup(self): # Overload the startup function print "Calling the Target Library Function..." def cleanup(self): # Overload the cleanup function print "Library Call Complete" def mainloop(self): # Start the library Call self.results = self.target_function(self.arg1, self.arg2) # Kill the thread when complete self.stop() def SomeLongRunningLibraryCall(arg1, arg2): max_dict_entries = 2500 delay_per_entry = .005 some_large_dictionary = {} dict_entry_count = 0 while(1): time.sleep(delay_per_entry) dict_entry_count += 1 some_large_dictionary[dict_entry_count]=range(10000) if len(some_large_dictionary) > max_dict_entries: break print arg1 + " " + arg2 return "Good Bye World" if __name__ == "__main__": # Lib Testing Code mythread = MyLibrarySniffingClass(SomeLongRunningLibraryCall, "Hello", "World") mythread.start() start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss delta_mem = 0 max_memory = 0 memory_usage_refresh = .005 # Seconds while(1): time.sleep(memory_usage_refresh) delta_mem = (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) - start_mem if delta_mem > max_memory: max_memory = delta_mem # Uncomment this line to see the memory usuage during run-time # print "Memory Usage During Call: %d MB" % (delta_mem / 1000000.0) # Check to see if the library call is complete if mythread.isShutdown(): print mythread.results break; print "\nMAX Memory Usage in MB: " + str(round(max_memory / 1000.0, 3)) ``` **Stoppable Thread** - [stoppable\_thread.py](https://gist.github.com/raw/b54fafd87634f017d50d/bed2a7c2eafed67f05ee3dce926e73ac0f8e2f9c/stoppable_thread.py) ``` import threading import time class StoppableThread(threading.Thread): def __init__(self): super(StoppableThread, self).__init__() self.daemon = True self.__monitor = threading.Event() self.__monitor.set() self.__has_shutdown = False def run(self): '''Overloads the threading.Thread.run''' # Call the User's Startup functions self.startup() # Loop until the thread is stopped while self.isRunning(): self.mainloop() # Clean up self.cleanup() # Flag to the outside world that the thread has exited # AND that the cleanup is complete self.__has_shutdown = True def stop(self): self.__monitor.clear() def isRunning(self): return self.__monitor.isSet() def isShutdown(self): return self.__has_shutdown ############################### ### User Defined Functions #### ############################### def mainloop(self): ''' Expected to be overwritten in a subclass!! Note that Stoppable while(1) is handled in the built in "run". ''' pass def startup(self): '''Expected to be overwritten in a subclass!!''' pass def cleanup(self): '''Expected to be overwritten in a subclass!!''' pass ```
This appears to work under Windows. Don't know about other operating systems. ``` In [50]: import os In [51]: import psutil In [52]: process = psutil.Process(os.getpid()) In [53]: process.get_ext_memory_info().peak_wset Out[53]: 41934848 ```
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
This question seemed rather interesting and it gave me a reason to look into Guppy / Heapy, for that I thank you. I tried for about 2 hours to get Heapy to do monitor a function call / process without modifying its source with *zero* luck. I did find a way to accomplish your task using the built in Python library [`resource`](http://docs.python.org/library/resource.html#resource-usage). Note that the documentation does not indicate what the `RU_MAXRSS` value returns. Another SO user [noted](https://stackoverflow.com/a/7669482/157744) that it was in kB. Running Mac OSX 7.3 and watching my system resources climb up during the test code below, I believe the returned values to be in **Bytes**, not kBytes. A 10000ft view on how I used the `resource` library to monitor the library call was to launch the function in a separate (monitor-able) thread and track the system resources for that process in the main thread. Below I have the two files that you'd need to run to test it out. **Library Resource Monitor** - [whatever\_you\_want.py](https://gist.github.com/raw/b54fafd87634f017d50d/e101d619bfbc9054ad129fe5141e0c584ac35577/whatever_you_want.py) ``` import resource import time from stoppable_thread import StoppableThread class MyLibrarySniffingClass(StoppableThread): def __init__(self, target_lib_call, arg1, arg2): super(MyLibrarySniffingClass, self).__init__() self.target_function = target_lib_call self.arg1 = arg1 self.arg2 = arg2 self.results = None def startup(self): # Overload the startup function print "Calling the Target Library Function..." def cleanup(self): # Overload the cleanup function print "Library Call Complete" def mainloop(self): # Start the library Call self.results = self.target_function(self.arg1, self.arg2) # Kill the thread when complete self.stop() def SomeLongRunningLibraryCall(arg1, arg2): max_dict_entries = 2500 delay_per_entry = .005 some_large_dictionary = {} dict_entry_count = 0 while(1): time.sleep(delay_per_entry) dict_entry_count += 1 some_large_dictionary[dict_entry_count]=range(10000) if len(some_large_dictionary) > max_dict_entries: break print arg1 + " " + arg2 return "Good Bye World" if __name__ == "__main__": # Lib Testing Code mythread = MyLibrarySniffingClass(SomeLongRunningLibraryCall, "Hello", "World") mythread.start() start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss delta_mem = 0 max_memory = 0 memory_usage_refresh = .005 # Seconds while(1): time.sleep(memory_usage_refresh) delta_mem = (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) - start_mem if delta_mem > max_memory: max_memory = delta_mem # Uncomment this line to see the memory usuage during run-time # print "Memory Usage During Call: %d MB" % (delta_mem / 1000000.0) # Check to see if the library call is complete if mythread.isShutdown(): print mythread.results break; print "\nMAX Memory Usage in MB: " + str(round(max_memory / 1000.0, 3)) ``` **Stoppable Thread** - [stoppable\_thread.py](https://gist.github.com/raw/b54fafd87634f017d50d/bed2a7c2eafed67f05ee3dce926e73ac0f8e2f9c/stoppable_thread.py) ``` import threading import time class StoppableThread(threading.Thread): def __init__(self): super(StoppableThread, self).__init__() self.daemon = True self.__monitor = threading.Event() self.__monitor.set() self.__has_shutdown = False def run(self): '''Overloads the threading.Thread.run''' # Call the User's Startup functions self.startup() # Loop until the thread is stopped while self.isRunning(): self.mainloop() # Clean up self.cleanup() # Flag to the outside world that the thread has exited # AND that the cleanup is complete self.__has_shutdown = True def stop(self): self.__monitor.clear() def isRunning(self): return self.__monitor.isSet() def isShutdown(self): return self.__has_shutdown ############################### ### User Defined Functions #### ############################### def mainloop(self): ''' Expected to be overwritten in a subclass!! Note that Stoppable while(1) is handled in the built in "run". ''' pass def startup(self): '''Expected to be overwritten in a subclass!!''' pass def cleanup(self): '''Expected to be overwritten in a subclass!!''' pass ```
Reading the source of `free`'s information, `/proc/meminfo` on a linux system: ``` ~ head /proc/meminfo MemTotal: 4039168 kB MemFree: 2567392 kB MemAvailable: 3169436 kB Buffers: 81756 kB Cached: 712808 kB SwapCached: 0 kB Active: 835276 kB Inactive: 457436 kB Active(anon): 499080 kB Inactive(anon): 17968 kB ``` I have created a decorator class to measure memory consumption of a function. ``` class memoryit: def FreeMemory(): with open('/proc/meminfo') as file: for line in file: if 'MemFree' in line: free_memKB = line.split()[1] return (float(free_memKB)/(1024*1024)) # returns GBytes float def __init__(self, function): # Decorator class to print the memory consumption of a self.function = function # function/method after calling it a number of iterations def __call__(self, *args, iterations = 1, **kwargs): before = memoryit.FreeMemory() for i in range (iterations): result = self.function(*args, **kwargs) after = memoryit.FreeMemory() print ('%r memory used: %2.3f GB' % (self.function.__name__, (before - after) / iterations)) return result ``` Function to measure consumption: ``` @memoryit def MakeMatrix (dim): matrix = [] for i in range (dim): matrix.append([j for j in range (dim)]) return (matrix) ``` Usage: ``` print ("Starting memory:", memoryit.FreeMemory()) m = MakeMatrix(10000) print ("Ending memory:", memoryit.FreeMemory() ) ``` Printout: ``` Starting memory: 10.58599853515625 'MakeMatrix' memory used: 3.741 GB Ending memory: 6.864116668701172 ```
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
This question seemed rather interesting and it gave me a reason to look into Guppy / Heapy, for that I thank you. I tried for about 2 hours to get Heapy to do monitor a function call / process without modifying its source with *zero* luck. I did find a way to accomplish your task using the built in Python library [`resource`](http://docs.python.org/library/resource.html#resource-usage). Note that the documentation does not indicate what the `RU_MAXRSS` value returns. Another SO user [noted](https://stackoverflow.com/a/7669482/157744) that it was in kB. Running Mac OSX 7.3 and watching my system resources climb up during the test code below, I believe the returned values to be in **Bytes**, not kBytes. A 10000ft view on how I used the `resource` library to monitor the library call was to launch the function in a separate (monitor-able) thread and track the system resources for that process in the main thread. Below I have the two files that you'd need to run to test it out. **Library Resource Monitor** - [whatever\_you\_want.py](https://gist.github.com/raw/b54fafd87634f017d50d/e101d619bfbc9054ad129fe5141e0c584ac35577/whatever_you_want.py) ``` import resource import time from stoppable_thread import StoppableThread class MyLibrarySniffingClass(StoppableThread): def __init__(self, target_lib_call, arg1, arg2): super(MyLibrarySniffingClass, self).__init__() self.target_function = target_lib_call self.arg1 = arg1 self.arg2 = arg2 self.results = None def startup(self): # Overload the startup function print "Calling the Target Library Function..." def cleanup(self): # Overload the cleanup function print "Library Call Complete" def mainloop(self): # Start the library Call self.results = self.target_function(self.arg1, self.arg2) # Kill the thread when complete self.stop() def SomeLongRunningLibraryCall(arg1, arg2): max_dict_entries = 2500 delay_per_entry = .005 some_large_dictionary = {} dict_entry_count = 0 while(1): time.sleep(delay_per_entry) dict_entry_count += 1 some_large_dictionary[dict_entry_count]=range(10000) if len(some_large_dictionary) > max_dict_entries: break print arg1 + " " + arg2 return "Good Bye World" if __name__ == "__main__": # Lib Testing Code mythread = MyLibrarySniffingClass(SomeLongRunningLibraryCall, "Hello", "World") mythread.start() start_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss delta_mem = 0 max_memory = 0 memory_usage_refresh = .005 # Seconds while(1): time.sleep(memory_usage_refresh) delta_mem = (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss) - start_mem if delta_mem > max_memory: max_memory = delta_mem # Uncomment this line to see the memory usuage during run-time # print "Memory Usage During Call: %d MB" % (delta_mem / 1000000.0) # Check to see if the library call is complete if mythread.isShutdown(): print mythread.results break; print "\nMAX Memory Usage in MB: " + str(round(max_memory / 1000.0, 3)) ``` **Stoppable Thread** - [stoppable\_thread.py](https://gist.github.com/raw/b54fafd87634f017d50d/bed2a7c2eafed67f05ee3dce926e73ac0f8e2f9c/stoppable_thread.py) ``` import threading import time class StoppableThread(threading.Thread): def __init__(self): super(StoppableThread, self).__init__() self.daemon = True self.__monitor = threading.Event() self.__monitor.set() self.__has_shutdown = False def run(self): '''Overloads the threading.Thread.run''' # Call the User's Startup functions self.startup() # Loop until the thread is stopped while self.isRunning(): self.mainloop() # Clean up self.cleanup() # Flag to the outside world that the thread has exited # AND that the cleanup is complete self.__has_shutdown = True def stop(self): self.__monitor.clear() def isRunning(self): return self.__monitor.isSet() def isShutdown(self): return self.__has_shutdown ############################### ### User Defined Functions #### ############################### def mainloop(self): ''' Expected to be overwritten in a subclass!! Note that Stoppable while(1) is handled in the built in "run". ''' pass def startup(self): '''Expected to be overwritten in a subclass!!''' pass def cleanup(self): '''Expected to be overwritten in a subclass!!''' pass ```
Improvement of the answer of @Vader B (as it did not work for me out of box): ``` $ /usr/bin/time --verbose ./myscript.py Command being timed: "./myscript.py" User time (seconds): 16.78 System time (seconds): 2.74 Percent of CPU this job got: 117% Elapsed (wall clock) time (h:mm:ss or m:ss): 0:16.58 Average shared text size (kbytes): 0 Average unshared data size (kbytes): 0 Average stack size (kbytes): 0 Average total size (kbytes): 0 Maximum resident set size (kbytes): 616092 # WE NEED THIS!!! Average resident set size (kbytes): 0 Major (requiring I/O) page faults: 0 Minor (reclaiming a frame) page faults: 432750 Voluntary context switches: 1075 Involuntary context switches: 118503 Swaps: 0 File system inputs: 0 File system outputs: 800 Socket messages sent: 0 Socket messages received: 0 Signals delivered: 0 Page size (bytes): 4096 Exit status: 0 ```
9,850,995
I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage: [Which Python memory profiler is recommended?](https://stackoverflow.com/questions/110259/python-memory-profiler) [How do I profile memory usage in Python?](https://stackoverflow.com/questions/552744/how-do-i-profile-memory-usage-in-python) but those seem to allow you more to track memory usage at the time the `heap()` method (in the case of guppy) is called. However, what I want to track is a function in an external library which I can't modify, and which grows to use a lot of RAM but then frees it once the execution of the function is complete. Is there any way to find out what the total amount of RAM used during the function call was?
2012/03/24
[ "https://Stackoverflow.com/questions/9850995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180783/" ]
It is possible to do this with [memory\_profiler](https://pypi.python.org/pypi/memory_profiler). The function `memory_usage` returns a list of values, these represent the memory usage over time (by default over chunks of .1 second). If you need the maximum, just take the max of that list. Little example: ``` from memory_profiler import memory_usage from time import sleep def f(): # a function that with growing # memory consumption a = [0] * 1000 sleep(.1) b = a * 100 sleep(.1) c = b * 100 return a mem_usage = memory_usage(f) print('Memory usage (in chunks of .1 seconds): %s' % mem_usage) print('Maximum memory usage: %s' % max(mem_usage)) ``` In my case (memory\_profiler 0.25) if prints the following output: ``` Memory usage (in chunks of .1 seconds): [45.65625, 45.734375, 46.41015625, 53.734375] Maximum memory usage: 53.734375 ```
Have been struggling with this task as well. After experimenting with psutil and methods from Adam, I wrote a function (credits to Adam Lewis) to measure the memory used by a specific function. People may find it easier to grab and use. 1) [measure\_memory\_usage](https://gist.github.com/ds7711/bd2f817090eca8f66b9b23f4805f7cd6) 2) [test measure\_memory\_usage](https://gist.github.com/ds7711/85261bf1f484cb79e65b3fb27f153d91) I found that materials about threading and overriding superclass are really helpful in understanding what Adam is doing in his scripts. Sorry I cannot post the links due to my "2 links" maximum limitation.
12,492,266
Let's say I have a simple table with NBA players: id,player,mp,ppg (mp - matches played, ppg - points per game). I need a query that gets all the guys but split the result into two parts: * players who played in more or equal 30 games ordered by PPG desc, * players who played less than 30 games ordered by PPG desc So desirable output would be (example): ``` n. player mp ppg 1. player1 82 32.5 2. player2 56 32.1 3. player3 82 29.7 4. player4 80 27.6 ``` ... ``` 70. player70 75 1.5 (lowest in the 30+ games group) 71. player71 29 35.7 (highest in the less than 30 games group) 72. player72 19 31.3 ``` ... Group 1) comes first (is more important) so even if PPG in group 2) is higher than the best one in group 1) it goes down after the worst PPG in the group where players have more than 30 games played. Is there a way to do that in just one query? I'm using mySQL. Thanks!
2012/09/19
[ "https://Stackoverflow.com/questions/12492266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1327135/" ]
``` select id, player, mp, ppg from playerTable order by if (mp>=30, 1, 0) desc, ppg desc, mp desc` ```
``` SELECT * FROM tablename ORDER BY CASE WHEN mp >= 30 THEN PPG END DESC, CASE WHEN mp < 30 THEN PPG END ASC ```
12,492,266
Let's say I have a simple table with NBA players: id,player,mp,ppg (mp - matches played, ppg - points per game). I need a query that gets all the guys but split the result into two parts: * players who played in more or equal 30 games ordered by PPG desc, * players who played less than 30 games ordered by PPG desc So desirable output would be (example): ``` n. player mp ppg 1. player1 82 32.5 2. player2 56 32.1 3. player3 82 29.7 4. player4 80 27.6 ``` ... ``` 70. player70 75 1.5 (lowest in the 30+ games group) 71. player71 29 35.7 (highest in the less than 30 games group) 72. player72 19 31.3 ``` ... Group 1) comes first (is more important) so even if PPG in group 2) is higher than the best one in group 1) it goes down after the worst PPG in the group where players have more than 30 games played. Is there a way to do that in just one query? I'm using mySQL. Thanks!
2012/09/19
[ "https://Stackoverflow.com/questions/12492266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1327135/" ]
``` select id, player, mp, ppg from playerTable order by if (mp>=30, 1, 0) desc, ppg desc, mp desc` ```
Assuming `ppq` is allways lower than 1000000, this would work: ``` SELECT * -- or whatever you want FROM players ORDER BY IF(mp>=30,1000000+ppg,mp) desc ``` This assumes, that the second group is ordered by `mp` desc (as in example), not by `ppg` (as in text)
12,492,266
Let's say I have a simple table with NBA players: id,player,mp,ppg (mp - matches played, ppg - points per game). I need a query that gets all the guys but split the result into two parts: * players who played in more or equal 30 games ordered by PPG desc, * players who played less than 30 games ordered by PPG desc So desirable output would be (example): ``` n. player mp ppg 1. player1 82 32.5 2. player2 56 32.1 3. player3 82 29.7 4. player4 80 27.6 ``` ... ``` 70. player70 75 1.5 (lowest in the 30+ games group) 71. player71 29 35.7 (highest in the less than 30 games group) 72. player72 19 31.3 ``` ... Group 1) comes first (is more important) so even if PPG in group 2) is higher than the best one in group 1) it goes down after the worst PPG in the group where players have more than 30 games played. Is there a way to do that in just one query? I'm using mySQL. Thanks!
2012/09/19
[ "https://Stackoverflow.com/questions/12492266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1327135/" ]
``` select id, player, mp, ppg from playerTable order by if (mp>=30, 1, 0) desc, ppg desc, mp desc` ```
First order by MP>30 then by PPG ``` ORDER BY (CASE WHEN mp >= 30 THEN 1 ELSE 2 END) ASC, PPG DESC ```
12,492,266
Let's say I have a simple table with NBA players: id,player,mp,ppg (mp - matches played, ppg - points per game). I need a query that gets all the guys but split the result into two parts: * players who played in more or equal 30 games ordered by PPG desc, * players who played less than 30 games ordered by PPG desc So desirable output would be (example): ``` n. player mp ppg 1. player1 82 32.5 2. player2 56 32.1 3. player3 82 29.7 4. player4 80 27.6 ``` ... ``` 70. player70 75 1.5 (lowest in the 30+ games group) 71. player71 29 35.7 (highest in the less than 30 games group) 72. player72 19 31.3 ``` ... Group 1) comes first (is more important) so even if PPG in group 2) is higher than the best one in group 1) it goes down after the worst PPG in the group where players have more than 30 games played. Is there a way to do that in just one query? I'm using mySQL. Thanks!
2012/09/19
[ "https://Stackoverflow.com/questions/12492266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1327135/" ]
``` select id, player, mp, ppg from playerTable order by if (mp>=30, 1, 0) desc, ppg desc, mp desc` ```
``` select player, mp, ppg from t order by mp < 30, ppg desc ```
15,048,773
I am using querydsl (which depends on sl4j-api 1.6) and arquillian-persistence-api (which depends on slf4j-jdk14 1.5.6). If I ignore in maven the older version 1.5.6 I get the following message on JBoss `SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.` I am using arquillian with managed JBoss AS 7.1 for testing (Maven downloads the version from maven central and run the tests). I am also using arquillian persistence api. What should I do to correct the given warning? I mean which dependency should I keep or how would I allow both to work properly? I suppose this is why I am not getting any error messages on arquillian persistence api failure (because the logger is not working?).
2013/02/24
[ "https://Stackoverflow.com/questions/15048773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1400037/" ]
The message you are seeing is a warning, not an error. It means SLF4J is selecting a binding for you because you've not chosen one yourself. The default binding simply discards all log messages, which is not very useful. If you have conflicting versions in Maven, normally it's safer to force the newer version. Libraries are *often* backwards compatible. So, stick with your newer version of `slf4j-api` and just ensure you declare a binding as a dependency, e.g. `slf4j-jdk14`. If you are producing a library, ensure your binding is declared with `test` scope only.
JBoss 7.1 has built-in support for SLF4J. Assuming this is a web application with WAR packaging you add `src/main/webapp/WEB-INF/jboss-deployment-structure.xml`: ``` <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.0"> <deployment> <dependencies> <module name="org.slf4j" /> </dependencies> </deployment> </jboss-deployment-structure> ``` This will pull in the JBoss SL4J adapter which will give you logging output. This implies that you want to use the application server provided libraries for SLF4J. You ought to update your `pom.xml` to fix the scope of the SLF4J dependency. ``` <dependencies> ... <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <scope>provided</scope> </dependency> ... </dependencies> ``` Depending on how your POM file is arranged you may also need to give the version of SLF4J you want to use. `mvn dependency:tree` can show you which SLF4J deps are being pulled in. Make sure they are all getting the "provided" scope. If you use Eclipse and the m2e plugin you can also open your POM file and check the "Dependency Hierarchy" tab which will provide you with similar information.
15,048,773
I am using querydsl (which depends on sl4j-api 1.6) and arquillian-persistence-api (which depends on slf4j-jdk14 1.5.6). If I ignore in maven the older version 1.5.6 I get the following message on JBoss `SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.` I am using arquillian with managed JBoss AS 7.1 for testing (Maven downloads the version from maven central and run the tests). I am also using arquillian persistence api. What should I do to correct the given warning? I mean which dependency should I keep or how would I allow both to work properly? I suppose this is why I am not getting any error messages on arquillian persistence api failure (because the logger is not working?).
2013/02/24
[ "https://Stackoverflow.com/questions/15048773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1400037/" ]
The message you are seeing is a warning, not an error. It means SLF4J is selecting a binding for you because you've not chosen one yourself. The default binding simply discards all log messages, which is not very useful. If you have conflicting versions in Maven, normally it's safer to force the newer version. Libraries are *often* backwards compatible. So, stick with your newer version of `slf4j-api` and just ensure you declare a binding as a dependency, e.g. `slf4j-jdk14`. If you are producing a library, ensure your binding is declared with `test` scope only.
First of all. Regarding the dependencies. In order to add SLF4J you must put **ONE** and only **ONE** of these dependencies in your pom.xml. It depends on what implementation you choose to use. Every dependency you add in the pom.xml is added automatically in the classpath. If one of the below dependencies are provided by another dependency then you can omit it. Dont forget that you must include only one even if the dependency is provided by another dependency. ```xml <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version></version> </dependency> ``` ```xml <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version></version> <scope>compile</scope> </dependency> ``` ```xml <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version></version> <scope>compile</scope> </dependency> ``` ```xml <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version></version> <scope>compile</scope> </dependency> ``` Now regarding the annoying error you are getting when building your maven project. If after having only one of the above dependencies you still get the SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". then you are facing a bug from m2e. Eclipse Juno and Indigo, when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards. Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the [m2e support site](https://bugs.eclipse.org/bugs/show_bug.cgi?id=387064). The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i think describes the same problem you are facing. [SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error](https://stackoverflow.com/questions/11916706/slf4j-failed-to-load-class-org-slf4j-impl-staticloggerbinder-error)
15,048,773
I am using querydsl (which depends on sl4j-api 1.6) and arquillian-persistence-api (which depends on slf4j-jdk14 1.5.6). If I ignore in maven the older version 1.5.6 I get the following message on JBoss `SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.` I am using arquillian with managed JBoss AS 7.1 for testing (Maven downloads the version from maven central and run the tests). I am also using arquillian persistence api. What should I do to correct the given warning? I mean which dependency should I keep or how would I allow both to work properly? I suppose this is why I am not getting any error messages on arquillian persistence api failure (because the logger is not working?).
2013/02/24
[ "https://Stackoverflow.com/questions/15048773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1400037/" ]
First of all. Regarding the dependencies. In order to add SLF4J you must put **ONE** and only **ONE** of these dependencies in your pom.xml. It depends on what implementation you choose to use. Every dependency you add in the pom.xml is added automatically in the classpath. If one of the below dependencies are provided by another dependency then you can omit it. Dont forget that you must include only one even if the dependency is provided by another dependency. ```xml <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version></version> </dependency> ``` ```xml <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version></version> <scope>compile</scope> </dependency> ``` ```xml <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version></version> <scope>compile</scope> </dependency> ``` ```xml <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version></version> <scope>compile</scope> </dependency> ``` Now regarding the annoying error you are getting when building your maven project. If after having only one of the above dependencies you still get the SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". then you are facing a bug from m2e. Eclipse Juno and Indigo, when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards. Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the [m2e support site](https://bugs.eclipse.org/bugs/show_bug.cgi?id=387064). The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i think describes the same problem you are facing. [SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error](https://stackoverflow.com/questions/11916706/slf4j-failed-to-load-class-org-slf4j-impl-staticloggerbinder-error)
JBoss 7.1 has built-in support for SLF4J. Assuming this is a web application with WAR packaging you add `src/main/webapp/WEB-INF/jboss-deployment-structure.xml`: ``` <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.0"> <deployment> <dependencies> <module name="org.slf4j" /> </dependencies> </deployment> </jboss-deployment-structure> ``` This will pull in the JBoss SL4J adapter which will give you logging output. This implies that you want to use the application server provided libraries for SLF4J. You ought to update your `pom.xml` to fix the scope of the SLF4J dependency. ``` <dependencies> ... <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <scope>provided</scope> </dependency> ... </dependencies> ``` Depending on how your POM file is arranged you may also need to give the version of SLF4J you want to use. `mvn dependency:tree` can show you which SLF4J deps are being pulled in. Make sure they are all getting the "provided" scope. If you use Eclipse and the m2e plugin you can also open your POM file and check the "Dependency Hierarchy" tab which will provide you with similar information.
142,630
Inspired by [this challenge](https://codegolf.stackexchange.com/questions/140854/1326-starting-holdem-combos) and related to [this one](https://codegolf.stackexchange.com/questions/25056/compare-two-poker-hands). ### Background Badugi [bæduːɡiː] is a low-ball draw-poker variant. The Pokerstars World Cup Of Online Poker **$1K** event starts within **3** hours and I'll need to know how good my hands are! The game uses a standard deck of **52** cards of four suits and thirteen ranks. The suits are unordered and shall be labelled `cdhs`; the ranks - ordered from highest `K` to lowest `A` - are `KQJT98765432A`. As such the full deck may be represented as follows (space separated): ``` Kc Kd Kh Ks Qc Qd Qh Qs Jc Jd Jh Js Tc Td Th Ts 9c 9d 9h 9s 8c 8d 8h 8s 7c 7d 7h 7s 6c 6d 6h 6s 5c 5d 5h 5s 4c 4d 4h 4s 3c 3d 3h 3s 2c 2d 2h 2s Ac Ad Ah As ``` Each player is dealt **four** cards from the deck, there are four betting rounds with three drawing rounds in-between (a player always has four cards, they have the option of changing 0-4 of their cards with new ones from the dealer on each of the three drawing rounds). If more than one player is still active after all these rounds there is a showdown, whereupon the strongest hand(s) win the wagered bets. The game is played low-ball, so the lowest hand wins, and as mentioned above `A` (ace) is low. Furthermore the hand ranking is different from other forms of poker, and can be somewhat confusing for beginners. The played "hand" is the lowest ranked combination made from the highest number of both "off-suit" (all-different-suits) and "off-rank" (all-different-ranks) cards possible (from the four held cards). That is: if one holds four cards of both distinct suits *and* distinct ranks one has a 4-card hand (called a "badugi"); if one does not have a 4-card hand but does have some set or sets of three cards of both distinct suits *and* distinct ranks one has a 3-card hand (one chooses their best); if one has neither a 4-card hand or a 3-card hand one probably has a 2-card hand, but if not one has a 1-card hand. * As such the best possible hand is the 4-card hand `4-3-2-A` - the lowest **off-rank** cards of **four different suits**, often termed a "number-1". The weakest possible hand would be the 1-card hand `K` and is only possible by holding exactly `Kc Kd Kh Ks`. * Note that `4c 3h 2c As` is **not** a "number-1", since the `4c` and `2c` are of the same suit, but it *is* the strongest of the 3-card hands, `3-2-A`, it draws with other `3-2-1`s (like `Kh 3d 2s Ah`) and beats all other 3-card hands but loses to all 4-card hands (which could be as weak as `K-Q-J-T`). + The other possible 3-card hand that could be made from `4c 3h 2c As` is `4-3-A`, but that is weaker (higher) so not chosen. * Similarly `8d 6h 3s 2h` is a 3-card hand played as `8-3-2` - there are two off-rank off-suit combinations of size 3 and `8-3-2` is better (lower) than `8-6-3` since the three (or "trey") is lower than the six. Comparing hands against one another follows the same logic - any 4-card beats any 3-card, any 3-card beats any 2-card and any 2-card beats any 1-card, while hands of the same number of used cards are compared from their highest rank down to their lowest (for example: `8-4-2` beats `8-5-A` but not any of `8-4-A`, `8-3-2` or `7-6-5`) ### The challenge: Given two unordered-collections each of four cards, identify the one(s) which win a Badugi showdown (identify both if it is a draw). The input may be anything reasonable: * a single string of all eight cards as labelled above (with or without spaces) with the left four being one hand and the right the other (with an optional separator); or a list of characters in the same fashion * a list of two strings - one per hand, or a list of lists of characters in the same fashion * two separate strings or list inputs, one per hand * the cards within the hands may be separated already too (so a list of lists of lists is fine) Note, however: * the cards may not be arranged into any order prior to input * ...and the suits and ranks are fixed as the character labels specified here - If your language does not support such constructs just suggest something reasonable and ask if it is an acceptable alternative given your languages constraints. The output should either be * formatted the same as the input, or a printed representation thereof; or * be one of three distinct and consistent results (e.g.: `"left"`, `"right"`, `"both"`; or `1`, `2`, `3`; etc.) Really - so long as it is clear which of the two inputs are being identified it should be fine. ### Test cases ``` input -> output (notes) ---------------------------------------------------------------------------- 3c 2s 4d Ah - As 3h 2d 4h -> 3c 2s 4d Ah (4-card 4-3-2-A beats 3-card 3-2-A) 3c 2s 4d Ah - As 2c 3d 4h -> 3c 2s 4d Ah - As 2c 3d 4h (4-card 4-3-2-A draws with 4-card 4-3-2-A) 2d Ac 4h 3c - Kh Ad 9s 2c -> Kh Ad 9s 2c (3-card 4-2-A loses to 4-card K-9-2-A) Kc Tc Qc Jc - Ac Ad Ah As -> Ac Ad Ah As (1-card T loses to 1-card A) 9c 9h Qc Qh - Qs Kh Jh Kd -> Qs Kh Jh Kd (2-card Q-9 loses to 3-card K-Q-J) 2d 5h 7c 5s - 2h 3c 8d 6c -> 2d 5h 7c 5s (3-card 7-5-2 beats 3-card 8-3-2) 3s 6c 2d Js - 6h Jd 3c 2s -> 6h Jd 3c 2s (3-card 6-3-2 loses to 4-card J-6-3-2) Ah 6d 4d Ac - 3h 2c 3s 2s -> 3h 2c 3s 2s (2-card 4-A loses to 2-card 3-2) 2h 8h 6h 4h - 6d 2d 5d 8d -> 2h 8h 6h 4h - 6d 2d 5d 8d (1-card 2 = 1-card 2) ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins per-language, and the shortest code overall wins. Don't let golfing languages put you off submitting in other languages, and ...have fun!
2017/09/13
[ "https://codegolf.stackexchange.com/questions/142630", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/53748/" ]
[Perl 6](https://perl6.org), 128 bytes ====================================== ```perl6 {.map({.combinations(1..4).grep({!.join.comb.repeated}).map({-$_,$_».trans('ATK'=>'1BZ')».ord.sort(-*)}).min}).minpairs».key} ``` [Try it online!](https://tio.run/##dZLNTsJAFIXX8BSHpEmnpkwshQrhz7owkZoYElYSQupMsVWhONOYEMKTufPF8E6JRmucxSzu/c65PzPbRL0Ex/UO1grD456v4y3bc5GvH7JNXGT5RjOP87bDH1VCmQZ/yrNNmecUSOIikQfnpGpaS9dafrzzQsUks8NZZA9Htnd1bzsUzZXkOlcFa545RpJtTvc2zpSm/HOyO5hGLgsMweo1xga@QEujLRGmIxeDUMNP0ZJopyPHBTt3Hcf9B2wJ@D9AeF8oyUNBCfjCoFGKUKJnBCXqfXtGAjOBqcCkBEkUGn@EugL2BHqpAadl8akGmU5SRLICUulOiguBjjZgy/SArkQgquNoiplBJyUYkJ1EOWPFkdoJZDl32aPZDs2t/4JUq0tsajZiHKVx70iq/mtBTr@@ypV5gn29Zj6ForewVozPzxeUq@l4B0bB5PUNfO4tMB7DvotAx0ajAfs6vLmFTZaW6tcPx08 "Perl 6 – Try It Online") Takes a list of hands (also more than two) which are lists of cards which are strings like `Kc`. Returns the indices of the hands with the lowest score. For two hands this is `(0)` if the first hand wins, `(1)` if the second hand wins, and `(0, 1)` for a draw. Explained: ```perl6 { # Map hands to best "played hand". .map({ # Generate all combinations of length 1 to 4. .combinations(1..4) # Remove hands with repeated characters. .grep({!.join.comb.repeated}) # Map to a cmp-arable representation. This works because # lists are compared element-wise. Translate some characters # so that ASCII order works. Sort in reverse order so that # element-wise comparison will go from highest to lowest. .map({ -$_, $_».trans('ATK'=>'1BZ')».ord.sort(-*) }) # Find best hand. .min }) # Return indices of lowest scoring hands. It's a shame that # `minpairs` doesn't support a filter like `min`. .minpairs».key } ```
[Python 3](https://docs.python.org/3/), ~~207~~ 204 bytes ========================================================= ```python lambda i,j:L(h(i))-L(h(j))if L(h(i))!=L(h(j))else(h(i)<h(j))-(h(i)>h(j)) L=len def h(l):s=set();return[x[0]for x in sorted(y.translate({65:49,75:90,84:65})for y in l)if not(s&set(x)or s.update(*x))][::-1] ``` [Try it online!](https://tio.run/##jVI9b4MwEN35Fe5S7MqJUr4S3FKJNekSqRtloLERRAQoJhJR1d@e4rNJmk5leLbv3bt7Ptye@qKp3XMevZ@r7PDBM1TSPXvFBS4Jmal1T0iZIxO5i0xIVFJA6BmOM9i/wN56jSpRW1zkqMAVYTKSosfkqRP9sauTIVmkedOhAZU1kk3XC45P877LalllvcBfgc@8kC59Fi7oymOB/01U/knlV8pL3fRY3quiAxkJOT@2XCkfBkLShLHZY3oWQ3ZoKyFRhBKc2O7Opsh2pEKPK4wLO6UosWOIuQXwwHgjQ6j1D5UDvPtHpavEOxNVGTut2sApBj6cKhjVBvLfALeAa6PSleKpv0I5qULgwuKq2hqHW6ivO64BN/zWoQ/RJah8qVXO5HfEFWQFF4euNOfLpNZGFegu/Kp1Lg6144D/mqG5l5m5nqG8VWkfK60tpvlCL37t73PjMyWpZalH0tJP9Uymv88sNH5tV9Y9HimKcrUQcv4B "Python 3 – Try It Online") *Saved 3 bytes thanks to Jonathan Frech* Returns `1` if the first hand wins, `-1` if the second hand wins and `0` in case of a draw. The function `h` computes a list that represents the hand. The lambda compares two representations of hand. I think it might be shortened, but I wanted to return only three values and didn't find a simpler way to do comparison.
142,630
Inspired by [this challenge](https://codegolf.stackexchange.com/questions/140854/1326-starting-holdem-combos) and related to [this one](https://codegolf.stackexchange.com/questions/25056/compare-two-poker-hands). ### Background Badugi [bæduːɡiː] is a low-ball draw-poker variant. The Pokerstars World Cup Of Online Poker **$1K** event starts within **3** hours and I'll need to know how good my hands are! The game uses a standard deck of **52** cards of four suits and thirteen ranks. The suits are unordered and shall be labelled `cdhs`; the ranks - ordered from highest `K` to lowest `A` - are `KQJT98765432A`. As such the full deck may be represented as follows (space separated): ``` Kc Kd Kh Ks Qc Qd Qh Qs Jc Jd Jh Js Tc Td Th Ts 9c 9d 9h 9s 8c 8d 8h 8s 7c 7d 7h 7s 6c 6d 6h 6s 5c 5d 5h 5s 4c 4d 4h 4s 3c 3d 3h 3s 2c 2d 2h 2s Ac Ad Ah As ``` Each player is dealt **four** cards from the deck, there are four betting rounds with three drawing rounds in-between (a player always has four cards, they have the option of changing 0-4 of their cards with new ones from the dealer on each of the three drawing rounds). If more than one player is still active after all these rounds there is a showdown, whereupon the strongest hand(s) win the wagered bets. The game is played low-ball, so the lowest hand wins, and as mentioned above `A` (ace) is low. Furthermore the hand ranking is different from other forms of poker, and can be somewhat confusing for beginners. The played "hand" is the lowest ranked combination made from the highest number of both "off-suit" (all-different-suits) and "off-rank" (all-different-ranks) cards possible (from the four held cards). That is: if one holds four cards of both distinct suits *and* distinct ranks one has a 4-card hand (called a "badugi"); if one does not have a 4-card hand but does have some set or sets of three cards of both distinct suits *and* distinct ranks one has a 3-card hand (one chooses their best); if one has neither a 4-card hand or a 3-card hand one probably has a 2-card hand, but if not one has a 1-card hand. * As such the best possible hand is the 4-card hand `4-3-2-A` - the lowest **off-rank** cards of **four different suits**, often termed a "number-1". The weakest possible hand would be the 1-card hand `K` and is only possible by holding exactly `Kc Kd Kh Ks`. * Note that `4c 3h 2c As` is **not** a "number-1", since the `4c` and `2c` are of the same suit, but it *is* the strongest of the 3-card hands, `3-2-A`, it draws with other `3-2-1`s (like `Kh 3d 2s Ah`) and beats all other 3-card hands but loses to all 4-card hands (which could be as weak as `K-Q-J-T`). + The other possible 3-card hand that could be made from `4c 3h 2c As` is `4-3-A`, but that is weaker (higher) so not chosen. * Similarly `8d 6h 3s 2h` is a 3-card hand played as `8-3-2` - there are two off-rank off-suit combinations of size 3 and `8-3-2` is better (lower) than `8-6-3` since the three (or "trey") is lower than the six. Comparing hands against one another follows the same logic - any 4-card beats any 3-card, any 3-card beats any 2-card and any 2-card beats any 1-card, while hands of the same number of used cards are compared from their highest rank down to their lowest (for example: `8-4-2` beats `8-5-A` but not any of `8-4-A`, `8-3-2` or `7-6-5`) ### The challenge: Given two unordered-collections each of four cards, identify the one(s) which win a Badugi showdown (identify both if it is a draw). The input may be anything reasonable: * a single string of all eight cards as labelled above (with or without spaces) with the left four being one hand and the right the other (with an optional separator); or a list of characters in the same fashion * a list of two strings - one per hand, or a list of lists of characters in the same fashion * two separate strings or list inputs, one per hand * the cards within the hands may be separated already too (so a list of lists of lists is fine) Note, however: * the cards may not be arranged into any order prior to input * ...and the suits and ranks are fixed as the character labels specified here - If your language does not support such constructs just suggest something reasonable and ask if it is an acceptable alternative given your languages constraints. The output should either be * formatted the same as the input, or a printed representation thereof; or * be one of three distinct and consistent results (e.g.: `"left"`, `"right"`, `"both"`; or `1`, `2`, `3`; etc.) Really - so long as it is clear which of the two inputs are being identified it should be fine. ### Test cases ``` input -> output (notes) ---------------------------------------------------------------------------- 3c 2s 4d Ah - As 3h 2d 4h -> 3c 2s 4d Ah (4-card 4-3-2-A beats 3-card 3-2-A) 3c 2s 4d Ah - As 2c 3d 4h -> 3c 2s 4d Ah - As 2c 3d 4h (4-card 4-3-2-A draws with 4-card 4-3-2-A) 2d Ac 4h 3c - Kh Ad 9s 2c -> Kh Ad 9s 2c (3-card 4-2-A loses to 4-card K-9-2-A) Kc Tc Qc Jc - Ac Ad Ah As -> Ac Ad Ah As (1-card T loses to 1-card A) 9c 9h Qc Qh - Qs Kh Jh Kd -> Qs Kh Jh Kd (2-card Q-9 loses to 3-card K-Q-J) 2d 5h 7c 5s - 2h 3c 8d 6c -> 2d 5h 7c 5s (3-card 7-5-2 beats 3-card 8-3-2) 3s 6c 2d Js - 6h Jd 3c 2s -> 6h Jd 3c 2s (3-card 6-3-2 loses to 4-card J-6-3-2) Ah 6d 4d Ac - 3h 2c 3s 2s -> 3h 2c 3s 2s (2-card 4-A loses to 2-card 3-2) 2h 8h 6h 4h - 6d 2d 5d 8d -> 2h 8h 6h 4h - 6d 2d 5d 8d (1-card 2 = 1-card 2) ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins per-language, and the shortest code overall wins. Don't let golfing languages put you off submitting in other languages, and ...have fun!
2017/09/13
[ "https://codegolf.stackexchange.com/questions/142630", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/53748/" ]
[Perl 6](https://perl6.org), 128 bytes ====================================== ```perl6 {.map({.combinations(1..4).grep({!.join.comb.repeated}).map({-$_,$_».trans('ATK'=>'1BZ')».ord.sort(-*)}).min}).minpairs».key} ``` [Try it online!](https://tio.run/##dZLNTsJAFIXX8BSHpEmnpkwshQrhz7owkZoYElYSQupMsVWhONOYEMKTufPF8E6JRmucxSzu/c65PzPbRL0Ex/UO1grD456v4y3bc5GvH7JNXGT5RjOP87bDH1VCmQZ/yrNNmecUSOIikQfnpGpaS9dafrzzQsUks8NZZA9Htnd1bzsUzZXkOlcFa545RpJtTvc2zpSm/HOyO5hGLgsMweo1xga@QEujLRGmIxeDUMNP0ZJopyPHBTt3Hcf9B2wJ@D9AeF8oyUNBCfjCoFGKUKJnBCXqfXtGAjOBqcCkBEkUGn@EugL2BHqpAadl8akGmU5SRLICUulOiguBjjZgy/SArkQgquNoiplBJyUYkJ1EOWPFkdoJZDl32aPZDs2t/4JUq0tsajZiHKVx70iq/mtBTr@@ypV5gn29Zj6ForewVozPzxeUq@l4B0bB5PUNfO4tMB7DvotAx0ajAfs6vLmFTZaW6tcPx08 "Perl 6 – Try It Online") Takes a list of hands (also more than two) which are lists of cards which are strings like `Kc`. Returns the indices of the hands with the lowest score. For two hands this is `(0)` if the first hand wins, `(1)` if the second hand wins, and `(0, 1)` for a draw. Explained: ```perl6 { # Map hands to best "played hand". .map({ # Generate all combinations of length 1 to 4. .combinations(1..4) # Remove hands with repeated characters. .grep({!.join.comb.repeated}) # Map to a cmp-arable representation. This works because # lists are compared element-wise. Translate some characters # so that ASCII order works. Sort in reverse order so that # element-wise comparison will go from highest to lowest. .map({ -$_, $_».trans('ATK'=>'1BZ')».ord.sort(-*) }) # Find best hand. .min }) # Return indices of lowest scoring hands. It's a shame that # `minpairs` doesn't support a filter like `min`. .minpairs».key } ```
[Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ==================================================================================================================== ``` ẎŒQȦ;L;Ṗ€Ṣ$ “A+KYTE”yḲONŒPÇ€ṢṪµ€⁼€Ṁ$ ``` A monadic link taking a list of two lists of characters - each being a space separated representation of the hand (e.g. `"Ac 2d 4s 3h"`) returning a list of two numbers identifying the winner(s) with `1` and any loser with `0` - i.e. `[1, 0]` = left wins; `[0, 1]` = right wins; `[1, 1]` = draw. **[Try it online!](https://tio.run/##y0rNyan8///hrr6jkwJPLLP2sX64c9qjpjUPdy5S4XrUMMdR2zsyxPVRw9zKhzs2@fsdnRRwuB0i/XDnqkNbgcxHjXvAAg0q////j1YySlEwzVAwT1YwLVbSUVAyylAwTlawSFEwS1aKBQA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##bY@xS8NAFMb3/hUfoZsVNGlqY6cbXBJRA11KyXQnHKHbTd2ii5tDBnGoi0MHcRIEI50qgf4bl38kvndG6uBw8O59v/d97@XXi8Wybe3nfV2mu/XkfGKrh@b21VbP/V5TrMRBMpueNcXT0n68XV7U5dXX3Y9sq5ftO5XNzcY1in5bb5yY0zverlkrVjgETdelrR6pceTaeSedsjRr2/ncCyR8g6GC0N4AnjAINHyFofayQQ//Ab5E8AcgWEj6IpAMJBpCIWKsAxKJqUQqETuAYMFuEKYDIolIM5C6iNSATGKNRO0jQo0TidAw4HMWxgqj34jAUM1rxw4Y0biC27wDKG6k3BVuB76RrjB7gDzHxGi@ix0Uu4WKUrws@wY "Jelly – Try It Online"). ### How? ``` ẎŒQȦ;L;Ṗ€Ṣ$ - Link 1, sortKey: list of lists of numbers representing some cards (see Main) Ẏ - flatten into a single list of numbers ŒQ - distinct sieve (1 at first occurrence of anything, 0 at the rest) Ȧ - Any & All? zero if any are 0 or if empty; 1 otherwise (i.e. playable hand?) L - length of input (number of cards in the hand) ; - concatenate $ - last two links as a monad: Ṗ€ - pop each (get just the rank portions) Ṣ - sort (Main's translation & negation of ordinals ensures A>2>3>...>Q>K) ; - concatenate (now we have [isPlayable; nCards; [lowToHighCards]]) “A+KYTE”yḲONŒPÇ€ṢṪµ€⁼€Ṁ$ - Main link: list of lists of characters, hands µ€ - for €ach of the two hands: “A+KYTE” - literal list of characters "A+KYTE" (compressing doesn't help - lower case would be “£Ḅṁ⁽>» though -- I'll stick with kyte though it's kind of nice.) y - translate - change As to +s, Ks to Ys and Ts to Es - note the ranks are now in ordinal order: - +<2<3<4<5<6<7<8<9<E<J<Q<Y Ḳ - split at spaces - split the four cards up O - to ordinals '+'->43, '2'->50, ... N - negate - effectively reverse the ordering ŒP - power-set - get all combinations of 0 to 4 cards inclusive Ç€ - call the last link (1) as a monad for €ach such selection Ṣ - sort these keys Ṫ - tail - get (one of) the maximal keys - (the key of a best, playable selection) $ - last two links as a monad: Ṁ - maximum (the better of the two best, playable selection keys) ⁼€ - equals? for €ach (1 if the hand is a winner, 0 if not) ```
142,630
Inspired by [this challenge](https://codegolf.stackexchange.com/questions/140854/1326-starting-holdem-combos) and related to [this one](https://codegolf.stackexchange.com/questions/25056/compare-two-poker-hands). ### Background Badugi [bæduːɡiː] is a low-ball draw-poker variant. The Pokerstars World Cup Of Online Poker **$1K** event starts within **3** hours and I'll need to know how good my hands are! The game uses a standard deck of **52** cards of four suits and thirteen ranks. The suits are unordered and shall be labelled `cdhs`; the ranks - ordered from highest `K` to lowest `A` - are `KQJT98765432A`. As such the full deck may be represented as follows (space separated): ``` Kc Kd Kh Ks Qc Qd Qh Qs Jc Jd Jh Js Tc Td Th Ts 9c 9d 9h 9s 8c 8d 8h 8s 7c 7d 7h 7s 6c 6d 6h 6s 5c 5d 5h 5s 4c 4d 4h 4s 3c 3d 3h 3s 2c 2d 2h 2s Ac Ad Ah As ``` Each player is dealt **four** cards from the deck, there are four betting rounds with three drawing rounds in-between (a player always has four cards, they have the option of changing 0-4 of their cards with new ones from the dealer on each of the three drawing rounds). If more than one player is still active after all these rounds there is a showdown, whereupon the strongest hand(s) win the wagered bets. The game is played low-ball, so the lowest hand wins, and as mentioned above `A` (ace) is low. Furthermore the hand ranking is different from other forms of poker, and can be somewhat confusing for beginners. The played "hand" is the lowest ranked combination made from the highest number of both "off-suit" (all-different-suits) and "off-rank" (all-different-ranks) cards possible (from the four held cards). That is: if one holds four cards of both distinct suits *and* distinct ranks one has a 4-card hand (called a "badugi"); if one does not have a 4-card hand but does have some set or sets of three cards of both distinct suits *and* distinct ranks one has a 3-card hand (one chooses their best); if one has neither a 4-card hand or a 3-card hand one probably has a 2-card hand, but if not one has a 1-card hand. * As such the best possible hand is the 4-card hand `4-3-2-A` - the lowest **off-rank** cards of **four different suits**, often termed a "number-1". The weakest possible hand would be the 1-card hand `K` and is only possible by holding exactly `Kc Kd Kh Ks`. * Note that `4c 3h 2c As` is **not** a "number-1", since the `4c` and `2c` are of the same suit, but it *is* the strongest of the 3-card hands, `3-2-A`, it draws with other `3-2-1`s (like `Kh 3d 2s Ah`) and beats all other 3-card hands but loses to all 4-card hands (which could be as weak as `K-Q-J-T`). + The other possible 3-card hand that could be made from `4c 3h 2c As` is `4-3-A`, but that is weaker (higher) so not chosen. * Similarly `8d 6h 3s 2h` is a 3-card hand played as `8-3-2` - there are two off-rank off-suit combinations of size 3 and `8-3-2` is better (lower) than `8-6-3` since the three (or "trey") is lower than the six. Comparing hands against one another follows the same logic - any 4-card beats any 3-card, any 3-card beats any 2-card and any 2-card beats any 1-card, while hands of the same number of used cards are compared from their highest rank down to their lowest (for example: `8-4-2` beats `8-5-A` but not any of `8-4-A`, `8-3-2` or `7-6-5`) ### The challenge: Given two unordered-collections each of four cards, identify the one(s) which win a Badugi showdown (identify both if it is a draw). The input may be anything reasonable: * a single string of all eight cards as labelled above (with or without spaces) with the left four being one hand and the right the other (with an optional separator); or a list of characters in the same fashion * a list of two strings - one per hand, or a list of lists of characters in the same fashion * two separate strings or list inputs, one per hand * the cards within the hands may be separated already too (so a list of lists of lists is fine) Note, however: * the cards may not be arranged into any order prior to input * ...and the suits and ranks are fixed as the character labels specified here - If your language does not support such constructs just suggest something reasonable and ask if it is an acceptable alternative given your languages constraints. The output should either be * formatted the same as the input, or a printed representation thereof; or * be one of three distinct and consistent results (e.g.: `"left"`, `"right"`, `"both"`; or `1`, `2`, `3`; etc.) Really - so long as it is clear which of the two inputs are being identified it should be fine. ### Test cases ``` input -> output (notes) ---------------------------------------------------------------------------- 3c 2s 4d Ah - As 3h 2d 4h -> 3c 2s 4d Ah (4-card 4-3-2-A beats 3-card 3-2-A) 3c 2s 4d Ah - As 2c 3d 4h -> 3c 2s 4d Ah - As 2c 3d 4h (4-card 4-3-2-A draws with 4-card 4-3-2-A) 2d Ac 4h 3c - Kh Ad 9s 2c -> Kh Ad 9s 2c (3-card 4-2-A loses to 4-card K-9-2-A) Kc Tc Qc Jc - Ac Ad Ah As -> Ac Ad Ah As (1-card T loses to 1-card A) 9c 9h Qc Qh - Qs Kh Jh Kd -> Qs Kh Jh Kd (2-card Q-9 loses to 3-card K-Q-J) 2d 5h 7c 5s - 2h 3c 8d 6c -> 2d 5h 7c 5s (3-card 7-5-2 beats 3-card 8-3-2) 3s 6c 2d Js - 6h Jd 3c 2s -> 6h Jd 3c 2s (3-card 6-3-2 loses to 4-card J-6-3-2) Ah 6d 4d Ac - 3h 2c 3s 2s -> 3h 2c 3s 2s (2-card 4-A loses to 2-card 3-2) 2h 8h 6h 4h - 6d 2d 5d 8d -> 2h 8h 6h 4h - 6d 2d 5d 8d (1-card 2 = 1-card 2) ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins per-language, and the shortest code overall wins. Don't let golfing languages put you off submitting in other languages, and ...have fun!
2017/09/13
[ "https://codegolf.stackexchange.com/questions/142630", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/53748/" ]
JavaScript (ES6), ~~209~~ ~~202~~ ~~192~~ ~~182~~ 181 bytes =========================================================== *Saved 7 bytes thanks to @Neil* Takes input as an array of arrays of strings. Returns `true` if the first hand wins, `false` if the second hand wins, or `2` in the event of a tie. ```js a=>([a,b]=a.map(a=>a.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).map(a=>!/(\w).*\1/.test(a)*a.length+a.map(a=>'KQJT98765432A'.search(a[0])+10).sort()).sort().pop()),a==b?2:a>b) ``` ### Test cases ```js let f = a=>([a,b]=a.map(a=>a.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).map(a=>!/(\w).*\1/.test(a)*a.length+a.map(a=>'KQJT98765432A'.search(a[0])+10).sort()).sort().pop()),a==b?2:a>b) console.log(f([["3c","2s","4d","Ah"], ["As","3h","2d","4h"]])) // true (1st hand wins) console.log(f([["3c","2s","4d","Ah"], ["As","2c","3d","4h"]])) // 2 (tie) console.log(f([["2d","Ac","4h","3c"], ["Kh","Ad","9s","2c"]])) // false (2nd hand wins) console.log(f([["Kc","Tc","Qc","Jc"], ["Ac","Ad","Ah","As"]])) // false (2nd hand wins) console.log(f([["9c","9h","Qc","Qh"], ["Qs","Kh","Jh","Kd"]])) // false (2nd hand wins) console.log(f([["2d","5h","7c","5s"], ["2h","3c","8d","6c"]])) // true (1st hand wins) console.log(f([["3s","6c","2d","Js"], ["6h","Jd","3c","2s"]])) // false (2nd hand wins) console.log(f([["Ah","6d","4d","Ac"], ["3h","2c","3s","2s"]])) // false (2nd hand wins) console.log(f([["2h","8h","6h","4h"], ["6d","2d","5d","8d"]])) // 2 (tie) ``` ### How? ```js a => ( // store the best combination for both hands in a and b respectively [a, b] = a.map(a => // compute the powerset of the hand a.reduce((a, x) => [...a, ...a.map(y => [x, ...y])], [[]]) // for each entry: .map(a => // invalidate entries that have at least 2 cards of same rank or same value !/(\w).*\1/.test(a) * // the score of valid entries is based on their length ... a.length + // ... and their card values, from highest to lowest // (we map 'KQJT98765432A' to [10 - 22], so that the resulting // strings can be safely sorted in lexicographical order) a.map(a => 'KQJT98765432A'.search(a[0]) + 10).sort() ) // keep the best one .sort().pop() ), // compare a with b a == b ? 2 : a > b ) ```
[Python 3](https://docs.python.org/3/), ~~207~~ 204 bytes ========================================================= ```python lambda i,j:L(h(i))-L(h(j))if L(h(i))!=L(h(j))else(h(i)<h(j))-(h(i)>h(j)) L=len def h(l):s=set();return[x[0]for x in sorted(y.translate({65:49,75:90,84:65})for y in l)if not(s&set(x)or s.update(*x))][::-1] ``` [Try it online!](https://tio.run/##jVI9b4MwEN35Fe5S7MqJUr4S3FKJNekSqRtloLERRAQoJhJR1d@e4rNJmk5leLbv3bt7Ptye@qKp3XMevZ@r7PDBM1TSPXvFBS4Jmal1T0iZIxO5i0xIVFJA6BmOM9i/wN56jSpRW1zkqMAVYTKSosfkqRP9sauTIVmkedOhAZU1kk3XC45P877LalllvcBfgc@8kC59Fi7oymOB/01U/knlV8pL3fRY3quiAxkJOT@2XCkfBkLShLHZY3oWQ3ZoKyFRhBKc2O7Opsh2pEKPK4wLO6UosWOIuQXwwHgjQ6j1D5UDvPtHpavEOxNVGTut2sApBj6cKhjVBvLfALeAa6PSleKpv0I5qULgwuKq2hqHW6ivO64BN/zWoQ/RJah8qVXO5HfEFWQFF4euNOfLpNZGFegu/Kp1Lg6144D/mqG5l5m5nqG8VWkfK60tpvlCL37t73PjMyWpZalH0tJP9Uymv88sNH5tV9Y9HimKcrUQcv4B "Python 3 – Try It Online") *Saved 3 bytes thanks to Jonathan Frech* Returns `1` if the first hand wins, `-1` if the second hand wins and `0` in case of a draw. The function `h` computes a list that represents the hand. The lambda compares two representations of hand. I think it might be shortened, but I wanted to return only three values and didn't find a simpler way to do comparison.
142,630
Inspired by [this challenge](https://codegolf.stackexchange.com/questions/140854/1326-starting-holdem-combos) and related to [this one](https://codegolf.stackexchange.com/questions/25056/compare-two-poker-hands). ### Background Badugi [bæduːɡiː] is a low-ball draw-poker variant. The Pokerstars World Cup Of Online Poker **$1K** event starts within **3** hours and I'll need to know how good my hands are! The game uses a standard deck of **52** cards of four suits and thirteen ranks. The suits are unordered and shall be labelled `cdhs`; the ranks - ordered from highest `K` to lowest `A` - are `KQJT98765432A`. As such the full deck may be represented as follows (space separated): ``` Kc Kd Kh Ks Qc Qd Qh Qs Jc Jd Jh Js Tc Td Th Ts 9c 9d 9h 9s 8c 8d 8h 8s 7c 7d 7h 7s 6c 6d 6h 6s 5c 5d 5h 5s 4c 4d 4h 4s 3c 3d 3h 3s 2c 2d 2h 2s Ac Ad Ah As ``` Each player is dealt **four** cards from the deck, there are four betting rounds with three drawing rounds in-between (a player always has four cards, they have the option of changing 0-4 of their cards with new ones from the dealer on each of the three drawing rounds). If more than one player is still active after all these rounds there is a showdown, whereupon the strongest hand(s) win the wagered bets. The game is played low-ball, so the lowest hand wins, and as mentioned above `A` (ace) is low. Furthermore the hand ranking is different from other forms of poker, and can be somewhat confusing for beginners. The played "hand" is the lowest ranked combination made from the highest number of both "off-suit" (all-different-suits) and "off-rank" (all-different-ranks) cards possible (from the four held cards). That is: if one holds four cards of both distinct suits *and* distinct ranks one has a 4-card hand (called a "badugi"); if one does not have a 4-card hand but does have some set or sets of three cards of both distinct suits *and* distinct ranks one has a 3-card hand (one chooses their best); if one has neither a 4-card hand or a 3-card hand one probably has a 2-card hand, but if not one has a 1-card hand. * As such the best possible hand is the 4-card hand `4-3-2-A` - the lowest **off-rank** cards of **four different suits**, often termed a "number-1". The weakest possible hand would be the 1-card hand `K` and is only possible by holding exactly `Kc Kd Kh Ks`. * Note that `4c 3h 2c As` is **not** a "number-1", since the `4c` and `2c` are of the same suit, but it *is* the strongest of the 3-card hands, `3-2-A`, it draws with other `3-2-1`s (like `Kh 3d 2s Ah`) and beats all other 3-card hands but loses to all 4-card hands (which could be as weak as `K-Q-J-T`). + The other possible 3-card hand that could be made from `4c 3h 2c As` is `4-3-A`, but that is weaker (higher) so not chosen. * Similarly `8d 6h 3s 2h` is a 3-card hand played as `8-3-2` - there are two off-rank off-suit combinations of size 3 and `8-3-2` is better (lower) than `8-6-3` since the three (or "trey") is lower than the six. Comparing hands against one another follows the same logic - any 4-card beats any 3-card, any 3-card beats any 2-card and any 2-card beats any 1-card, while hands of the same number of used cards are compared from their highest rank down to their lowest (for example: `8-4-2` beats `8-5-A` but not any of `8-4-A`, `8-3-2` or `7-6-5`) ### The challenge: Given two unordered-collections each of four cards, identify the one(s) which win a Badugi showdown (identify both if it is a draw). The input may be anything reasonable: * a single string of all eight cards as labelled above (with or without spaces) with the left four being one hand and the right the other (with an optional separator); or a list of characters in the same fashion * a list of two strings - one per hand, or a list of lists of characters in the same fashion * two separate strings or list inputs, one per hand * the cards within the hands may be separated already too (so a list of lists of lists is fine) Note, however: * the cards may not be arranged into any order prior to input * ...and the suits and ranks are fixed as the character labels specified here - If your language does not support such constructs just suggest something reasonable and ask if it is an acceptable alternative given your languages constraints. The output should either be * formatted the same as the input, or a printed representation thereof; or * be one of three distinct and consistent results (e.g.: `"left"`, `"right"`, `"both"`; or `1`, `2`, `3`; etc.) Really - so long as it is clear which of the two inputs are being identified it should be fine. ### Test cases ``` input -> output (notes) ---------------------------------------------------------------------------- 3c 2s 4d Ah - As 3h 2d 4h -> 3c 2s 4d Ah (4-card 4-3-2-A beats 3-card 3-2-A) 3c 2s 4d Ah - As 2c 3d 4h -> 3c 2s 4d Ah - As 2c 3d 4h (4-card 4-3-2-A draws with 4-card 4-3-2-A) 2d Ac 4h 3c - Kh Ad 9s 2c -> Kh Ad 9s 2c (3-card 4-2-A loses to 4-card K-9-2-A) Kc Tc Qc Jc - Ac Ad Ah As -> Ac Ad Ah As (1-card T loses to 1-card A) 9c 9h Qc Qh - Qs Kh Jh Kd -> Qs Kh Jh Kd (2-card Q-9 loses to 3-card K-Q-J) 2d 5h 7c 5s - 2h 3c 8d 6c -> 2d 5h 7c 5s (3-card 7-5-2 beats 3-card 8-3-2) 3s 6c 2d Js - 6h Jd 3c 2s -> 6h Jd 3c 2s (3-card 6-3-2 loses to 4-card J-6-3-2) Ah 6d 4d Ac - 3h 2c 3s 2s -> 3h 2c 3s 2s (2-card 4-A loses to 2-card 3-2) 2h 8h 6h 4h - 6d 2d 5d 8d -> 2h 8h 6h 4h - 6d 2d 5d 8d (1-card 2 = 1-card 2) ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins per-language, and the shortest code overall wins. Don't let golfing languages put you off submitting in other languages, and ...have fun!
2017/09/13
[ "https://codegolf.stackexchange.com/questions/142630", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/53748/" ]
JavaScript (ES6), ~~209~~ ~~202~~ ~~192~~ ~~182~~ 181 bytes =========================================================== *Saved 7 bytes thanks to @Neil* Takes input as an array of arrays of strings. Returns `true` if the first hand wins, `false` if the second hand wins, or `2` in the event of a tie. ```js a=>([a,b]=a.map(a=>a.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).map(a=>!/(\w).*\1/.test(a)*a.length+a.map(a=>'KQJT98765432A'.search(a[0])+10).sort()).sort().pop()),a==b?2:a>b) ``` ### Test cases ```js let f = a=>([a,b]=a.map(a=>a.reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).map(a=>!/(\w).*\1/.test(a)*a.length+a.map(a=>'KQJT98765432A'.search(a[0])+10).sort()).sort().pop()),a==b?2:a>b) console.log(f([["3c","2s","4d","Ah"], ["As","3h","2d","4h"]])) // true (1st hand wins) console.log(f([["3c","2s","4d","Ah"], ["As","2c","3d","4h"]])) // 2 (tie) console.log(f([["2d","Ac","4h","3c"], ["Kh","Ad","9s","2c"]])) // false (2nd hand wins) console.log(f([["Kc","Tc","Qc","Jc"], ["Ac","Ad","Ah","As"]])) // false (2nd hand wins) console.log(f([["9c","9h","Qc","Qh"], ["Qs","Kh","Jh","Kd"]])) // false (2nd hand wins) console.log(f([["2d","5h","7c","5s"], ["2h","3c","8d","6c"]])) // true (1st hand wins) console.log(f([["3s","6c","2d","Js"], ["6h","Jd","3c","2s"]])) // false (2nd hand wins) console.log(f([["Ah","6d","4d","Ac"], ["3h","2c","3s","2s"]])) // false (2nd hand wins) console.log(f([["2h","8h","6h","4h"], ["6d","2d","5d","8d"]])) // 2 (tie) ``` ### How? ```js a => ( // store the best combination for both hands in a and b respectively [a, b] = a.map(a => // compute the powerset of the hand a.reduce((a, x) => [...a, ...a.map(y => [x, ...y])], [[]]) // for each entry: .map(a => // invalidate entries that have at least 2 cards of same rank or same value !/(\w).*\1/.test(a) * // the score of valid entries is based on their length ... a.length + // ... and their card values, from highest to lowest // (we map 'KQJT98765432A' to [10 - 22], so that the resulting // strings can be safely sorted in lexicographical order) a.map(a => 'KQJT98765432A'.search(a[0]) + 10).sort() ) // keep the best one .sort().pop() ), // compare a with b a == b ? 2 : a > b ) ```
[Jelly](https://github.com/DennisMitchell/jelly), 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ==================================================================================================================== ``` ẎŒQȦ;L;Ṗ€Ṣ$ “A+KYTE”yḲONŒPÇ€ṢṪµ€⁼€Ṁ$ ``` A monadic link taking a list of two lists of characters - each being a space separated representation of the hand (e.g. `"Ac 2d 4s 3h"`) returning a list of two numbers identifying the winner(s) with `1` and any loser with `0` - i.e. `[1, 0]` = left wins; `[0, 1]` = right wins; `[1, 1]` = draw. **[Try it online!](https://tio.run/##y0rNyan8///hrr6jkwJPLLP2sX64c9qjpjUPdy5S4XrUMMdR2zsyxPVRw9zKhzs2@fsdnRRwuB0i/XDnqkNbgcxHjXvAAg0q////j1YySlEwzVAwT1YwLVbSUVAyylAwTlawSFEwS1aKBQA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##bY@xS8NAFMb3/hUfoZsVNGlqY6cbXBJRA11KyXQnHKHbTd2ii5tDBnGoi0MHcRIEI50qgf4bl38kvndG6uBw8O59v/d97@XXi8Wybe3nfV2mu/XkfGKrh@b21VbP/V5TrMRBMpueNcXT0n68XV7U5dXX3Y9sq5ftO5XNzcY1in5bb5yY0zverlkrVjgETdelrR6pceTaeSedsjRr2/ncCyR8g6GC0N4AnjAINHyFofayQQ//Ab5E8AcgWEj6IpAMJBpCIWKsAxKJqUQqETuAYMFuEKYDIolIM5C6iNSATGKNRO0jQo0TidAw4HMWxgqj34jAUM1rxw4Y0biC27wDKG6k3BVuB76RrjB7gDzHxGi@ix0Uu4WKUrws@wY "Jelly – Try It Online"). ### How? ``` ẎŒQȦ;L;Ṗ€Ṣ$ - Link 1, sortKey: list of lists of numbers representing some cards (see Main) Ẏ - flatten into a single list of numbers ŒQ - distinct sieve (1 at first occurrence of anything, 0 at the rest) Ȧ - Any & All? zero if any are 0 or if empty; 1 otherwise (i.e. playable hand?) L - length of input (number of cards in the hand) ; - concatenate $ - last two links as a monad: Ṗ€ - pop each (get just the rank portions) Ṣ - sort (Main's translation & negation of ordinals ensures A>2>3>...>Q>K) ; - concatenate (now we have [isPlayable; nCards; [lowToHighCards]]) “A+KYTE”yḲONŒPÇ€ṢṪµ€⁼€Ṁ$ - Main link: list of lists of characters, hands µ€ - for €ach of the two hands: “A+KYTE” - literal list of characters "A+KYTE" (compressing doesn't help - lower case would be “£Ḅṁ⁽>» though -- I'll stick with kyte though it's kind of nice.) y - translate - change As to +s, Ks to Ys and Ts to Es - note the ranks are now in ordinal order: - +<2<3<4<5<6<7<8<9<E<J<Q<Y Ḳ - split at spaces - split the four cards up O - to ordinals '+'->43, '2'->50, ... N - negate - effectively reverse the ordering ŒP - power-set - get all combinations of 0 to 4 cards inclusive Ç€ - call the last link (1) as a monad for €ach such selection Ṣ - sort these keys Ṫ - tail - get (one of) the maximal keys - (the key of a best, playable selection) $ - last two links as a monad: Ṁ - maximum (the better of the two best, playable selection keys) ⁼€ - equals? for €ach (1 if the hand is a winner, 0 if not) ```
11,769,159
I am using the following CSS code within a html page in order to set the H1 and H2 color values. ``` <style type="text/css"> img {border-style: none;} H1 {color: "#33CCFF"} H2 {color: "#33CCFF"} </style> ``` This is working fine for Internet explorer, but is failing for Chrome, Safari, and Firefox. How do I fix this issue to support all browsers? Thanks
2012/08/01
[ "https://Stackoverflow.com/questions/11769159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1385852/" ]
you need remove '"' around color * ; goes at the end of the css declaration always, like this: H1 {color:#FFF;width:100%;} H1#ID.class {color:#FFF;width:100%;} <==== right order for combining ID's + Class
You need to remove the quotes as Voodoo says, but you should also really be closing the color declaration with a semicolon (;). It may work without it, but you're really asking for trouble. ;)
23,944,108
I would like to share a common version variable between an sbtPlugin and the rest of the build Here is what I am trying: in `project/Build.scala`: ``` object Versions { scalaJs = "0.5.0-M3" } object MyBuild extends Build { //Use version number } ``` in `plugins.sbt`: ``` addSbtPlugin("org.scala-lang.modules.scalajs" % "scalajs-sbt-plugin" % Versions.scalaJs) ``` results in ``` plugins.sbt:15: error: not found: value Versions addSbtPlugin("org.scala-lang.modules.scalajs" % "scalajs-sbt-plugin" % Versions.scalaJs) ``` Is there a way to share the version number specification between `plugins.sbt` and the rest of the build, e.g. `project/Build.scala`?
2014/05/29
[ "https://Stackoverflow.com/questions/23944108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121477/" ]
For the `project/plugins.sbt` file you'd have to have another `project` under `project` with the `Versions.scala` file. That would make the definition of `Versions.scalaJs` visible. The reason for doing it is that `*.sbt` files belong to a project build definition at the current level with `*.scala` files under `project` to expand on it. And it's...[turtles all the way down](http://en.wikipedia.org/wiki/Turtles_all_the_way_down), i.e. [sbt is recursive](http://www.scala-sbt.org/release/docs/Getting-Started/Full-Def.html#sbt-is-recursive). I'm not sure how much the following can help, but it might be worth to try out - to share versions between projects - `plugins` and the main one - you'd have to use `ProjectRef` as described in the answer to [RootProject and ProjectRef](https://stackoverflow.com/q/19469708/1305344): > > When you want to include other, separate builds directly instead of > using their published binaries, you use "source dependencies". This is > what `RootProject` and `ProjectRef` declare. `ProjectRef` is the most > general: you specify the location of the build (a URI) and the ID of > the project in the build (a String) that you want to depend on. > `RootProject` is a convenience that selects the root project for the > build at the URI you specify. > > >
My proposal is to hack. For example, in `build.sbt` you can add a task: ``` val readPluginSbt = taskKey[String]("Read plugins.sbt file.") readPluginSbt := { val lineIterator = scala.io.Source.fromFile(new java.io.File("project","plugins.sbt")).getLines val linesWithValIterator = lineIterator.filter(line => line.contains("scalaxbVersion")) val versionString = linesWithValIterator.mkString("\n").split("=")(1).trim val version = versionString.split("\n")(0) // only val declaration println(version) version } ``` When you call `readPluginSbt` you will see the contents of `plugins.sbt`. You can parse this file and extract the variable. For example: ``` resolvers += Resolver.sonatypeRepo("public") val scalaxbVersion = "1.1.2" addSbtPlugin("org.scalaxb" % "sbt-scalaxb" % scalaxbVersion) addSbtPlugin("org.xerial.sbt" % "sbt-pack" % "0.5.1") ``` You can extract `scalaxbVersion` with regular expressions/split: ``` scala> val line = """val scalaxbVersion = "1.1.2"""" line: String = val scalaxbVersion = "1.1.2" scala> line.split("=")(1).trim res1: String = "1.1.2" ```
23,944,108
I would like to share a common version variable between an sbtPlugin and the rest of the build Here is what I am trying: in `project/Build.scala`: ``` object Versions { scalaJs = "0.5.0-M3" } object MyBuild extends Build { //Use version number } ``` in `plugins.sbt`: ``` addSbtPlugin("org.scala-lang.modules.scalajs" % "scalajs-sbt-plugin" % Versions.scalaJs) ``` results in ``` plugins.sbt:15: error: not found: value Versions addSbtPlugin("org.scala-lang.modules.scalajs" % "scalajs-sbt-plugin" % Versions.scalaJs) ``` Is there a way to share the version number specification between `plugins.sbt` and the rest of the build, e.g. `project/Build.scala`?
2014/05/29
[ "https://Stackoverflow.com/questions/23944108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121477/" ]
sbt-buildinfo ------------- If you need to share `version` number between `build.sbt` and `hello.scala`, what would you normally do? I don't know about you, but I would use [sbt-buildinfo](https://github.com/sbt/sbt-buildinfo) that I wrote. This can be configured using `buildInfoKeys` setting to expose arbitrary key values like `version` or some custom `String` value. I understand this is not exactly what you're asking but bear with me. meta-build (turtles all the way down) ------------------------------------- As [Jacek noted](https://stackoverflow.com/a/23944311/3827) and stated in [Getting Started Guide](http://www.scala-sbt.org/0.13/tutorial/Full-Def.html), the build in sbt is a project defined in the build located in `project` directory one level down. To distinguish the builds, let's define the normal build as the *proper build*, and the build that defines the proper build as *meta-build*. For example, we can say that an sbt plugin is a library of the root project in the meta build. Now let's get back to your question. How can we share info between `project/Build.scala` and `project/plugins.sbt`? using sbt-buildinfo for meta-build ---------------------------------- We can just define another level of build by creating `project/project` and add `sbt-buildinfo` to the (meta-)meta-build. Here are the files. In `project/project/buildinfo.sbt`: ```scala addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.3.2") ``` In `project/project/Dependencies.scala`: ```scala package metabuild object Dependencies { def scalaJsVersion = "0.5.0-M2" } ``` In `project/build.properties`: ```scala sbt.version=0.13.5 ``` In `project/buildinfo.sbt`: ```scala import metabuild.Dependencies._ buildInfoSettings sourceGenerators in Compile <+= buildInfo buildInfoKeys := Seq[BuildInfoKey]("scalaJsVersion" -> scalaJsVersion) buildInfoPackage := "metabuild" ``` In `project/scalajs.sbt`: ```scala import metabuild.Dependencies._ addSbtPlugin("org.scala-lang.modules.scalajs" % "scalajs-sbt-plugin" % scalaJsVersion) ``` In `project/Build.scala`: ```scala import sbt._ import Keys._ import metabuild.BuildInfo._ object Builds extends Build { println(s"test: $scalaJsVersion") } ``` So there's a bit of a boilerplate in `project/buildinfo.sbt`, but the version info is shared across the build definition and the plugin declaration. If you're curious where `BuildInfo` is defined, peek into `project/target/scala-2.10/sbt-0.13/src_managed/`.
For the `project/plugins.sbt` file you'd have to have another `project` under `project` with the `Versions.scala` file. That would make the definition of `Versions.scalaJs` visible. The reason for doing it is that `*.sbt` files belong to a project build definition at the current level with `*.scala` files under `project` to expand on it. And it's...[turtles all the way down](http://en.wikipedia.org/wiki/Turtles_all_the_way_down), i.e. [sbt is recursive](http://www.scala-sbt.org/release/docs/Getting-Started/Full-Def.html#sbt-is-recursive). I'm not sure how much the following can help, but it might be worth to try out - to share versions between projects - `plugins` and the main one - you'd have to use `ProjectRef` as described in the answer to [RootProject and ProjectRef](https://stackoverflow.com/q/19469708/1305344): > > When you want to include other, separate builds directly instead of > using their published binaries, you use "source dependencies". This is > what `RootProject` and `ProjectRef` declare. `ProjectRef` is the most > general: you specify the location of the build (a URI) and the ID of > the project in the build (a String) that you want to depend on. > `RootProject` is a convenience that selects the root project for the > build at the URI you specify. > > >
23,944,108
I would like to share a common version variable between an sbtPlugin and the rest of the build Here is what I am trying: in `project/Build.scala`: ``` object Versions { scalaJs = "0.5.0-M3" } object MyBuild extends Build { //Use version number } ``` in `plugins.sbt`: ``` addSbtPlugin("org.scala-lang.modules.scalajs" % "scalajs-sbt-plugin" % Versions.scalaJs) ``` results in ``` plugins.sbt:15: error: not found: value Versions addSbtPlugin("org.scala-lang.modules.scalajs" % "scalajs-sbt-plugin" % Versions.scalaJs) ``` Is there a way to share the version number specification between `plugins.sbt` and the rest of the build, e.g. `project/Build.scala`?
2014/05/29
[ "https://Stackoverflow.com/questions/23944108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121477/" ]
sbt-buildinfo ------------- If you need to share `version` number between `build.sbt` and `hello.scala`, what would you normally do? I don't know about you, but I would use [sbt-buildinfo](https://github.com/sbt/sbt-buildinfo) that I wrote. This can be configured using `buildInfoKeys` setting to expose arbitrary key values like `version` or some custom `String` value. I understand this is not exactly what you're asking but bear with me. meta-build (turtles all the way down) ------------------------------------- As [Jacek noted](https://stackoverflow.com/a/23944311/3827) and stated in [Getting Started Guide](http://www.scala-sbt.org/0.13/tutorial/Full-Def.html), the build in sbt is a project defined in the build located in `project` directory one level down. To distinguish the builds, let's define the normal build as the *proper build*, and the build that defines the proper build as *meta-build*. For example, we can say that an sbt plugin is a library of the root project in the meta build. Now let's get back to your question. How can we share info between `project/Build.scala` and `project/plugins.sbt`? using sbt-buildinfo for meta-build ---------------------------------- We can just define another level of build by creating `project/project` and add `sbt-buildinfo` to the (meta-)meta-build. Here are the files. In `project/project/buildinfo.sbt`: ```scala addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.3.2") ``` In `project/project/Dependencies.scala`: ```scala package metabuild object Dependencies { def scalaJsVersion = "0.5.0-M2" } ``` In `project/build.properties`: ```scala sbt.version=0.13.5 ``` In `project/buildinfo.sbt`: ```scala import metabuild.Dependencies._ buildInfoSettings sourceGenerators in Compile <+= buildInfo buildInfoKeys := Seq[BuildInfoKey]("scalaJsVersion" -> scalaJsVersion) buildInfoPackage := "metabuild" ``` In `project/scalajs.sbt`: ```scala import metabuild.Dependencies._ addSbtPlugin("org.scala-lang.modules.scalajs" % "scalajs-sbt-plugin" % scalaJsVersion) ``` In `project/Build.scala`: ```scala import sbt._ import Keys._ import metabuild.BuildInfo._ object Builds extends Build { println(s"test: $scalaJsVersion") } ``` So there's a bit of a boilerplate in `project/buildinfo.sbt`, but the version info is shared across the build definition and the plugin declaration. If you're curious where `BuildInfo` is defined, peek into `project/target/scala-2.10/sbt-0.13/src_managed/`.
My proposal is to hack. For example, in `build.sbt` you can add a task: ``` val readPluginSbt = taskKey[String]("Read plugins.sbt file.") readPluginSbt := { val lineIterator = scala.io.Source.fromFile(new java.io.File("project","plugins.sbt")).getLines val linesWithValIterator = lineIterator.filter(line => line.contains("scalaxbVersion")) val versionString = linesWithValIterator.mkString("\n").split("=")(1).trim val version = versionString.split("\n")(0) // only val declaration println(version) version } ``` When you call `readPluginSbt` you will see the contents of `plugins.sbt`. You can parse this file and extract the variable. For example: ``` resolvers += Resolver.sonatypeRepo("public") val scalaxbVersion = "1.1.2" addSbtPlugin("org.scalaxb" % "sbt-scalaxb" % scalaxbVersion) addSbtPlugin("org.xerial.sbt" % "sbt-pack" % "0.5.1") ``` You can extract `scalaxbVersion` with regular expressions/split: ``` scala> val line = """val scalaxbVersion = "1.1.2"""" line: String = val scalaxbVersion = "1.1.2" scala> line.split("=")(1).trim res1: String = "1.1.2" ```
148,433
I am looking for a way to replace my phone as a 2FA method. U2F is not universally supported. Most services that I use support TOTP (Google Authenticator), and so I thought the Yubikey would support loading the TOTP secret and, upon press of a button, somehow detect the web site I am on, generate the code, and enter it, without additional software involved. Apparently, this does not work. But could it? Or is there hardware that supports this use case?
2017/01/15
[ "https://security.stackexchange.com/questions/148433", "https://security.stackexchange.com", "https://security.stackexchange.com/users/57381/" ]
The hardware token detects the website you're on, generates an appropriate code, and submits it directly without the user typing anything? That sounds a lot like u2f. The reason why you don't see this offered is the same reason why only a few sites support u2f: it would require the browser to interact directly with the hardware token, and at the moment only Google Chrome is able to connect to USB devices. Other vendors don't see it as an important feature to include. Sad, because it solves phishing more or less entirely. So no, this doesn't exist as you describe if you're not willing to use u2f. There's stuff like LastPass which can do something of what you ask, but that's a browser extension not a hardware token.
@tylerl is not completely right here. (Especially since U2F requires additional software ;-) The yubikey can work independently of the any driver and any website. So the yubikey will not detect a website, if not in U2F mode. A full blown yubikey has the following modes: * PGP * U2F * AES yubico mode * HOTP * Challenge Response (can be used as TOTP) * Static password I guess what you are amining at should be HOTP. Which is the event based mode defined in RFC 4226. TOTP is based on HOTP with time being the counter. You can initialize the yubikey in HOTP mode and write the secret key to the yubikey. The yubikey will then work as a normal keyboard and emit the OTP value whenever you touch the button. Not matter if you are on the right website, in a browser or in notepad. => completely without any additional software and completly without the website caring about you using a yubikey. I think there are only two challenges here: 1. The website/application where you want to use this should support HOTP, not only TOTP. 2. The yubikey only has two slots for this. I.e. you could only use the yubikey with two websites/applications.
32,944,847
I have a compression command which I pipe to a md5sum check command as such: ``` tar zcvpf file.tar.gz file | xargs -I '{}' bash -c "test -f '{}' && md5sum '{}'" | tee file_mybackup.md5 ``` I would now like to split the tar.gz file into 100MB chunks. I can do this by: ``` tar zcvpf - file | split -d -b 1M - file.tar.gz. ``` Is there a way that I can pipe the output of the tar command to simultaneously perform the split command and md5sum check? I know that split does not output to STDOUT so I can't pipe from the split command to the md5sum command. I tried to use a named pipe: ``` mkfifo newpipe tar zcvpf - file | tee newpipe | split -d -b 1M - file.tar.gz. & cat newpipe | xargs -I '{}' bash -c "test -f '{}' && md5sum '{}'" | tee file_mybackup.md5 ``` However this fails to output the md5sum output. Any help would be appreciated
2015/10/05
[ "https://Stackoverflow.com/questions/32944847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1977981/" ]
If the background task is assigned to a specific user, you could use session data to indicate that task has completed. In your Ajax function, you could look at this session data, and only look at the database when you have indication that this is completed: <https://docs.djangoproject.com/en/1.8/topics/http/sessions/> Another solution would be to use a system file, used for synchronization. For example: * The file is created when the background task is created, with start date and time. You may add further information like the user that requested it. * As long as the file is present (With a further check for timeout, checking the data from the file), no need to look at the database. * If the file is not present, you know that the request has completed and you can look at the database to update. This file may also be accessible as an Url (To avoid the Ajax request)
Maybe you should use Jquery and ajax to do the request using this.. <http://api.jquery.com/category/deferred-object/> Hope it helps you
26,801
After solving the first few levels in Crayon Physics my "world map" looks like this: ![enter image description here](https://i.stack.imgur.com/jVTrg.jpg) It appears I earned two flags on the first level, one flag on the following two, no flag for the fourth, then I earned two flags and... a ball. Is that just cosmetic, or does it depend on how well I did? If so, how can I improve this score?
2011/07/27
[ "https://gaming.stackexchange.com/questions/26801", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/23/" ]
Those are cosmetic. Only the stars count. You can i[mprove your score](http://www.kloonigames.com/blog/crayonphysics/crayon-physics-deluxe-gameplay-update) by finishing a round in one of the following ways. 1. Hole in one - for this, you have to get the star by drawing a single line 2. Old School, and - for this, you shouldn't touch the ball or draw any pins 3. Awesome - the user marks a solution "awesome". You can look for some sample solutions on youtube walkthroughs for each. :)
If you have two flags on one level, you can click the level then the 'solutions tab' and mark your solution as 'awesome'. This gives you one orange flag for the level, and an extra star.
634,507
Can you point out where am I going wrong ? I wanted to select 5 men from 7 men . This can be done very easily as 7C5 ways = 21ways, but I was confused as to why the following calculation didn't work out the same way -> I first selected 3 men from 7 men as 7C3 ways = 35 ways And then I selected 2 men from remaining 4 men as 4C2 ways = 6 ways ...so since I am selecting 3men AND 2men so 35x6= 210
2014/01/11
[ "https://math.stackexchange.com/questions/634507", "https://math.stackexchange.com", "https://math.stackexchange.com/users/120564/" ]
You are overcounting in the following way. If the men were elements of $M = \{A,B,C,D,E,F,G\}$ then you might choose $A,B,C$ from $M$ and then $D,E$ from the remaining four or you might choose $A,B,D$ and $C,E$ from the remaining four but you get the same five men in both cases. For any given five element set there are $\binom{5}{3}=\binom{5}{2}=10$ ways to choose the first three elements and therefore you are counting each individual five element set $10$ times, as your calculations have already shown.
Let's try it with smaller numbers. I want to select $3$ men from $4$ men. This can be done easily in $\_4\text{C}\_3=4$ ways. (Equivalently, I can choose to *omit* one of the $4$ men in $\_4\text{C}\_1=4$ ways.) This is clearly the right answer. Now let's try it another way. First I select $1$ man from $4$ men in $\_4\text{C}\_1=4$ ways. Then I select $1$ man from the remaining $3$ men in $\_3\text{C}\_1=3$ ways. Finally I select $1$ man from the remaining $2$ men in $\_2\text{C}\_1=2$ ways. So there are $4\times3\times2=24$ ways to select the $3$ men! Can you see why the second solution is wrong? By the way, how many ways are there to make an *ordered* selection (permutation) of $3$ men from the set of $4$ men?
634,507
Can you point out where am I going wrong ? I wanted to select 5 men from 7 men . This can be done very easily as 7C5 ways = 21ways, but I was confused as to why the following calculation didn't work out the same way -> I first selected 3 men from 7 men as 7C3 ways = 35 ways And then I selected 2 men from remaining 4 men as 4C2 ways = 6 ways ...so since I am selecting 3men AND 2men so 35x6= 210
2014/01/11
[ "https://math.stackexchange.com/questions/634507", "https://math.stackexchange.com", "https://math.stackexchange.com/users/120564/" ]
You are overcounting in the following way. If the men were elements of $M = \{A,B,C,D,E,F,G\}$ then you might choose $A,B,C$ from $M$ and then $D,E$ from the remaining four or you might choose $A,B,D$ and $C,E$ from the remaining four but you get the same five men in both cases. For any given five element set there are $\binom{5}{3}=\binom{5}{2}=10$ ways to choose the first three elements and therefore you are counting each individual five element set $10$ times, as your calculations have already shown.
Hi lets us concider a small real life example! See.... let us concider that we have 5 members such as A B C D E ok. Now you are willing to choose any 3 members from them to form a team.So then you will use the combination concept among them.right!fine...this will be simply 5C3 = ((120)/((2!)\*(3!)))= 10. **But according to you "WHAT IF WE CHOOSE 2 MEMBERS FROM THESE 5 MEN AND THEN WHAT IF WE CHOOSE THE REMAINING 1 MAN FROM THE REMAINING 3 MEMBERS....CAN WE CHOOSE TOTAL 3 MEMBERS THIS WAY?AS WE CHOOSE 3 MEMBERS ABOVE IN PREVIOUS CASE CAN WE CHOOSE 3 MEMBERS FROM THESE 5 MEN BY APPLYING THE 2ND CONCEPT???according to you the answer gonna be (5C2)x(3C1)=30!!** \**ok then let us now have anexperiment!!! :-) \** so what is the experiment!! well!! we have A B C D E as our 5 men ok.fine.then we are going to choose 3 members from them applying your concept and see what is going to be the result!! :-) first we now choose 2 men from these 5 men!this can be done in 5C2 ways.that is 10 actually....ok? now we can tabulate the pairs of the selected men....right! they may be: {A-B , A-C , A-D , A-E , B-C , ... , D-E} ---- here is total 10 numbers of pairs we have got.fine! And now we will choose the remainin 1 member from the remaining 3 men.(cause our moto was to choose total 3 men from 5 members) ``` now if we choose that 1 guy from the remaining 3 men we will have only 3 choice!very simple!....but if we tabulate the choices now we will have: {(C/D/E) , (B/D/E) , (B/C/E) , (B/C/D) , (A/D/E) , ... , (A/B/C)}---I think this line is not clear enough!ok let me make this clear to you.. ``` here we write my 2 tabulated data in a readable manner: pairs may get selected first: { A-B , A-C , A-D , A-E, ... , D-E}----(total 10 pairs) choices for the last guy :{ (C/D/E), (B/D/E),(B/C/E),(B/C/D)... (A/B/C)---(total 10 triplets of the alphabets for the corresponding pair selected in the first step!) **(please have a look into the parenthesis and the PAIRS and the respective choices in form of TRIPLETS)** I mean if (A-B) is selected then the choices are from the triplet of (C/D/E) -- (1) if (A-C) is selected then the choices are from the triplet of (B/D/E) -- (2) if (A-D) is selected then the choices are from the triplet of (B/C/E) -- (3) if (A-E) is selected then the choices are from the triplet of (B/C/D) -- (4) ........and so on and atlast we have the combination ... if (D-E) is selected then the choices are from the triplet of (A/B/C) -- (10) so from the above experiment we can say,if the pair (A-B) is selected then C - D - E may be combined with A - B and we will get total (A-B-C) **or** (A-B-D) **or** (A-B-E) if it is A-C the pair then we will get total (A-C-B) **or** (A-C-D) **or** (A-C-E) like this we can proceed to fom our team of 3 members!!! \*\*But see here we have a case which is not admissible that is in these to pair of selection as (A-B) or (A-C) we have the team as (A-B-C) and (A-C-B)!!!!!! if we apply your concept of counting as: (5C2)x(3C1)=30 we are counting these cases as two different teams or as two different selections which is not according to the concept of COMBINATION at all,the selections are basically same but we are counting them as two different team!!!did you get my point? :-) **here I am showing only one contradiction occurs in our experiment if we follow your concept of selection!!** Hope this discussion will help you to clear your doubt on the concept of COMBINATION or selection of objects from a given set!!best of luck... :-)
634,507
Can you point out where am I going wrong ? I wanted to select 5 men from 7 men . This can be done very easily as 7C5 ways = 21ways, but I was confused as to why the following calculation didn't work out the same way -> I first selected 3 men from 7 men as 7C3 ways = 35 ways And then I selected 2 men from remaining 4 men as 4C2 ways = 6 ways ...so since I am selecting 3men AND 2men so 35x6= 210
2014/01/11
[ "https://math.stackexchange.com/questions/634507", "https://math.stackexchange.com", "https://math.stackexchange.com/users/120564/" ]
Let's try it with smaller numbers. I want to select $3$ men from $4$ men. This can be done easily in $\_4\text{C}\_3=4$ ways. (Equivalently, I can choose to *omit* one of the $4$ men in $\_4\text{C}\_1=4$ ways.) This is clearly the right answer. Now let's try it another way. First I select $1$ man from $4$ men in $\_4\text{C}\_1=4$ ways. Then I select $1$ man from the remaining $3$ men in $\_3\text{C}\_1=3$ ways. Finally I select $1$ man from the remaining $2$ men in $\_2\text{C}\_1=2$ ways. So there are $4\times3\times2=24$ ways to select the $3$ men! Can you see why the second solution is wrong? By the way, how many ways are there to make an *ordered* selection (permutation) of $3$ men from the set of $4$ men?
Hi lets us concider a small real life example! See.... let us concider that we have 5 members such as A B C D E ok. Now you are willing to choose any 3 members from them to form a team.So then you will use the combination concept among them.right!fine...this will be simply 5C3 = ((120)/((2!)\*(3!)))= 10. **But according to you "WHAT IF WE CHOOSE 2 MEMBERS FROM THESE 5 MEN AND THEN WHAT IF WE CHOOSE THE REMAINING 1 MAN FROM THE REMAINING 3 MEMBERS....CAN WE CHOOSE TOTAL 3 MEMBERS THIS WAY?AS WE CHOOSE 3 MEMBERS ABOVE IN PREVIOUS CASE CAN WE CHOOSE 3 MEMBERS FROM THESE 5 MEN BY APPLYING THE 2ND CONCEPT???according to you the answer gonna be (5C2)x(3C1)=30!!** \**ok then let us now have anexperiment!!! :-) \** so what is the experiment!! well!! we have A B C D E as our 5 men ok.fine.then we are going to choose 3 members from them applying your concept and see what is going to be the result!! :-) first we now choose 2 men from these 5 men!this can be done in 5C2 ways.that is 10 actually....ok? now we can tabulate the pairs of the selected men....right! they may be: {A-B , A-C , A-D , A-E , B-C , ... , D-E} ---- here is total 10 numbers of pairs we have got.fine! And now we will choose the remainin 1 member from the remaining 3 men.(cause our moto was to choose total 3 men from 5 members) ``` now if we choose that 1 guy from the remaining 3 men we will have only 3 choice!very simple!....but if we tabulate the choices now we will have: {(C/D/E) , (B/D/E) , (B/C/E) , (B/C/D) , (A/D/E) , ... , (A/B/C)}---I think this line is not clear enough!ok let me make this clear to you.. ``` here we write my 2 tabulated data in a readable manner: pairs may get selected first: { A-B , A-C , A-D , A-E, ... , D-E}----(total 10 pairs) choices for the last guy :{ (C/D/E), (B/D/E),(B/C/E),(B/C/D)... (A/B/C)---(total 10 triplets of the alphabets for the corresponding pair selected in the first step!) **(please have a look into the parenthesis and the PAIRS and the respective choices in form of TRIPLETS)** I mean if (A-B) is selected then the choices are from the triplet of (C/D/E) -- (1) if (A-C) is selected then the choices are from the triplet of (B/D/E) -- (2) if (A-D) is selected then the choices are from the triplet of (B/C/E) -- (3) if (A-E) is selected then the choices are from the triplet of (B/C/D) -- (4) ........and so on and atlast we have the combination ... if (D-E) is selected then the choices are from the triplet of (A/B/C) -- (10) so from the above experiment we can say,if the pair (A-B) is selected then C - D - E may be combined with A - B and we will get total (A-B-C) **or** (A-B-D) **or** (A-B-E) if it is A-C the pair then we will get total (A-C-B) **or** (A-C-D) **or** (A-C-E) like this we can proceed to fom our team of 3 members!!! \*\*But see here we have a case which is not admissible that is in these to pair of selection as (A-B) or (A-C) we have the team as (A-B-C) and (A-C-B)!!!!!! if we apply your concept of counting as: (5C2)x(3C1)=30 we are counting these cases as two different teams or as two different selections which is not according to the concept of COMBINATION at all,the selections are basically same but we are counting them as two different team!!!did you get my point? :-) **here I am showing only one contradiction occurs in our experiment if we follow your concept of selection!!** Hope this discussion will help you to clear your doubt on the concept of COMBINATION or selection of objects from a given set!!best of luck... :-)
39,124,265
I want to get a sample from serial port in python. but when I run the code to know the rate of it, python gives me different values! it is usually about `24000` time per second. But sometimes it returns `14000`. What is this big difference's reason ? and if I want to sampling 1 million what should I do? this is the sample code for test run speed: ``` import time def g(start=0, stop=5, step=1): while start < stop: yield start start += step t1 = time.time() t2 = t1 + 1 for item in g(10,1000000,1): print(item) t1 = time.time() if t1 > t2: break ```
2016/08/24
[ "https://Stackoverflow.com/questions/39124265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526335/" ]
Investigate the `timeit` module, which was designed for applications like this. Benchmarks have to be run under very controlled conditions to be anything like repeatable. `timeit` runs your code a number of times and gives you the best result. Usually slower performance will be an indication that your computer is running some other task(s) at the same time as the benchmark.
You will have always some time discrepancies in running code in python, it's because of resources your CPU `gives` to running your script. You have to make couple of tries and calculate average time of it.
39,124,265
I want to get a sample from serial port in python. but when I run the code to know the rate of it, python gives me different values! it is usually about `24000` time per second. But sometimes it returns `14000`. What is this big difference's reason ? and if I want to sampling 1 million what should I do? this is the sample code for test run speed: ``` import time def g(start=0, stop=5, step=1): while start < stop: yield start start += step t1 = time.time() t2 = t1 + 1 for item in g(10,1000000,1): print(item) t1 = time.time() if t1 > t2: break ```
2016/08/24
[ "https://Stackoverflow.com/questions/39124265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5526335/" ]
Investigate the `timeit` module, which was designed for applications like this. Benchmarks have to be run under very controlled conditions to be anything like repeatable. `timeit` runs your code a number of times and gives you the best result. Usually slower performance will be an indication that your computer is running some other task(s) at the same time as the benchmark.
I was @15000 at first execution and then arround 28000. In general the result depends mainly of * your CPU load * cache hit/miss * RAM access time But in your case it is the print which takes most of the execution time. So print access time to stdout is the cause of your variation. try this : ``` for item in g(10,100000000,1): #print(item) t1 = time.time() if t1 > t2: print(item) #print only the last break ```
24,281,460
I am currently creating a multistep form with Formhandler, including a variety of translation labels. At default, German labels are shown, but there is a option to switch the website to English - when I do this, the label texts change, so this works. **My problem:** when I submit the first step of the form in English to get to the second page, suddenly the form (and the whole website) change back to German. Of course I want it to stay in English. Is there some kind of hidden field that has to be passed on for Formhandler to "keep" the current language? What could be the reason it loses the set language?
2014/06/18
[ "https://Stackoverflow.com/questions/24281460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3214306/" ]
I believe the problem is invoking `runAction` twice on the same node. **EDIT**: As LearnCocos2D mentioned in the comments invoking `runAction` more then once should work as long as the actions are not interfering with each other (i.e. two move actions on the same node running in parallel) so it's either a behavioral change in version 3.x or maybe your ALERT\_FADE\_DURATION definition is too small (as noted in the comments as well) Try using the `CCActionSpawn` action which can run actions in parallel on the same node : ``` CCAction *spawnAction = [CCActionSpawn actionWithArray:@[actionMove , actionFade]]; CCAction *sequenceAction = [CCActionSequence actionWithArray:@[spawnAction]]; [labelDP runAction:sequenceAction]; ``` This should give you the desired effect. First move and fade the label and only then remove it from its parent node
Try with this: ``` CCAction *actionMove = [CCActionMoveBy actionWithDuration:ALERT_FADE_DURATION position:ccp(0.0f, 40.0f)]; CCAction *actionFade = [CCActionFadeOut actionWithDuration:ALERT_FADE_DURATION]; CCAction *actionRemove = [CCActionRemove action]; id seq = [CCActionSequence actions:actionMove, actionRemove, nil]; [labelDP runAction:[CCActionSpawn actions:actionFade, seq, nil]]; ```
10,909,063
The mongoDB API documentation seems to be lacking in this area. I am trying to use the aggregate function to get a count of popular tags in a certain collection. Here is the command I wish to execute: ``` db.runCommand( { aggregate : "articles", pipeline : [ { $unwind : "$Tags" }, { $group : { _id : "$Tags", count : { $sum : 1 } } } ]}); ``` When I execute this using the shell, I get the following: ``` { "result": [{ "_id": "2012", "count": 3 }, { "_id": "seattle", "count": 5 }], "ok": 1 } ``` I'm using c# 4.0, so I guess I would prefer to get this back as a dynamic object, but I'll take whatever I can get... FWIW, I am using mongoDB for Windows, 32 bit, v2.1.1 (Nightly)
2012/06/06
[ "https://Stackoverflow.com/questions/10909063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438940/" ]
Here's the corresponding C# Driver Doc page: [RunCommand()](http://api.mongodb.org/csharp/1.3.1/html/4fe0d8b2-161e-ff83-355d-7517b251d81a.htm). So basically you call `Database.RunCommand("MyCommand")`. This ticket in JIRA may come handy for an example of more complex commands requiring (multiple) properties: [CSHARP-478](https://jira.mongodb.org/browse/CSHARP-478)
In MongoDB CSharp Drivers 2.0.0+: I use below syntax to run such commands: ``` var command = new CommandDocument { {"aggregate", "TestCollection"}, { "pipeline", new BsonArray { new BsonDocument {{"$unwind", "$Tags"}}, new BsonDocument { { "$group", new BsonDocument { {"_id", "$Tags"}, {"count", new BsonDocument {{"$sum", 1}}} } } } } } }; var result = db.RunCommand<BsonDocument>(command)["result"] .AsBsonArray.ToList(); ```
21,263,422
AWS (Amazon Web Service) provides an API for submitting HTTP requests to Alexa. This API is called Alexa Web Information Service. I submit an HTTP request with `&Action=UrlInfo` and `&ResponseGroup=UsageStats`. I then receive an XML within the HTTP response. Here is the part in the XML which is relevant to my question: ``` <aws:PageViews> <aws:PerMillion> <aws:Value>12,345</aws:Value> <aws:Delta>+0.67%</aws:Delta> </aws:PerMillion> <aws:Rank> <aws:Value>1</aws:Value> <aws:Delta>0</aws:Delta> </aws:Rank> <aws:PerUser> <aws:Value>12.34</aws:Value> <aws:Delta>-0.56%</aws:Delta> </aws:PerUser> </aws:PageViews> ``` The documentation for the API is at **<http://docs.aws.amazon.com/AlexaWebInfoService/latest/>**. A description for the specific parameters that I am using in my HTTP request, can be found under **API Reference** / **Actions** / **UrlInfo**, but I have not been able to find any details on any of the above tags. **Does anyone happen to know the exact meaning of each of these tags? :** * PerMillion / Value * PerMillion / Delta * Rank / Value * Rank / Delta * PerUser / Value * PerUser / Delta Thanks
2014/01/21
[ "https://Stackoverflow.com/questions/21263422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1382251/" ]
Regarding aws:PerMillion > > The PageViews PerMillion stat shows "out of every million pageviews > made by all users on the Internet today how many pageviews are made on > this site?" The daily pageviews number is then averaged over the > specified time period. > > > <https://forums.aws.amazon.com/message.jspa?messageID=578614> > > > and aws:PerUser > > it is "per million pageviews on the internet" > > > <https://forums.aws.amazon.com/message.jspa?messageID=265890> > > >
I've annotated a sample result with my understanding of the return values based on Treton's answer: ```xml <aws:TopSites> <!-- Country in which the sites in this result have been grouped. --> <aws:Country> <aws:CountryName>Australia</aws:CountryName> <aws:CountryCode>AU</aws:CountryCode> <!-- Total number of sites Alexa is tracking in this country --> <aws:TotalSites>22052</aws:TotalSites> <!-- List of sites in result. --> <aws:Sites> <aws:Site> <aws:DataUrl>google.com</aws:DataUrl> <aws:Country> <!-- Rank within country (eg 10 = 10th most popular site in country). --> <aws:Rank>1</aws:Rank> <!-- --> <aws:Reach> <!-- Out of every million users on the internet today, how many visited this site? @see https://forums.aws.amazon.com/message.jspa?messageID=578614 --> <aws:PerMillion>801700</aws:PerMillion> </aws:Reach> <aws:PageViews> <!-- Out of every million pageviews by all users on the internet today, how many were made to this site? --> <aws:PerMillion>267200</aws:PerMillion> <!-- What is the average (mean) number of pageviews to this site, per user, per day? --> <aws:PerUser>14.94</aws:PerUser> </aws:PageViews> </aws:Country> <!-- Rank within whole world. --> <aws:Global> <aws:Rank>1</aws:Rank> </aws:Global> </aws:Site> </aws:Sites> </aws:Country> </aws:TopSites> ```
12,018,257
I have a site where users can publish links. Users fill a form with 2 fields: * Title * URL When the user clicks "submit" I have a crawler that looks for an image of the link provided and makes a thumbnail. The problem is that **the crawler usually takes about 5-10 seconds to finish loading** and cropping the thumb. I thought I could do an ajax call like this. As you can see, when the user submits a link first we see if its valid (first ajax call) then if succesful we do another ajax call to try to find and save the image of this link. My idea was to do that while I move the user to the links.php page, however, I find that if I do it like this the AJAX call breaks and the function in `save_image.php` doesn't run. What can I do to avoid making my users wait for the `save_image.php` process? I need this process to run, but I don't need any data returned. ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { if (data) { $.ajax({ url: 'publish/save_image.php', type: 'POST', data: { id : data.id, type : data.type, url : url, csrf_test_name : csrf } }); } //THIS NEXT LINE BREAKS SECOND AJAX CALL window.location = 'links.php'; } }); ``` Thanks in advance! **SUMMING UP:** I want the user to submit a link and redirect the user to the links page **while the thumbnail for that link is being generated**. I don't want to show the thumbnail to the user.
2012/08/18
[ "https://Stackoverflow.com/questions/12018257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949388/" ]
force user to fill first the url and then the title, when user go to title field start crawl data, till finish the title and press sumbit you will gain some time and make the proccess apparently faster.
Why use XHR at all if you don't need the data returned? Just let your form submit the link to `links.php` and let it save the image there!
12,018,257
I have a site where users can publish links. Users fill a form with 2 fields: * Title * URL When the user clicks "submit" I have a crawler that looks for an image of the link provided and makes a thumbnail. The problem is that **the crawler usually takes about 5-10 seconds to finish loading** and cropping the thumb. I thought I could do an ajax call like this. As you can see, when the user submits a link first we see if its valid (first ajax call) then if succesful we do another ajax call to try to find and save the image of this link. My idea was to do that while I move the user to the links.php page, however, I find that if I do it like this the AJAX call breaks and the function in `save_image.php` doesn't run. What can I do to avoid making my users wait for the `save_image.php` process? I need this process to run, but I don't need any data returned. ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { if (data) { $.ajax({ url: 'publish/save_image.php', type: 'POST', data: { id : data.id, type : data.type, url : url, csrf_test_name : csrf } }); } //THIS NEXT LINE BREAKS SECOND AJAX CALL window.location = 'links.php'; } }); ``` Thanks in advance! **SUMMING UP:** I want the user to submit a link and redirect the user to the links page **while the thumbnail for that link is being generated**. I don't want to show the thumbnail to the user.
2012/08/18
[ "https://Stackoverflow.com/questions/12018257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949388/" ]
The AJAX request seems to fail, because when you navigate away, the user request is aborted. Because of that, the execution of `save_image.php` is interrupted. You can use PHP's [`ignore_user_abort`](http://de2.php.net/manual/en/function.ignore-user-abort.php) to force the PHP process to continue in the background. Put it at the top of `save_image.php`: ```php <?php ignore_user_abort(true); // ... save image, etc. ?> ``` For this to work, you have to send (and [flush](http://php.net/manual/en/function.flush.php)) some output to the client: > > PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see [flush()](http://php.net/manual/en/function.flush.php). > > > Any output should work (e.g. "OK"). This might be a bit of a challenge considering you're using a framework, but it shouldn't be impossible. This might work: [Flushing with CodeIgniter](http://codeigniter.com/forums/viewthread/110755/) You can read more about PHP connection handling [here](http://php.net/manual/en/features.connection-handling.php).
Why use XHR at all if you don't need the data returned? Just let your form submit the link to `links.php` and let it save the image there!
12,018,257
I have a site where users can publish links. Users fill a form with 2 fields: * Title * URL When the user clicks "submit" I have a crawler that looks for an image of the link provided and makes a thumbnail. The problem is that **the crawler usually takes about 5-10 seconds to finish loading** and cropping the thumb. I thought I could do an ajax call like this. As you can see, when the user submits a link first we see if its valid (first ajax call) then if succesful we do another ajax call to try to find and save the image of this link. My idea was to do that while I move the user to the links.php page, however, I find that if I do it like this the AJAX call breaks and the function in `save_image.php` doesn't run. What can I do to avoid making my users wait for the `save_image.php` process? I need this process to run, but I don't need any data returned. ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { if (data) { $.ajax({ url: 'publish/save_image.php', type: 'POST', data: { id : data.id, type : data.type, url : url, csrf_test_name : csrf } }); } //THIS NEXT LINE BREAKS SECOND AJAX CALL window.location = 'links.php'; } }); ``` Thanks in advance! **SUMMING UP:** I want the user to submit a link and redirect the user to the links page **while the thumbnail for that link is being generated**. I don't want to show the thumbnail to the user.
2012/08/18
[ "https://Stackoverflow.com/questions/12018257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949388/" ]
The AJAX request seems to fail, because when you navigate away, the user request is aborted. Because of that, the execution of `save_image.php` is interrupted. You can use PHP's [`ignore_user_abort`](http://de2.php.net/manual/en/function.ignore-user-abort.php) to force the PHP process to continue in the background. Put it at the top of `save_image.php`: ```php <?php ignore_user_abort(true); // ... save image, etc. ?> ``` For this to work, you have to send (and [flush](http://php.net/manual/en/function.flush.php)) some output to the client: > > PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see [flush()](http://php.net/manual/en/function.flush.php). > > > Any output should work (e.g. "OK"). This might be a bit of a challenge considering you're using a framework, but it shouldn't be impossible. This might work: [Flushing with CodeIgniter](http://codeigniter.com/forums/viewthread/110755/) You can read more about PHP connection handling [here](http://php.net/manual/en/features.connection-handling.php).
force user to fill first the url and then the title, when user go to title field start crawl data, till finish the title and press sumbit you will gain some time and make the proccess apparently faster.
12,018,257
I have a site where users can publish links. Users fill a form with 2 fields: * Title * URL When the user clicks "submit" I have a crawler that looks for an image of the link provided and makes a thumbnail. The problem is that **the crawler usually takes about 5-10 seconds to finish loading** and cropping the thumb. I thought I could do an ajax call like this. As you can see, when the user submits a link first we see if its valid (first ajax call) then if succesful we do another ajax call to try to find and save the image of this link. My idea was to do that while I move the user to the links.php page, however, I find that if I do it like this the AJAX call breaks and the function in `save_image.php` doesn't run. What can I do to avoid making my users wait for the `save_image.php` process? I need this process to run, but I don't need any data returned. ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { if (data) { $.ajax({ url: 'publish/save_image.php', type: 'POST', data: { id : data.id, type : data.type, url : url, csrf_test_name : csrf } }); } //THIS NEXT LINE BREAKS SECOND AJAX CALL window.location = 'links.php'; } }); ``` Thanks in advance! **SUMMING UP:** I want the user to submit a link and redirect the user to the links page **while the thumbnail for that link is being generated**. I don't want to show the thumbnail to the user.
2012/08/18
[ "https://Stackoverflow.com/questions/12018257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949388/" ]
force user to fill first the url and then the title, when user go to title field start crawl data, till finish the title and press sumbit you will gain some time and make the proccess apparently faster.
to understand your problem, we need to understand the working of javascript your code is as follows ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { if (data) { $.ajax({ url: 'publish/save_image.php', type: 'POST', data: { id : data.id, type : data.type, url : url, csrf_test_name : csrf } }); } //THIS NEXT LINE BREAKS SECOND AJAX CALL window.location = 'links.php'; } }); ``` from the above i can say that as soon as ajax request is made, java script executes the second line regardless of the response. we can take the following example ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { console.log(data); } }); for(var i = 0; i < 15000000; i++) { console.log(i); } ``` you may see the output as follows ``` 1 2 3 . . . 1000 data//response of ajax . . 14999999 ``` so to avoid that you can use either [jQuery.when()](http://api.jquery.com/jQuery.when/) our ajax success function. Hopefully this will help you
12,018,257
I have a site where users can publish links. Users fill a form with 2 fields: * Title * URL When the user clicks "submit" I have a crawler that looks for an image of the link provided and makes a thumbnail. The problem is that **the crawler usually takes about 5-10 seconds to finish loading** and cropping the thumb. I thought I could do an ajax call like this. As you can see, when the user submits a link first we see if its valid (first ajax call) then if succesful we do another ajax call to try to find and save the image of this link. My idea was to do that while I move the user to the links.php page, however, I find that if I do it like this the AJAX call breaks and the function in `save_image.php` doesn't run. What can I do to avoid making my users wait for the `save_image.php` process? I need this process to run, but I don't need any data returned. ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { if (data) { $.ajax({ url: 'publish/save_image.php', type: 'POST', data: { id : data.id, type : data.type, url : url, csrf_test_name : csrf } }); } //THIS NEXT LINE BREAKS SECOND AJAX CALL window.location = 'links.php'; } }); ``` Thanks in advance! **SUMMING UP:** I want the user to submit a link and redirect the user to the links page **while the thumbnail for that link is being generated**. I don't want to show the thumbnail to the user.
2012/08/18
[ "https://Stackoverflow.com/questions/12018257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949388/" ]
The AJAX request seems to fail, because when you navigate away, the user request is aborted. Because of that, the execution of `save_image.php` is interrupted. You can use PHP's [`ignore_user_abort`](http://de2.php.net/manual/en/function.ignore-user-abort.php) to force the PHP process to continue in the background. Put it at the top of `save_image.php`: ```php <?php ignore_user_abort(true); // ... save image, etc. ?> ``` For this to work, you have to send (and [flush](http://php.net/manual/en/function.flush.php)) some output to the client: > > PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see [flush()](http://php.net/manual/en/function.flush.php). > > > Any output should work (e.g. "OK"). This might be a bit of a challenge considering you're using a framework, but it shouldn't be impossible. This might work: [Flushing with CodeIgniter](http://codeigniter.com/forums/viewthread/110755/) You can read more about PHP connection handling [here](http://php.net/manual/en/features.connection-handling.php).
to understand your problem, we need to understand the working of javascript your code is as follows ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { if (data) { $.ajax({ url: 'publish/save_image.php', type: 'POST', data: { id : data.id, type : data.type, url : url, csrf_test_name : csrf } }); } //THIS NEXT LINE BREAKS SECOND AJAX CALL window.location = 'links.php'; } }); ``` from the above i can say that as soon as ajax request is made, java script executes the second line regardless of the response. we can take the following example ``` $.ajax({ url: 'publish/submit_link.php', type: 'POST', dataType: 'JSON', data: { link : link, title : title, }, success: function (data) { console.log(data); } }); for(var i = 0; i < 15000000; i++) { console.log(i); } ``` you may see the output as follows ``` 1 2 3 . . . 1000 data//response of ajax . . 14999999 ``` so to avoid that you can use either [jQuery.when()](http://api.jquery.com/jQuery.when/) our ajax success function. Hopefully this will help you
19,489,787
I have 3 images that are all in the same line and float left but i would also like to centre them. I have tried using `margin: 0px auto;` but it doesn't seem to do anything. Any suggestions? CSS: ``` #boxes .box { width:370px; height:241px; float: left; margin: 0px auto; background-image:url(../imgs/box_front.png); background-repeat:no-repeat; background-color: #FFF; } ```
2013/10/21
[ "https://Stackoverflow.com/questions/19489787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From your selector, I can make out that the boxes which are floated to the left are nested inside element having an id of `#boxes`, so if you can, assign some fixed width to `#boxes` and than use `margin: auto;` ``` #boxes { width: 800px; /* You need to set this */ margin: auto; } ``` [**Demo**](http://jsfiddle.net/FF5cy/)
You should align to center to your parent div that is `#boxes` not to your image. Try this: ``` #boxes{ margin: 0 auto; text-align: center; } ```
19,489,787
I have 3 images that are all in the same line and float left but i would also like to centre them. I have tried using `margin: 0px auto;` but it doesn't seem to do anything. Any suggestions? CSS: ``` #boxes .box { width:370px; height:241px; float: left; margin: 0px auto; background-image:url(../imgs/box_front.png); background-repeat:no-repeat; background-color: #FFF; } ```
2013/10/21
[ "https://Stackoverflow.com/questions/19489787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
From your selector, I can make out that the boxes which are floated to the left are nested inside element having an id of `#boxes`, so if you can, assign some fixed width to `#boxes` and than use `margin: auto;` ``` #boxes { width: 800px; /* You need to set this */ margin: auto; } ``` [**Demo**](http://jsfiddle.net/FF5cy/)
Add this CSS ``` #boxes .box { width:370px; height:241px; float: left; margin: 0px auto; background-image:url(../imgs/box_front.png); background-repeat:no-repeat; background-position:center center; background-color: #FFF; } ```
19,489,787
I have 3 images that are all in the same line and float left but i would also like to centre them. I have tried using `margin: 0px auto;` but it doesn't seem to do anything. Any suggestions? CSS: ``` #boxes .box { width:370px; height:241px; float: left; margin: 0px auto; background-image:url(../imgs/box_front.png); background-repeat:no-repeat; background-color: #FFF; } ```
2013/10/21
[ "https://Stackoverflow.com/questions/19489787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It is impossible to center floated items. One of the things you can do - is make the items `inline-block` and set the `text-align: center` property to their parent. Online example: <http://jsfiddle.net/8HPWU/>
You should align to center to your parent div that is `#boxes` not to your image. Try this: ``` #boxes{ margin: 0 auto; text-align: center; } ```
19,489,787
I have 3 images that are all in the same line and float left but i would also like to centre them. I have tried using `margin: 0px auto;` but it doesn't seem to do anything. Any suggestions? CSS: ``` #boxes .box { width:370px; height:241px; float: left; margin: 0px auto; background-image:url(../imgs/box_front.png); background-repeat:no-repeat; background-color: #FFF; } ```
2013/10/21
[ "https://Stackoverflow.com/questions/19489787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It is impossible to center floated items. One of the things you can do - is make the items `inline-block` and set the `text-align: center` property to their parent. Online example: <http://jsfiddle.net/8HPWU/>
Add this CSS ``` #boxes .box { width:370px; height:241px; float: left; margin: 0px auto; background-image:url(../imgs/box_front.png); background-repeat:no-repeat; background-position:center center; background-color: #FFF; } ```
21,799,485
``` T1 - id, name, userID (stocks) - not really used in this cased T2 - id, name, stockID, userID (categories) T3 - id, name, stockID, categoryID, quality, userID (goods) ``` column "quality" can be "0" (good) or "1" (bad) and each goods (even same sort) = 1 row this SQL, (this "far" I can get), show only total count of good and bad stuff, and if category exist, but haven't any rows, then it's not shown in final results: ``` SELECT T2.name, COUNT(*) AS TOTAL FROM T3 LEFT JOIN T2 ON T2.id=T3.categoryID WHERE T3.stockID=2 GROUP BY T3.categoryID ``` Result: ``` CATEGORY - TOTAL category1 - 1237 category2 - 857 category3 - 125 ``` category4 is not shown, because no rows exist, but I need every single rows been shown, even if T3 rows doesn't exist and BAD stuff count of course.. Desired result: ``` CATEGORY - BAD / TOTAL category1 - 425 / 1237 category2 - 326 / 857 category3 - 0 / 125 category4 - 0 / 0 ```
2014/02/15
[ "https://Stackoverflow.com/questions/21799485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2576791/" ]
``` SELECT T2.name, SUM(CASE WHEN T3.quality=1 THEN 1 ELSE 0 END)AS BAD, COUNT(*)AS TOTAL FROM T2 LEFT JOIN T3 ON T2.id=T3.categoryID WHERE t2.stockid=2 GROUP BY T2.name; ```
I think you want to do the `left join` in the other direction (you could also do a `right outer join`). And change the `count()` to count matching records: ``` SELECT T2.name, coalesce(SUM(t.3bad), 0) as Bad, COUNT(t3.categoryID) AS TOTAL FROM T2 LEFT JOIN T3 ON T2.id = T3.categoryID and T3.stockID = 2; GROUP BY T2.name; ``` Also, it is a good idea to `select` the same fields that are in the `group by` clause. Really, more than a good idea. Most databases (and the standard) generally require this. The MySQL extension to `group by` can cause problems. Note that I moved the `where` condition into the `on` clause. This prevents additional filtering that would remove the rows you want.
7,226,226
I'm working on Two's complement addition. Basically I need to show the addition of -27 to +31, with both numbers in binary using 6 bits. My problem is with carry operations. Maybe I'm not doing it right or something. -27 is in binary: 111011 +31 is in binary: 011111 The answer I think should be: +4 is in binary: 000010 Here's what I'm doing: ``` Carry 1 1 1 1 1 - 27 1 1 1 0 1 1 + 31 0 1 1 1 1 1 ------------------------- Sum: 0 1 1 0 1 0 ``` Which in my mind computes to 52 not 4. What am I doing wrong?
2011/08/29
[ "https://Stackoverflow.com/questions/7226226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494901/" ]
your math is wrong. 27 is `0 1 1 0 1 1` in binary (note the leading 0 I added for the sign) -27 is `1 0 0 0 1 1` in two's complement. when you do the math with this, you should get the correct result. --- Here's a "trick" to perform two's complement quickly. Starting from the LSB, copy down the numbers exactly until you encounter the 1st zero, then copy that zero as well. After that, flip all the bits until the MSB. This is equivalent to flipping all the bits (one's complement) and adding one (to turn it into two's complement), but just in one step.
Hmmm, `31 - 27 = 4`, correct! :) `4 is 100` in binary though, an are you sure that `-27 is 111011`???
20,845,778
I currently have the problem that Jekyll does not work well with Markdown and LaTeX. So I have a lot of articles with `$\frac{some}{latex}$` or `$$\int^e_v {en} more$$`. **How can I replace `$...$` by `<span>$...$</span>` and `$$...$$` by `<div>$$..$$</div>`?** Things that make this task difficult are: * The `...` might include newlines. In fact, `...` might contain anything, except `$` * The first `$` gets replaced by `<span>$`, but the second one by `$</span>` * `$...$` and `$$...$$` can be used in the same document (but always seperated by at least one whitespace) edit: I've just seen that I also need some escaping. So the task has one more difficulty: * `\$` should not be matched for any of the two cases above.
2013/12/30
[ "https://Stackoverflow.com/questions/20845778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/562769/" ]
### We can accomplish this by doing two steps replacement: ``` import re str = "$rac{some}{latex}$$$\int^e_v {en} more$$\$rac{some}{latex}$$$\int^e_v {en} more$$\n$rac{some}{latex}$\n$$\int^e_v {en} more$$\n\$rac{some}{latex}$\n$$\int^e_v {en} more$$" #first step: str = re.sub(r'(?<![\\])\$\$([^\$]+)\$\$', "<div>$$\g<1>$$</div>", str) #second step: str = re.sub(r'(?<![\$\\])\$([^\$]+)(?:(?<!\<div\>)(?<!\\)\$)', "<span>$\g<1>$</span>", str) print str ``` Explanation: ------------ ### First step: We perform a replace only in the `$$` occurrences, replacing it by `<div>$$\g<1>$$</div>`(`\g<1>` will be replaced by the first group defined in the regex). ``` str = re.sub(r'(?<![\\])\$\$([^\$]+)\$\$', "<div>$$\g<1>$$</div>", str) ``` Realize that we are using this **regex** `(?<![\\])\$\$([^\$]+)\$\$` [regex101 example](http://regex101.com/r/lM6nF8) which works in the following way: 1. `(?<![\\]) ...` Defines that we are matching something `...` which is not preceded by a `\` *[in the regex: `(?<![\\])`]*. So firstly we said we do not want a `\` before the expression. 2. `... \$\$ ...` Defines that we have to have a `$$` occurrence in the beginning of the string. 3. `... ([^\$]+)` Defines that we want everything but a `$` after the previous step *[in the regex `[^\$]+`]*. And then we put it into a capture group `(...)`, for after refer to it in the code. 4. `... \$\$` After all we finish the expression saying that we have to have a `$$` occurrence in the final of the string. --- ### Second step: We perform a replace only in the `$` occurrences, replacing it by `<span>$\g<1>$</span>`(again, the `\g<1>` will be replaced by the first group match defined in the regex) ``` str = re.sub(r'(?<![\$\\])\$([^\$]+)(?:(?<!\<div\>)(?<!\\)\$)', "<span>$\g<1>$</span>", str) ``` Realize also that we are using this other **regex** `(?<![\$\\])\$([^\$]+)(?:(?<!\<div\>)(?<!\\)\$)` (yeah, little bit harder) [regex101 example](http://regex101.com/r/tI7aB0) which works in the following way: 1. `(?<![\$\\]) ...` Defines that we are matching something `...` which is not preceded by a `\` **or** a `$` *[in the regex: `(?<![\\\$])`]*. So firstly we said we do not want a `\` or a `$` in the beginning. 2. `... \$ ...` Defines that our string needs to start with one `$` 3. `... ([^\$]+) ...` Defines a capture group with everything but `$`, for future call back. 4. `... (?:(?<!\<div\>)(?<!\\)\$)` We finish saying that our string finish with a `$` but not preceded by a div *[in the regex: `?<!\<div\>)`]* or a `\` *[in the regex: `(?<!\\)`]*. (then we put it all into a non-capture group to say that all of this is only one thing `(?:(?<!\<div\>)(?<!\\)\$)`) --- ***Note:** perhaps there are more efficient ways to get this result.*
I *know* you asked for regex, but you'll run into headaches for those edges cases you mentioned you'll handle by hand. (If there are other regex solutions posted, compare this answer with theirs). With this it's simple to change the behavior of double and single TeX markers and handle escapes in the TeX code. Here is a very simple pyparsing example that does what you are looking for: ``` from pyparsing import * D1 = QuotedString("$",escChar='\\') D2 = QuotedString("$$",escChar='\\') div_action = lambda x: "<div>$%s$</div>"%x[0] span_action = lambda x: "<span>$$%s$$</span>"%x[0] D1.setParseAction(span_action) D2.setParseAction(div_action) others = Word(printables) grammar = OneOrMore(D2 | D1 | others).leaveWhitespace() ``` And a use case: ``` S = "$\LaTeX$ is worth $$x=\$3.40$$" print grammar.transformString(S) ``` Giving: ``` <span>$\LaTeX$</span> is worth <div>$$x=$3.40$$</div> ```
8,542,609
How to get active (having focus) frame (JInternalFrame) that is inside JDesktopPane? I need it for my MDI notepad (not that anybody would use that, just a training project). Looking at api, I see only functions to get all JInternalFrames, not active one.
2011/12/17
[ "https://Stackoverflow.com/questions/8542609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1046871/" ]
Use [JDekstopPane.getSelectedFrame()](http://docs.oracle.com/javase/7/docs/api/javax/swing/JDesktopPane.html) method (*From doc: currently active JInternalFrame in this JDesktopPane, or null if no JInternalFrame is currently active.*) or `JDesktopPane.getAllFrames()` to get list of all `JInternalFrames` currently displayed in the desktop and check `isSelected()` method.
Make a `List<JInternalFrame>` and check [`isSelected()`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JInternalFrame.html#isSelected%28%29) as you iterate though it. Addendum: See also this [example](http://groups.google.com/group/comp.lang.java.programmer/msg/2e1b14bcad9bd7fa) that uses `Action` to select an internal frame from a menu.
8,542,609
How to get active (having focus) frame (JInternalFrame) that is inside JDesktopPane? I need it for my MDI notepad (not that anybody would use that, just a training project). Looking at api, I see only functions to get all JInternalFrames, not active one.
2011/12/17
[ "https://Stackoverflow.com/questions/8542609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1046871/" ]
Use [JDekstopPane.getSelectedFrame()](http://docs.oracle.com/javase/7/docs/api/javax/swing/JDesktopPane.html) method (*From doc: currently active JInternalFrame in this JDesktopPane, or null if no JInternalFrame is currently active.*) or `JDesktopPane.getAllFrames()` to get list of all `JInternalFrames` currently displayed in the desktop and check `isSelected()` method.
Have you looked at the Java tutorial titled [How to Use Internal Frames](http://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html)? In your code you need an `InternalFrameListener` ([API](http://docs.oracle.com/javase/7/docs/api/javax/swing/event/InternalFrameListener.html)) ([Tutorial](http://docs.oracle.com/javase/tutorial/uiswing/events/internalframelistener.html)) and listen to activate/deactivate events. Activated means the internal frame was brought to the top; deactivated means it's no longer on top. Since `JDesktopPane` extends `JLayeredPane` you can also set the z-order of components added to it. Don't iterate over all the panes - use events. If for some reason you prefer to poll your UI rather than use an event-driven approach you can call `getSelectedFrame` which returns the active `JInternalFrame`. I'm not sure why no one else mentioned it.
3,057,981
I've just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what's going on with synchronize, wait() and notify(). I'm curious about whether there's a way to wait() on two resources at once. I think the following won't quite do what I'm thinking of (**edit**: *note that the usual while loops have been left out of this example to focus just on freeing up two resources*): ``` synchronized(token1) { synchronized(token2) { token1.wait(); token2.wait(); //won't run until token1 is returned System.out.println("I got both tokens back"); } } ``` In this (very contrived) case token2 will be held until token1 is returned, then token1 will be held until token2 is returned. The goal is to release both token1 and token2, then resume when both are available (note that moving the token1.wait() outside the inner synchronized loop is not what I'm getting at). A loop checking whether both are available might be more appropriate to achieve this behaviour (would this be getting near the idea of double-check locking?), but would use up extra resources - I'm not after a definitive solution since this is just to satisfy my curiosity. **Edit** Let's just for the sake of argument say that the two tokens here represent two distinct resources that the thread must use at the same time, and that some other threads will need both at the same time.
2010/06/16
[ "https://Stackoverflow.com/questions/3057981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297938/" ]
"\r" should work for both windows and Mac OS X. Something like: ``` std::cout << "will not see this\rwill see this" << std::flush; std::cout << std::endl; // all done ```
I don't have access to a mac, but from a pure console standpoint, this is going to be largely dependent on how it treats the carriage return and line-feed characters. If you can literally send one or the other to the console, you want to send *just* a carriage return. I'm pretty sure Mac treats both carriage returns and line-feeds differently than \*nix & windows. If you're looking for in-place updates (e.g. overwrite the current line), I'd recommend looking at the `curses` lib. This should provide a platform independent means of doing what you're looking for. (because, even using standard C++, there is no platform independent means of what you're asking for).
3,057,981
I've just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what's going on with synchronize, wait() and notify(). I'm curious about whether there's a way to wait() on two resources at once. I think the following won't quite do what I'm thinking of (**edit**: *note that the usual while loops have been left out of this example to focus just on freeing up two resources*): ``` synchronized(token1) { synchronized(token2) { token1.wait(); token2.wait(); //won't run until token1 is returned System.out.println("I got both tokens back"); } } ``` In this (very contrived) case token2 will be held until token1 is returned, then token1 will be held until token2 is returned. The goal is to release both token1 and token2, then resume when both are available (note that moving the token1.wait() outside the inner synchronized loop is not what I'm getting at). A loop checking whether both are available might be more appropriate to achieve this behaviour (would this be getting near the idea of double-check locking?), but would use up extra resources - I'm not after a definitive solution since this is just to satisfy my curiosity. **Edit** Let's just for the sake of argument say that the two tokens here represent two distinct resources that the thread must use at the same time, and that some other threads will need both at the same time.
2010/06/16
[ "https://Stackoverflow.com/questions/3057981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297938/" ]
"\r" should work for both windows and Mac OS X. Something like: ``` std::cout << "will not see this\rwill see this" << std::flush; std::cout << std::endl; // all done ```
As Nathan Ernst's answer says, if you want a robust, proper way to do this, use curses - specifically [ncurses](https://en.wikipedia.org/wiki/Ncurses). If you want a low-effort hackish way that tends to work, carry on... Command-line terminals for Linux, UNIX, MacOS, Windows etc. tend to support a small set of basic ASCII control characters, including character 13 decimal - known as a Carriage Return and [encoded in C++](https://en.cppreference.com/w/cpp/language/escape) as '\r' or equivalently in octal '\015' or hex '\x0D' - instructing the terminal to return to the start of the line. What you generally want to do is... ``` int line_width = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80; std::string spaces{line_width - 1, ' '}; for (const auto& filename : filenames) { std::cout << '\r' << spaces << '\r' << filename << std::flush; process_file(filename); } std::cout << std::endl; // move past last filename... ``` This uses a string of spaces to overwrite the old filename before writing the next one, so if you have a shorter filename you don't see trailing characters from the earlier longer filename(s). The [`std::flush`](https://en.cppreference.com/w/cpp/io/manip/flush) ensures the C++ program calls the OS `write()` function to send the text to the terminal before starting to process the file. Without that, the text needed for the update - `\r`, spaces, `\r` and a filename - will be appended to a buffer and only written to the OS - in e.g. 4k chunks - when the buffer is full, so the filename displayed would lag dozens of files behind the actual file being processing. Further, say the buffer is 4k - 4096 bytes - and at some point you have 4080 bytes buffered, then output text for the next filename: you'll end up with `\r` and 15 spaces fitting in the buffer, which when auto-flushed will end up wiping out the first 15 characters on the line on-screen and leaving the rest of the previous filename (if it was longer than 15 characters), then waiting until the buffer is full again before updating the screen (still haphazardly). The final `std::endl` just moves the cursor on from the line where you've been printing filenames so you can write "all done", or just leave `main()` and have the shell prompt display on a nice clean line, instead of potentially overwriting part of your last filename (great shells like zsh check for this).
3,057,981
I've just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what's going on with synchronize, wait() and notify(). I'm curious about whether there's a way to wait() on two resources at once. I think the following won't quite do what I'm thinking of (**edit**: *note that the usual while loops have been left out of this example to focus just on freeing up two resources*): ``` synchronized(token1) { synchronized(token2) { token1.wait(); token2.wait(); //won't run until token1 is returned System.out.println("I got both tokens back"); } } ``` In this (very contrived) case token2 will be held until token1 is returned, then token1 will be held until token2 is returned. The goal is to release both token1 and token2, then resume when both are available (note that moving the token1.wait() outside the inner synchronized loop is not what I'm getting at). A loop checking whether both are available might be more appropriate to achieve this behaviour (would this be getting near the idea of double-check locking?), but would use up extra resources - I'm not after a definitive solution since this is just to satisfy my curiosity. **Edit** Let's just for the sake of argument say that the two tokens here represent two distinct resources that the thread must use at the same time, and that some other threads will need both at the same time.
2010/06/16
[ "https://Stackoverflow.com/questions/3057981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297938/" ]
I don't have access to a mac, but from a pure console standpoint, this is going to be largely dependent on how it treats the carriage return and line-feed characters. If you can literally send one or the other to the console, you want to send *just* a carriage return. I'm pretty sure Mac treats both carriage returns and line-feeds differently than \*nix & windows. If you're looking for in-place updates (e.g. overwrite the current line), I'd recommend looking at the `curses` lib. This should provide a platform independent means of doing what you're looking for. (because, even using standard C++, there is no platform independent means of what you're asking for).
As Nathan Ernst's answer says, if you want a robust, proper way to do this, use curses - specifically [ncurses](https://en.wikipedia.org/wiki/Ncurses). If you want a low-effort hackish way that tends to work, carry on... Command-line terminals for Linux, UNIX, MacOS, Windows etc. tend to support a small set of basic ASCII control characters, including character 13 decimal - known as a Carriage Return and [encoded in C++](https://en.cppreference.com/w/cpp/language/escape) as '\r' or equivalently in octal '\015' or hex '\x0D' - instructing the terminal to return to the start of the line. What you generally want to do is... ``` int line_width = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 80; std::string spaces{line_width - 1, ' '}; for (const auto& filename : filenames) { std::cout << '\r' << spaces << '\r' << filename << std::flush; process_file(filename); } std::cout << std::endl; // move past last filename... ``` This uses a string of spaces to overwrite the old filename before writing the next one, so if you have a shorter filename you don't see trailing characters from the earlier longer filename(s). The [`std::flush`](https://en.cppreference.com/w/cpp/io/manip/flush) ensures the C++ program calls the OS `write()` function to send the text to the terminal before starting to process the file. Without that, the text needed for the update - `\r`, spaces, `\r` and a filename - will be appended to a buffer and only written to the OS - in e.g. 4k chunks - when the buffer is full, so the filename displayed would lag dozens of files behind the actual file being processing. Further, say the buffer is 4k - 4096 bytes - and at some point you have 4080 bytes buffered, then output text for the next filename: you'll end up with `\r` and 15 spaces fitting in the buffer, which when auto-flushed will end up wiping out the first 15 characters on the line on-screen and leaving the rest of the previous filename (if it was longer than 15 characters), then waiting until the buffer is full again before updating the screen (still haphazardly). The final `std::endl` just moves the cursor on from the line where you've been printing filenames so you can write "all done", or just leave `main()` and have the shell prompt display on a nice clean line, instead of potentially overwriting part of your last filename (great shells like zsh check for this).
49,491,839
I have multiple WARs that expose CXF JAXRS endpoints. They have similar web.xml ``` <web-app id="app1"> <context-param> <param-name>contextClass</param-name> <param-value>org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:META-INF/spring/*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>app1</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>app1</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app> ``` They share common Spring configuration (named `common-rest.xml`) ``` <beans> <import resource="classpath:META-INF/cxf/cxf.xml" /> <context:annotation-config /> <bean id="httpDestinationRegistry" class="org.apache.cxf.transport.http.DestinationRegistryImpl" /> <bean id="baseJaxRSServer" abstract="true" lazy-init="false" class="org.apache.cxf.jaxrs.spring.JAXRSServerFactoryBeanDefinitionParser.SpringJAXRSServerFactoryBean" init-method="create" p:address="${http.server}/" /> </beans> ``` And every bean has similar configuration ``` <beans> <import resource="classpath:META-INF/app/common-rest.xml" /> <bean id="app1JaxRSServer" parent="baseJaxRSServer" p:serviceBeans-ref="app1ServiceBeans" /> </beans> ``` Exact path is defined in each bundle's MANIFEST ``` Web-ContextPath: app1 ``` The problem is I can't make multiple bundles work together. With single bundle it's working OK, but if I try to run another one I get exception for creating `app1JaxRSServer` bean ``` org.apache.cxf.service.factory.ServiceConstructionException: There is an endpoint already running on /. ``` Using Karaf 4.0.9, CXF 3.1.13, Spring 3.2.18
2018/03/26
[ "https://Stackoverflow.com/questions/49491839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/878418/" ]
The controller action on the server side will need a concrete type to read the entire body of the request ``` public class Order { public int OrderId { get; set; } public int[] Ids { get; set; } } ``` This is primarily because the action can only read from the body once. Update action to... ``` [HttpPost] [ActionName("cancel")] public async Task<Response> Cancel([FromBody]Order order) { if(ModelState.IsValid) { int orderId = order.OrderId; int[] ids = order.Ids; //... } //... } ``` the original code used to send the request in the example will work as is, but as mentioned it can be improved.
The HttpClient can do the serialisation for you. See if ``` var response = await client.PostAsJsonAsync($"{url}/admin/cancel", obj); ``` works better. Then you don't need to write the serialisation code yourself. If you still have a problem, use a tool such as Fiddler to monitor the actual request and see what parameter and values are submitted in the request body, to see if they match what's expected by the endpoint.
147,548
We are writing a application in which a part of the job is to fetch a relatively large (>10000 features) and often updated dataset from a WFS server, store a local copy, and do geospatial analyses on it. We are stuck on the downloading part, as we hit the default 1000 features limit on the server side, which we do not control. We see that QGIS for example can access this dataset completely, from which we can in principle manually save it in a suitable format for our application, but this is not the desirable way to go, as we want a completely automatic procedure. We are using OGR (ogr2ogr) and can get local copies of up to 1000 features. We wonder if there is an easy way to get the entire dataset using this approach. Hints to other approaches are also welcome.
2015/05/17
[ "https://gis.stackexchange.com/questions/147548", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/-1/" ]
If you are using Linux, you should be able to connect to a WFS server, and fetch a layer without any problem with `wget`. I was able to fetch a dataset consisting of 10209 features, which was 33.3 MB in size. My test command was the following: ``` wget -O output.gml "http://demo.opengeo.org/geoserver/wfs?request=GetFeature&version=1.1.0&typeName=osm:admin_5678&srsname=EPSG:3857" ``` Be sure to endorse the URL in quotes, as they contain more than one parameters, and otherwise it would be interpreted by the shell incorrectly. The `-O` flag writes the received data into a user specified file, but it has to be included before the URL. ![output](https://i.stack.imgur.com/jBDiR.png)
You could try the OGR WFS option "-dsco OGR\_WFS\_PAGING\_ALLOWED=ON" as described in the docs <http://www.gdal.org/drv_wfs.html>
147,548
We are writing a application in which a part of the job is to fetch a relatively large (>10000 features) and often updated dataset from a WFS server, store a local copy, and do geospatial analyses on it. We are stuck on the downloading part, as we hit the default 1000 features limit on the server side, which we do not control. We see that QGIS for example can access this dataset completely, from which we can in principle manually save it in a suitable format for our application, but this is not the desirable way to go, as we want a completely automatic procedure. We are using OGR (ogr2ogr) and can get local copies of up to 1000 features. We wonder if there is an easy way to get the entire dataset using this approach. Hints to other approaches are also welcome.
2015/05/17
[ "https://gis.stackexchange.com/questions/147548", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/-1/" ]
The easiest way to do this, is to use GDAL's ogr2ogr utility. Firstly, you need to create an XML file with the URL to the WFS endpoint. ``` <OGRWFSDataSource> <URL>http://demo.opengeo.org/geoserver/ows?service=wfs&amp;typeName=osm:roads</URL> <PagingAllowed>ON</PagingAllowed> </OGRWFSDataSource> ``` If you want to add any other parameter, like a filter, you can add it to the url as well. Just remember to make sure that the URL is XML escaped Then you can just run ogr2ogr, with a command like this: `ogr2ogr -f "SQLite" roads.db road.xml` If you want to write to a shapefile, you can use a command like: `ogr2ogr roads road.xml` You can get more details about the optional parameters here: [WFS driver](http://www.gdal.org/drv_wfs.html)
You could try the OGR WFS option "-dsco OGR\_WFS\_PAGING\_ALLOWED=ON" as described in the docs <http://www.gdal.org/drv_wfs.html>
40,498,878
I'm trying to understand the concepts of Linked Lists. I've searched for information about my question but I haven't found any answer which would help me. I'd like to know how to check if linked list is sorted? Evidently, we can't use the simple two lines function as for regular lists. For example if I want to check if my list is sorted(without using `list.sort()`), I'll create the function like this: ``` def is_sorted(l): return all(a <= b for a, b in zip(l[:-1], l[1:])) ``` But for the linked list, should I compare list tail and head values? How it works exactly? --- Contruction I use to create Linked Lists: ``` class Node : def __init__(self, data): self.data = data self.next = None self.prev = None class LinkedList: def __init__(self): self.head = None def add(self, data): node = Node(data) if self.head == None: self.head = node else: node.next = self.head node.next.prev = node self.head = node def search(self, k): p = self.head if p != None : while p.next != None : if ( p.data == k ) : return p p = p.next if ( p.data == k ) : return p return None def remove( self, p ) : tmp = p.prev p.prev.next = p.next p.prev = tmp def __str__( self ) : s = "" p = self.head if p != None : while p.next != None : s += p.data p = p.next s += p.data return s ```
2016/11/09
[ "https://Stackoverflow.com/questions/40498878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6182035/" ]
You can do basically the same thing. The only caveat is that you need a way to iterate over your linked list... ``` class LinkedList: ... def __iter__(self): p = self.head while p: # I yield the data for simplicity in this problem. # Depending on the constraints for linked lists, it might be # nicer to yield nodes. yield p.data p = p.next ``` Now that we have that, checking if it is sorted is easy and pretty much analogous to the method you wrote for lists earlier: ``` def is_sorted(linked_list): iter1 = iter(linked_list) iter2 = iter(linked_list) next(iter2, None) # drop the first element in iter2. return all(i1 <= i2 for i1, i2 in zip(iter1, iter2)) ``` Also note that having a method for iterating over the linked list really simplifies other methods that you've already written. e.g. ``` def __str__(self): return ''.join(iter(self)) # Original code assumes string data, so I do too. ```
Calling this a **linkedList** does not cause it to become compatible with Python's **list** type. :-) Your **LinkedList** class doesn't have the methods necessary to make it an iterable object in Python. Thus, you can't use the built-in functions that work on iterables. You'd have to write a new method to check the list: traverse from head to tail, checking that each element's value is >= the previous one. Alternatively, look up the [additional methods](https://stackoverflow.com/questions/9884132/what-exactly-are-pythons-iterator-iterable-and-iteration-protocols#9884259) needed to make this an iterable (you need more methods of the form ), and then apply your known solution.
64,443,461
I am reading a file and looking for this string in the file.looking to capture the value(00:00:22) using regex.I have written regular expression but its not finding that value? ``` "20.10.02 00:00:22:135 INFO Running Cron : BatchJob" Pattern p = Pattern.compile("([01][0-9]|2[0-3]):([01][0-9]|2[0-3]) INFO Running Cron", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(line); System.out.println(m.find()); ```
2020/10/20
[ "https://Stackoverflow.com/questions/64443461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/739115/" ]
This is not possible in TS right now. because it adds considerable complexity to their Control-Flow Analyzer. other than explicitly putting `foo !== null` as the `if expression`, there two possible things to do: 1- using [Assertions](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions): ``` if (test){ // since test is equal to (foo !== null) foobar(foo as string) } ``` But it's a bit bug-prone because you may change the `test` variable in the future then that type assertion would lead to bugs because foo is no longer for sure a `string`. 2- [User-Defined Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) The better way in my opinion is using user-defined type guard as @VLAZ correctly mentioned. ``` const isNotNull = <T>(x:T): x is Exclude(T, null) => x !== null if (isNotNull(foo)){ foobar(foo) } ```
This is currently not possible (see [this issue](https://github.com/microsoft/TypeScript/issues/12184)). Here's a workaround. It assigns `wrappedFoo` a type which either contains a string and true, or null and false. After checking for the boolean value, Typescript knows which of those two it is: ```js const foo: string | null = Math.random() > .5 ? null : 'bar' const wrappedFoo = foo === null ? { foo, isString: false as const } : { foo, isString: true as const } if (wrappedFoo.isString){ console.log(wrappedFoo.foo.length) } else { console.log(wrappedFoo.foo.length) // Error Object is possibly 'null' } ```
64,443,461
I am reading a file and looking for this string in the file.looking to capture the value(00:00:22) using regex.I have written regular expression but its not finding that value? ``` "20.10.02 00:00:22:135 INFO Running Cron : BatchJob" Pattern p = Pattern.compile("([01][0-9]|2[0-3]):([01][0-9]|2[0-3]) INFO Running Cron", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(line); System.out.println(m.find()); ```
2020/10/20
[ "https://Stackoverflow.com/questions/64443461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/739115/" ]
This is not possible in TS right now. because it adds considerable complexity to their Control-Flow Analyzer. other than explicitly putting `foo !== null` as the `if expression`, there two possible things to do: 1- using [Assertions](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions): ``` if (test){ // since test is equal to (foo !== null) foobar(foo as string) } ``` But it's a bit bug-prone because you may change the `test` variable in the future then that type assertion would lead to bugs because foo is no longer for sure a `string`. 2- [User-Defined Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards) The better way in my opinion is using user-defined type guard as @VLAZ correctly mentioned. ``` const isNotNull = <T>(x:T): x is Exclude(T, null) => x !== null if (isNotNull(foo)){ foobar(foo) } ```
Next version of Typescript (4.4) [will support control flow analysis of conditional expressions](https://github.com/microsoft/TypeScript/pull/44730). The only change you'll need to do is `let foo` -> `const foo`, because > > Narrowing through indirect references occurs only when the conditional expression or discriminant property access is declared in a `const` variable declaration with no type annotation, and the reference being narrowed is a const variable, a readonly property, or a parameter for which there are no assignments in the function body > > > [Playground v4.4](https://www.typescriptlang.org/play?ts=4.4.0-dev.20210702#code/MYewdgzgLgBAZiEMC8MCyBDKALAdAJwzABMQBbACgEoYA%20GXAVhgH4YwBXAGy5gC4YAcgBGGfIICwAKFCRYIHAFN8ABXwgADihhR8HRdNnQdi46gRIAhMlSceMAGQOYC7MrWbpcDmGBQAluDwiKL4FAAeAtD4-mAA5jQA3jAAvtLSAPQZMBDYINzEMMrq%20F4hYhQWVOlSWTl5BewKRfgl0v5wMBRQplBJ0jCDwSChlYjVUilAA)
49,320,384
Is there a way in Laravel to do some check on associating? For example I've `Home` and `Owner`, I would like on `associate` check if `Home` as already an `Owner`, and in that case I must execute some code... Some suggestions?
2018/03/16
[ "https://Stackoverflow.com/questions/49320384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1663720/" ]
You should use `event.stopPropagation();` who prevents the event from beeing trigger with the children elements. There is the doc : <https://api.jquery.com/event.stoppropagation/>
Its a Firefox-Bug. In Firefox the "Dragenter-Event" gets fired twice. No matter if there is any child-element or not. You could try to work with event.target and event.currentTarget in combination with pointer-events: none.
5,516,743
I'm trying to setup a 2-column layout where the left area is fixed and the main content is fluid. I've seen several answers on here, which tend to work. However, there is some odd behavior when I use a "jsTree" in my "left" area and jQuery UI tabs in the main/content area. **html** ``` <div id="main"> <div id="left"> <div id="tree"> </div> </div> <div id="right"> <ul> <li><a href="#a">A</a></li> <li><a href="#b">B</a></li> <li><a href="#c">C</a></li> </ul> <div id="a"> <h3>A is here</h3> </div> <div id="b"> <h3>B is here</h3> </div> <div id="c"> <h3>C is here</h3> </div> </div> </div> ``` **css** ``` #left { float: left; width: 200px; overflow: auto; } #right { margin: 0 0 0 200px; } ``` **javascript** ``` $(document).ready(function() { $('#right').tabs(); $('#tree').jstree({ "plugins" : [ "json_data", "themes"], "json_data" : { "data" : [ { "data" : "A node", "children" : [ "Child 1", "Child 2" ] }, { "attr" : { "id" : "li.node.id" }, "data" : { "title" : "Long format demo", "attr" : { "href" : "#" } } } ] }, }); }); ``` The problem I'm having is, as I expand the tree (on the left) the tabs on the right start getting funky. The area containing the tabs (the element I believe) grows vertically. Take a look here for this example: <http://jsfiddle.net/codecraig/gBUw2/>
2011/04/01
[ "https://Stackoverflow.com/questions/5516743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70535/" ]
Josiah has it right but a better solution is to change the nature of the clear-fix technique. The `.ui-helper-clearfix` does this: ``` .ui-helper-clearfix::after { clear: both; content: '.'; display: block; height: 0px; visibility: hidden; } ``` And the problem is the `clear:both`. You can get the desired clearing without losing the full-width block display with this: ``` #right .ui-helper-clearfix { clear: none; overflow: hidden; } ``` That replaces the `clear:both` *clear-fix* with an `overflow:hidden` *clear-fix*. <http://jsfiddle.net/ambiguous/BkWWW/>
The widget tabs header has a clear fix. [updated fiddle](http://jsfiddle.net/gBUw2/4/). You could fix this with a non float layout, or override the css like so: ``` #right .ui-helper-clearfix { display: inline-block; } ``` This makes it so that the header does not expand the full width of the container however.
5,516,743
I'm trying to setup a 2-column layout where the left area is fixed and the main content is fluid. I've seen several answers on here, which tend to work. However, there is some odd behavior when I use a "jsTree" in my "left" area and jQuery UI tabs in the main/content area. **html** ``` <div id="main"> <div id="left"> <div id="tree"> </div> </div> <div id="right"> <ul> <li><a href="#a">A</a></li> <li><a href="#b">B</a></li> <li><a href="#c">C</a></li> </ul> <div id="a"> <h3>A is here</h3> </div> <div id="b"> <h3>B is here</h3> </div> <div id="c"> <h3>C is here</h3> </div> </div> </div> ``` **css** ``` #left { float: left; width: 200px; overflow: auto; } #right { margin: 0 0 0 200px; } ``` **javascript** ``` $(document).ready(function() { $('#right').tabs(); $('#tree').jstree({ "plugins" : [ "json_data", "themes"], "json_data" : { "data" : [ { "data" : "A node", "children" : [ "Child 1", "Child 2" ] }, { "attr" : { "id" : "li.node.id" }, "data" : { "title" : "Long format demo", "attr" : { "href" : "#" } } } ] }, }); }); ``` The problem I'm having is, as I expand the tree (on the left) the tabs on the right start getting funky. The area containing the tabs (the element I believe) grows vertically. Take a look here for this example: <http://jsfiddle.net/codecraig/gBUw2/>
2011/04/01
[ "https://Stackoverflow.com/questions/5516743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70535/" ]
The widget tabs header has a clear fix. [updated fiddle](http://jsfiddle.net/gBUw2/4/). You could fix this with a non float layout, or override the css like so: ``` #right .ui-helper-clearfix { display: inline-block; } ``` This makes it so that the header does not expand the full width of the container however.
All you need to do is to simply tweak your css, like this: ``` #left { float: left; width: 23%; overflow: auto; } #right { float: left; width: 75%; display: block; } ``` This would also fix the issue that the tabs' container don't expand full width. Though you could tune the width percentage of #right to whatever you like.
5,516,743
I'm trying to setup a 2-column layout where the left area is fixed and the main content is fluid. I've seen several answers on here, which tend to work. However, there is some odd behavior when I use a "jsTree" in my "left" area and jQuery UI tabs in the main/content area. **html** ``` <div id="main"> <div id="left"> <div id="tree"> </div> </div> <div id="right"> <ul> <li><a href="#a">A</a></li> <li><a href="#b">B</a></li> <li><a href="#c">C</a></li> </ul> <div id="a"> <h3>A is here</h3> </div> <div id="b"> <h3>B is here</h3> </div> <div id="c"> <h3>C is here</h3> </div> </div> </div> ``` **css** ``` #left { float: left; width: 200px; overflow: auto; } #right { margin: 0 0 0 200px; } ``` **javascript** ``` $(document).ready(function() { $('#right').tabs(); $('#tree').jstree({ "plugins" : [ "json_data", "themes"], "json_data" : { "data" : [ { "data" : "A node", "children" : [ "Child 1", "Child 2" ] }, { "attr" : { "id" : "li.node.id" }, "data" : { "title" : "Long format demo", "attr" : { "href" : "#" } } } ] }, }); }); ``` The problem I'm having is, as I expand the tree (on the left) the tabs on the right start getting funky. The area containing the tabs (the element I believe) grows vertically. Take a look here for this example: <http://jsfiddle.net/codecraig/gBUw2/>
2011/04/01
[ "https://Stackoverflow.com/questions/5516743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70535/" ]
Josiah has it right but a better solution is to change the nature of the clear-fix technique. The `.ui-helper-clearfix` does this: ``` .ui-helper-clearfix::after { clear: both; content: '.'; display: block; height: 0px; visibility: hidden; } ``` And the problem is the `clear:both`. You can get the desired clearing without losing the full-width block display with this: ``` #right .ui-helper-clearfix { clear: none; overflow: hidden; } ``` That replaces the `clear:both` *clear-fix* with an `overflow:hidden` *clear-fix*. <http://jsfiddle.net/ambiguous/BkWWW/>
All you need to do is to simply tweak your css, like this: ``` #left { float: left; width: 23%; overflow: auto; } #right { float: left; width: 75%; display: block; } ``` This would also fix the issue that the tabs' container don't expand full width. Though you could tune the width percentage of #right to whatever you like.
61,367,678
Consider following code snippet: ``` enum class Bar { A }; void foo(Bar) {} struct Baz { void foo() { foo(Bar::A); } }; ``` It fails to compile, the message from gcc 9.2 is: ``` :12:19: error: no matching function for call to 'Baz::foo(Bar)' 12 | foo(Bar::A); | ``` I don't suspect it is a bug since clang 10 also fails. I have two questions regarding this situation: 1. Where does standard define bahaviour for such overloads? 2. What are the possible reasons that compiler behaviour is specified that way? [live example](https://godbolt.org/z/LcnL9-)
2020/04/22
[ "https://Stackoverflow.com/questions/61367678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3414900/" ]
According to the rule of unqualified name lookup, from the standard, [[basic.lookup.unqual]/1](https://timsong-cpp.github.io/cppwp/basic.lookup.unqual#1), (emphasis mine) > > In all the cases listed in [basic.lookup.unqual], the scopes are searched for a declaration in the order listed in each of the respective categories; **name lookup ends as soon as a declaration is found for the name**. > > > That means the name `foo` is found at the class scope (i.e. the `Baz::foo` itself), then name lookup stops; the global one won't be found and considered for the overload resolution which happens later. About your 2nd question, functions can't be overloaded through different scopes; which might cause unnecessary confusion and complexity. Consider the following code: ``` struct Baz { void foo(int i) { } void foo() { foo('A'); } }; ``` You know `'A'` would be converted to `int` then passed to `foo(int)`, that's fine. If functions are allowed to be overloaded through scopes, if someday a `foo(char)` is added in global scope by someone or library, behavior of the code would change, that's quite confusing especially when you don't know about the adding of the global one.
The call to `foo` inside `Baz::foo()` will only look up names inside the class. If you mean to use the `foo` declared outside the class `Baz`, you need to use the scope-resolution operator, like this: ``` enum class Bar { A }; void foo(Bar) {} struct Baz { void foo() { ::foo(Bar::A); // looks up global 'foo' } }; ``` Note that the unscoped call to `foo` fails because there is a `Bar::foo` that is found in the closest scope. If you name the function differently, then no function is found in `Bar`, and the compiler will look in the outer scope for the function. ``` enum class Bar { A }; void foo(Bar) {} struct Baz { void goo() { // not 'foo' foo(Bar::A); // this is fine, since there is no 'Bar::foo' to find } }; ``` Here's the quote from [cppreference](https://en.cppreference.com/w/cpp/language/unqualified_lookup#Class_definition) for a *class definition*. > > e) if this class is a member of a namespace, or is nested in a class that is a member of a namespace, or is a local class in a function that is a member of a namespace, the scope of the namespace is searched until the definition of the class, enclosing class, or function. if the lookup of for a name introduced by a friend declaration: in this case only the innermost enclosing namespace is considered, otherwise lookup continues to enclosing namespaces until the global scope as usual. > > > Of course, this only applies to class definitions, but for *member functions* (which is your example), it says > > For a name used inside a member function body, a default argument of a member function, exception specification of a member function, or a default member initializer, the scopes searched are the same as in [class definition], ... > > > So the same logic applies.
12,525
I've been scouring google to see if it's possible to record gameplay audio for consoles as well as live commentary from a microphone or headset. Most of what I come across, from either forums or product FAQs say that it's possible to do one but not both. On PCs, it's easy, but on consoles you can only do one. Or so I'm told. However, I see quite a few videos on Youtube from consoles with both game audio and live commentary. So it must be possible. Can anyone tell me how how it's possible to do both on a console? I know nothing about video editing and production so I'm curious what devices and programs are needed to accomplish this. Also, is it possible to record the console audio and live commentary as two separate tracks? Thank you for your time! I appreciate any help.
2014/09/02
[ "https://avp.stackexchange.com/questions/12525", "https://avp.stackexchange.com", "https://avp.stackexchange.com/users/6425/" ]
`-preset` ========= Use the slowest preset that is fast enough that it does not drop frames. You can see if `ffmpeg` is dropping frames in the console output (if I recall correctly). Presets are: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow. `-crf` ====== Use the highest `-crf` value that still provides an acceptable quality level. Range is 0-51. 0 is lossless, 18 is generally considered to be visually lossless or nearly so, 23 is default, and 51 is worst quality. Using a value of 1 will likely result in a huge file. ### Also see: * [FFmpeg H.264 Video Encoding Guide](https://trac.ffmpeg.org/wiki/Encode/H.264)
You specify a preset and a quality value at the same time and by that overriding the preset. I would also recommend you don't encode with ffmpeg while capturing as this would be pretty slow on most PCs. The "error" in your ffmpeg commandline is the option `-crf 1`. `CRF` is a quality setting of x264 and the lower the value the higher the bitrate of the video will be. Setting it to `1` will make the video pretty much lossless. Just leave that command out and maybe use a preset like `medium` or `slow` and not `ultrafast` like you have right now to get a decent quality.
4,776,446
There a lot of C++ class libraries either open source or commercial like MFC, ATL, SmartWin++, QT. but none of them has the design and the architecture and the purity of .NET framework class library. What about the idea of implementing C++ library that is like .NET framework class library and provide the developers with a wide range of features and of course the library will be unmanaged and will wrap win32 API and COM
2011/01/23
[ "https://Stackoverflow.com/questions/4776446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/539471/" ]
Interesting question. But I believe it would be either a waste of time or not optimal to re-create the .NET BCL (base class library) for unmanaged C++. Why is that? 1. The C++ language is quite different from the .NET languages. This means that if you were to re-write the BCL for C++, you would optimally try to make the best use of C++. This would probably result in a fairly different framework design: * `IDisposable` and `Close` methods would not be necessary, since C++ offers deterministic freeing of releases and teardown of objects; something like `using` blocks, but far more generic. (The relevant C++ concepts are scopes, automatic storage, RAII, and smart pointer classes.) That is, a C++ BCL has the potential for a much more elegant design in this respect. * C++ templates are quite different from .NET generics. C++ also doesn't have delegates or events (even though you could probably mimick these). Reflection and run-time type and code generation also won't work easily with C++. Finally, C++ (before C++0x) doesn't support lambda functions. This means that the more modern additions to the BCL would probably have to look quite different in C++. 2. There are things in the BCL that have become obsolete, or if you designed the BCL today, it would turn out quite differently. Let's take `System.Reflection`. This part of the BCL was built before generics were introduced. If it was re-written from scratch today, chances are that reflection would take advantage of generics and therefore better type safety. 3. As you see, a new, C++ version of the BCL would very likely end up quite different than the .NET BCL it's based on; so you ought to wonder if it's even necessary to base such a new library on the .NET BCL at all. Do you even need to have one single framework, or is it easier in the end to develop separate libraries? One for networking, one for abstract data types, one for GUIs, one for reflection etc. * Separate libraries have the disadvantage that they possibly have no consistent API design. Therefore experience with one library doesn't help you at all learning another API. * Because of that, separate libraries can be easier to maintain. One can maintain the reflection library without having to concert each of one's actions with the GUI library maintainers, for example. * Separate libraries have the advantage that you can exchange one for the other if you find a cleaner, faster, or otherwise better replacement. 4. Even if someone wrote a C++ version of the BCL -- it would take much resources to maintain such a library in the long term, even more so when you consider that it should be platform-independent. Microsoft has this capacity and these resources. Would you, too? The lure of one great library for everything is indeed the consistency of one API, and the fact that "everyone" would use it. But I think even if you wrote such a C++ BCL, you'll find it hard to reach almost every C++ programmer and convince them to your that library.
I assume: That you like C++ for performance reasons. That you like .NET for productivity reasons. You can try, but finally you will note that C++ will not supply the language constructions possible in managed languages (features as delegates, native interfaces, variance, lambda expressions, LINQ, etc), you can mimick but it will not look clean as you see in C# (you will need ugly preprocessor defines, and get up cryptic code, things that will not help code refactoring and other mantainance tasks). You could check 2 alternatives: * The alternative of use [D (a new language)](http://dlang.org/). D is inspired on C++ performance and Java or.NET productivity. D compiler targets to native code, NOT Virtual Machine instruction set. But you need take off many editor tools, like Visual Studio's Intellisense and the native standard class library is under development yet. * Or you can use [AOT (Ahead of time compilation)](http://www.mono-project.com/AOT) or [NGEN (Native Image Generation)](http://msdn.microsoft.com/en-us/library/6t9t5wcf(v=VS.100).aspx). To compile .NET bytecode to native code. But it has some restrictions. In both cases you get a modern language thinked for productivity and better performance than raw .NET platform without the cost of implement your own C++ BCL.
26,857
There is a lot of track remixes online. Most of producers use separated vocals from songs. It is almost impossible that they could cut only vocal out of total track in such good quality. What is more, anywhere in the network is not available finished dry vocal version. So how is it possible that they are in possession of such good vocal version? Assume also that they have not purchased it from the artist. Please tell me HOW?? O\_O Thx
2013/10/17
[ "https://sound.stackexchange.com/questions/26857", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/6561/" ]
The generic term for split / separated tracks is "stems". If you google "vocal stems" you'll find free ones for random songs, not hits but usable. Vocal stems for popular songs are usually available (at a price) from the label or artist.
They purchased it from the artist, or possibly the record company. There is no other clean or effective option. Sound, and particularly voices are complex and once you mix sounds together, they can't be separated cleanly. It's kind of like if you mix water from one cup with water in another cup, you can't get the water back in the cups they came from. If you had the exact copy of everything but the vocals, you could do a subtraction (invert phase and mix together), but if you don't have either the instruments or the vocal track, you can't separate them cleanly. Also, if anything was altered with an instrumental track, it wouldn't work right either, though it might still get a passable result.
25,234,556
In vim, I could use `:%sno/[abt]//g` to remove all text of "[abt]" literally (as explained [here](http://vim.wikia.com/wiki/Simplifying_regular_expressions_using_magic_and_no-magic)). I tried the same command in `evil-mode`, but it complains it doesn't understand the `sno` command, so how can I do the same thing in `evil-mode`?
2014/08/11
[ "https://Stackoverflow.com/questions/25234556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266185/" ]
To my knowledge, `evil` does not (yet?) support the "magic/no magic" regexp options (actually, it only does a smallish subset of `ex` functionality~~, so I don't think `%` will work either~~). As @Ehvince's answer suggests, the standard Emacs way to do the replace is with `query-replace` or `query-replace-regexp`. If you'd like to stick to `evil`, just escape the square brackets with a backslash: ``` :s/\[abt\]//g ``` *NB*: backslash escapes in Emacs often bite people coming from other environments or programming languages; have a look at [the bottom of this manual node on the backslash](http://www.gnu.org/software/emacs/manual/html_node/elisp/Regexp-Special.html#Regexp-Special) for more information.
You would use the emacs command `query-replace` bound to `M-%`: ``` M-% [abt] RET <nothing> RET ``` and then approve each occurence with `y` or all with `!`. The doc is at `C-h f query-replace`. `query-replace-regexp` is bound to `C-M-%`.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
I think the best term *is* "reticle." Businesses that make the glass used in cameras call them reticles. See the images on this site: <http://www.reticles.com/reticles_kr900.htm>.
Cross hairs are meant for aiming (centering) and are not usually interactive. The rectangular visualization's primary purpose is not centering of focus, but selecting the relevant part of the image for scanning. Theoretically user can change both size and location in the screen, therefore this is not a common cross hair. The rectangular visualization enables the user to see and modify the "region of interest". (See definition of "region of interest" or ROI here [[Wikipedia]](http://en.wikipedia.org/wiki/Region_of_interest), [[Mathworks]](http://www.mathworks.com/help/toolbox/images/f19-13234.html), [[Wolfram]](http://library.wolfram.com/examples/roi/)). I found that this rectange is refered to as ["**viewfinder box**"](http://acer-tr.custhelp.com/app/answers/detail/a_id/16483/~/how-to-install-a-printer-with-acer-print), ["**viewfinder rectange**"](http://areacellphone.com/2010/05/howto-download-install-android-apps-using-qr-codes/), ["**viewfinder area**"](http://www.quickmark.cn/en/Info/android.asp), ["**crosshair box**"](http://www.cadtutor.net/forum/archive/index.php/t-17689.html) (or ["annoying yellow box around crosshair"](http://forums.steampowered.com/forums/showthread.php?t=1718837) in non-QR usage), however a more correct term (which is commonly used in image processing) would be "**region of interest**". Relevent queries: [viewfinder box](https://www.google.com/search?q=%22viewfinder+box%22+qr&hl=en&tbm=isch) [viewfinder rectangle](https://www.google.com/search?q=%22viewfinder+rectangle%22+qr&hl=en&tbm=isch) [viewfinder area](https://www.google.com/search?q=%22viewfinder+area%22+qr&hl=en&tbm=isch)
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
I think the best term *is* "reticle." Businesses that make the glass used in cameras call them reticles. See the images on this site: <http://www.reticles.com/reticles_kr900.htm>.
I've written a number of QR code-reading apps, and have always called it a "reticle" in my code, because (son of a photographer here) I was always taught that *any* lines, grid, crosshair, or indicia overlaid on a view (like a viewfinder in a camera) were *all* called reticles. Hence, it's a general term: a crosshair overlaid on a view is *also* a kind of reticle. I can see why it's not such a good user-facing term however, as it's not a simple, common English descriptive term. So for user-facing purposes, I'd go with Apple's usage and call it the "Focus Area," even if it's not literally used for focusing the lens— the point is it's directing the user where to put the focus of their attention.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
**Colloquial: *Target Area,* \*Focus Area,\* or *Focus Frame*** It looks like "[target area](http://www.google.com/imgres?hl=en&biw=1428&bih=933&tbm=isch&tbnid=3bqqeUAwteODEM%3a&imgrefurl=http://www.androidapps-home.com/quickmark-barcode-scanner-android-6963.html&docid=Nbr4x3pvKwmdGM&imgurl=http://ssl.gstatic.com/android/market/tw.com.quickmark/ss-320-1-7&w=320&h=480&ei=7G7XT6L5DOms8AGi_vyNBQ&zoom=1&iact=hc&vpx=181&vpy=175&dur=953&hovh=275&hovw=183&tx=100&ty=130&sig=106342795571774308654&page=1&tbnh=154&tbnw=104&start=0&ndsp=38&ved=1t:429,r:0,s:0,i:75)" is the most straightforward term. "Focus frame" is the best colloquial phrase from photography, given that it is often referred to as an "AF (autofocus) Frame" or "focus frame" in camera manuals and discussions. There is some reference to "focus area," which is also descriptive and easy to understand: 1. <http://qrganize.com/features.php> 2. <http://www.butkus.org/chinon/chinon/cp-9af/cp-9af.htm> 3. <http://forums.dpreview.com/forums/readflat.asp?forum=1020&message=41383138&changemode=1> 4. <http://www.sds.com/mug/9xi_vfdr.html> 5. <http://www.scoop.it/t/fuji-x-pro1/p/1758069851/do-you-read-the-manual-tip-3-focus-frame-to-center-fujifilm-digital-camera-x-pro1-owner-s-manual> 6. <http://www.scoop.it/t/fuji-x-pro1/p/1884969260/do-you-read-the-manual-tip-7-corrected-af-frame-fujifilm-digital-camera-x-pro1-owner-s-manual> 7. <http://www.sds.com/mug/700si-inf3.html> 8. <http://www.sds.com/mug/9xi_vfdr.html> **Technical: *Reticle* or *Crosshairs*** [Reticle](http://en.wikipedia.org/wiki/Reticle) (or "crosshairs") is a term originating with telescopes, microscopes, and oscilloscopes, to name a few. Because scopes are round, "reticle" generally implies a circular view with cross hairs. However, the term is technically accurate when describing focus areas in cameras (credit goes to @mawcsco for finding the reference): <http://www.reticles.com/reticles_kr900.htm>. Here's another interesting reference: <http://www.techniquip.com/manuals/DCG-200MManual_r3.pdf>. **Alternative Colloquial: *Crosshair Box*** Although I believe the above terms to be more generally understandable in reference to cameras, scanners and similar apps, the term "crosshair box" does show up colloquially as a [reference to the "pick box"](http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair%20box&x=0&y=0) in AutoDesk's product AutoCAD, for virtual cameras in gaming environments, and in one found reference to the reticle on a telescope: 1. <http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair+box&x=0&y=0> 2. <http://www.garagegames.com/community/forums/viewthread/48233> 3. <http://www.astropix.com/HTML/I_ASTROP/TRACKED/MANUAL.HTM> 4. <http://community.bistudio.com/wiki/Camera.sqs> **iOS Term: *Focus Indicator*** Apple uses a similar element called the "[focus indicator](http://developer.apple.com/library/ios/#DOCUMENTATION/AudioVideo/Conceptual/CameraAndPhotoLib_TopicsForIOS/Articles/TakingPicturesAndMovies.html)" in the camera app, however this square moves to indicate where the focus is, rather than form a fixed frame in the viewfinder. **Other Camera Terms** Cameras use "viewfinders," for the entire viewable area, "[bright line frame](http://www.butkus.org/chinon/chinon/intrafocus_35f-ma/body09.jpg)" and "[frame finder](http://www.mir.com.my/rb/photography/companies/nikon/nikkoresources/RF-Nikkor/RF-Accessories/Nikon-RF-Finders/KelSportFrame_3.jpg)" for the area inside the viewfinder.
I've written a number of QR code-reading apps, and have always called it a "reticle" in my code, because (son of a photographer here) I was always taught that *any* lines, grid, crosshair, or indicia overlaid on a view (like a viewfinder in a camera) were *all* called reticles. Hence, it's a general term: a crosshair overlaid on a view is *also* a kind of reticle. I can see why it's not such a good user-facing term however, as it's not a simple, common English descriptive term. So for user-facing purposes, I'd go with Apple's usage and call it the "Focus Area," even if it's not literally used for focusing the lens— the point is it's directing the user where to put the focus of their attention.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
I think the best term *is* "reticle." Businesses that make the glass used in cameras call them reticles. See the images on this site: <http://www.reticles.com/reticles_kr900.htm>.
According to [ehow](http://www.ehow.com/how_8488499_read-qr-codes-iphone.html) it is called a reticle. But I usually just hear it called the QR reader.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
Well going to the actual source of QR codes - the company who invented them ([Denso Corporation](http://en.wikipedia.org/wiki/Denso)) don't seem to have given that a particular name at all. The products that they sell refer to that roughly in equal measure as the '[Reading Area](http://www.denso-adc.com/products/gt15)' or the '[Scanning Area](http://www.denso-wave.com/en/adcd/product/qrcode/handy_terminal/bht-800q.html)'. Even the actual patent for QR codes: ([Optically readable two-dimensional code and method and apparatus using the same](http://worldwide.espacenet.com/publicationDetails/originalDocument?CC=US&NR=5726435A&KC=A&FT=D&ND=7&date=19980310&DB=EPODOC&locale=en_EP)) doesn't detail the actual guide lines, only going as far as to state that it is an 'image pickup device'. You could *possibly* refer to it as a 'CCD Area', as a CCD (Charge-Coupled Device) is the type of image sensor that QR codes use (see this patent: [Optical information reading apparatus](http://www.freepatentsonline.com/y2006/0054844.html) - also from Denso) but that's not really the most intuitive term. So basically, it seems like the specific term is still up-for-grabs. Reticule, 'Reading Area' or 'Guidelines' or whatever makes the most sense to the user really.
I've written a number of QR code-reading apps, and have always called it a "reticle" in my code, because (son of a photographer here) I was always taught that *any* lines, grid, crosshair, or indicia overlaid on a view (like a viewfinder in a camera) were *all* called reticles. Hence, it's a general term: a crosshair overlaid on a view is *also* a kind of reticle. I can see why it's not such a good user-facing term however, as it's not a simple, common English descriptive term. So for user-facing purposes, I'd go with Apple's usage and call it the "Focus Area," even if it's not literally used for focusing the lens— the point is it's directing the user where to put the focus of their attention.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
**Colloquial: *Target Area,* \*Focus Area,\* or *Focus Frame*** It looks like "[target area](http://www.google.com/imgres?hl=en&biw=1428&bih=933&tbm=isch&tbnid=3bqqeUAwteODEM%3a&imgrefurl=http://www.androidapps-home.com/quickmark-barcode-scanner-android-6963.html&docid=Nbr4x3pvKwmdGM&imgurl=http://ssl.gstatic.com/android/market/tw.com.quickmark/ss-320-1-7&w=320&h=480&ei=7G7XT6L5DOms8AGi_vyNBQ&zoom=1&iact=hc&vpx=181&vpy=175&dur=953&hovh=275&hovw=183&tx=100&ty=130&sig=106342795571774308654&page=1&tbnh=154&tbnw=104&start=0&ndsp=38&ved=1t:429,r:0,s:0,i:75)" is the most straightforward term. "Focus frame" is the best colloquial phrase from photography, given that it is often referred to as an "AF (autofocus) Frame" or "focus frame" in camera manuals and discussions. There is some reference to "focus area," which is also descriptive and easy to understand: 1. <http://qrganize.com/features.php> 2. <http://www.butkus.org/chinon/chinon/cp-9af/cp-9af.htm> 3. <http://forums.dpreview.com/forums/readflat.asp?forum=1020&message=41383138&changemode=1> 4. <http://www.sds.com/mug/9xi_vfdr.html> 5. <http://www.scoop.it/t/fuji-x-pro1/p/1758069851/do-you-read-the-manual-tip-3-focus-frame-to-center-fujifilm-digital-camera-x-pro1-owner-s-manual> 6. <http://www.scoop.it/t/fuji-x-pro1/p/1884969260/do-you-read-the-manual-tip-7-corrected-af-frame-fujifilm-digital-camera-x-pro1-owner-s-manual> 7. <http://www.sds.com/mug/700si-inf3.html> 8. <http://www.sds.com/mug/9xi_vfdr.html> **Technical: *Reticle* or *Crosshairs*** [Reticle](http://en.wikipedia.org/wiki/Reticle) (or "crosshairs") is a term originating with telescopes, microscopes, and oscilloscopes, to name a few. Because scopes are round, "reticle" generally implies a circular view with cross hairs. However, the term is technically accurate when describing focus areas in cameras (credit goes to @mawcsco for finding the reference): <http://www.reticles.com/reticles_kr900.htm>. Here's another interesting reference: <http://www.techniquip.com/manuals/DCG-200MManual_r3.pdf>. **Alternative Colloquial: *Crosshair Box*** Although I believe the above terms to be more generally understandable in reference to cameras, scanners and similar apps, the term "crosshair box" does show up colloquially as a [reference to the "pick box"](http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair%20box&x=0&y=0) in AutoDesk's product AutoCAD, for virtual cameras in gaming environments, and in one found reference to the reticle on a telescope: 1. <http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair+box&x=0&y=0> 2. <http://www.garagegames.com/community/forums/viewthread/48233> 3. <http://www.astropix.com/HTML/I_ASTROP/TRACKED/MANUAL.HTM> 4. <http://community.bistudio.com/wiki/Camera.sqs> **iOS Term: *Focus Indicator*** Apple uses a similar element called the "[focus indicator](http://developer.apple.com/library/ios/#DOCUMENTATION/AudioVideo/Conceptual/CameraAndPhotoLib_TopicsForIOS/Articles/TakingPicturesAndMovies.html)" in the camera app, however this square moves to indicate where the focus is, rather than form a fixed frame in the viewfinder. **Other Camera Terms** Cameras use "viewfinders," for the entire viewable area, "[bright line frame](http://www.butkus.org/chinon/chinon/intrafocus_35f-ma/body09.jpg)" and "[frame finder](http://www.mir.com.my/rb/photography/companies/nikon/nikkoresources/RF-Nikkor/RF-Accessories/Nikon-RF-Finders/KelSportFrame_3.jpg)" for the area inside the viewfinder.
Well going to the actual source of QR codes - the company who invented them ([Denso Corporation](http://en.wikipedia.org/wiki/Denso)) don't seem to have given that a particular name at all. The products that they sell refer to that roughly in equal measure as the '[Reading Area](http://www.denso-adc.com/products/gt15)' or the '[Scanning Area](http://www.denso-wave.com/en/adcd/product/qrcode/handy_terminal/bht-800q.html)'. Even the actual patent for QR codes: ([Optically readable two-dimensional code and method and apparatus using the same](http://worldwide.espacenet.com/publicationDetails/originalDocument?CC=US&NR=5726435A&KC=A&FT=D&ND=7&date=19980310&DB=EPODOC&locale=en_EP)) doesn't detail the actual guide lines, only going as far as to state that it is an 'image pickup device'. You could *possibly* refer to it as a 'CCD Area', as a CCD (Charge-Coupled Device) is the type of image sensor that QR codes use (see this patent: [Optical information reading apparatus](http://www.freepatentsonline.com/y2006/0054844.html) - also from Denso) but that's not really the most intuitive term. So basically, it seems like the specific term is still up-for-grabs. Reticule, 'Reading Area' or 'Guidelines' or whatever makes the most sense to the user really.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
**Colloquial: *Target Area,* \*Focus Area,\* or *Focus Frame*** It looks like "[target area](http://www.google.com/imgres?hl=en&biw=1428&bih=933&tbm=isch&tbnid=3bqqeUAwteODEM%3a&imgrefurl=http://www.androidapps-home.com/quickmark-barcode-scanner-android-6963.html&docid=Nbr4x3pvKwmdGM&imgurl=http://ssl.gstatic.com/android/market/tw.com.quickmark/ss-320-1-7&w=320&h=480&ei=7G7XT6L5DOms8AGi_vyNBQ&zoom=1&iact=hc&vpx=181&vpy=175&dur=953&hovh=275&hovw=183&tx=100&ty=130&sig=106342795571774308654&page=1&tbnh=154&tbnw=104&start=0&ndsp=38&ved=1t:429,r:0,s:0,i:75)" is the most straightforward term. "Focus frame" is the best colloquial phrase from photography, given that it is often referred to as an "AF (autofocus) Frame" or "focus frame" in camera manuals and discussions. There is some reference to "focus area," which is also descriptive and easy to understand: 1. <http://qrganize.com/features.php> 2. <http://www.butkus.org/chinon/chinon/cp-9af/cp-9af.htm> 3. <http://forums.dpreview.com/forums/readflat.asp?forum=1020&message=41383138&changemode=1> 4. <http://www.sds.com/mug/9xi_vfdr.html> 5. <http://www.scoop.it/t/fuji-x-pro1/p/1758069851/do-you-read-the-manual-tip-3-focus-frame-to-center-fujifilm-digital-camera-x-pro1-owner-s-manual> 6. <http://www.scoop.it/t/fuji-x-pro1/p/1884969260/do-you-read-the-manual-tip-7-corrected-af-frame-fujifilm-digital-camera-x-pro1-owner-s-manual> 7. <http://www.sds.com/mug/700si-inf3.html> 8. <http://www.sds.com/mug/9xi_vfdr.html> **Technical: *Reticle* or *Crosshairs*** [Reticle](http://en.wikipedia.org/wiki/Reticle) (or "crosshairs") is a term originating with telescopes, microscopes, and oscilloscopes, to name a few. Because scopes are round, "reticle" generally implies a circular view with cross hairs. However, the term is technically accurate when describing focus areas in cameras (credit goes to @mawcsco for finding the reference): <http://www.reticles.com/reticles_kr900.htm>. Here's another interesting reference: <http://www.techniquip.com/manuals/DCG-200MManual_r3.pdf>. **Alternative Colloquial: *Crosshair Box*** Although I believe the above terms to be more generally understandable in reference to cameras, scanners and similar apps, the term "crosshair box" does show up colloquially as a [reference to the "pick box"](http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair%20box&x=0&y=0) in AutoDesk's product AutoCAD, for virtual cameras in gaming environments, and in one found reference to the reticle on a telescope: 1. <http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair+box&x=0&y=0> 2. <http://www.garagegames.com/community/forums/viewthread/48233> 3. <http://www.astropix.com/HTML/I_ASTROP/TRACKED/MANUAL.HTM> 4. <http://community.bistudio.com/wiki/Camera.sqs> **iOS Term: *Focus Indicator*** Apple uses a similar element called the "[focus indicator](http://developer.apple.com/library/ios/#DOCUMENTATION/AudioVideo/Conceptual/CameraAndPhotoLib_TopicsForIOS/Articles/TakingPicturesAndMovies.html)" in the camera app, however this square moves to indicate where the focus is, rather than form a fixed frame in the viewfinder. **Other Camera Terms** Cameras use "viewfinders," for the entire viewable area, "[bright line frame](http://www.butkus.org/chinon/chinon/intrafocus_35f-ma/body09.jpg)" and "[frame finder](http://www.mir.com.my/rb/photography/companies/nikon/nikkoresources/RF-Nikkor/RF-Accessories/Nikon-RF-Finders/KelSportFrame_3.jpg)" for the area inside the viewfinder.
According to [ehow](http://www.ehow.com/how_8488499_read-qr-codes-iphone.html) it is called a reticle. But I usually just hear it called the QR reader.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
**Colloquial: *Target Area,* \*Focus Area,\* or *Focus Frame*** It looks like "[target area](http://www.google.com/imgres?hl=en&biw=1428&bih=933&tbm=isch&tbnid=3bqqeUAwteODEM%3a&imgrefurl=http://www.androidapps-home.com/quickmark-barcode-scanner-android-6963.html&docid=Nbr4x3pvKwmdGM&imgurl=http://ssl.gstatic.com/android/market/tw.com.quickmark/ss-320-1-7&w=320&h=480&ei=7G7XT6L5DOms8AGi_vyNBQ&zoom=1&iact=hc&vpx=181&vpy=175&dur=953&hovh=275&hovw=183&tx=100&ty=130&sig=106342795571774308654&page=1&tbnh=154&tbnw=104&start=0&ndsp=38&ved=1t:429,r:0,s:0,i:75)" is the most straightforward term. "Focus frame" is the best colloquial phrase from photography, given that it is often referred to as an "AF (autofocus) Frame" or "focus frame" in camera manuals and discussions. There is some reference to "focus area," which is also descriptive and easy to understand: 1. <http://qrganize.com/features.php> 2. <http://www.butkus.org/chinon/chinon/cp-9af/cp-9af.htm> 3. <http://forums.dpreview.com/forums/readflat.asp?forum=1020&message=41383138&changemode=1> 4. <http://www.sds.com/mug/9xi_vfdr.html> 5. <http://www.scoop.it/t/fuji-x-pro1/p/1758069851/do-you-read-the-manual-tip-3-focus-frame-to-center-fujifilm-digital-camera-x-pro1-owner-s-manual> 6. <http://www.scoop.it/t/fuji-x-pro1/p/1884969260/do-you-read-the-manual-tip-7-corrected-af-frame-fujifilm-digital-camera-x-pro1-owner-s-manual> 7. <http://www.sds.com/mug/700si-inf3.html> 8. <http://www.sds.com/mug/9xi_vfdr.html> **Technical: *Reticle* or *Crosshairs*** [Reticle](http://en.wikipedia.org/wiki/Reticle) (or "crosshairs") is a term originating with telescopes, microscopes, and oscilloscopes, to name a few. Because scopes are round, "reticle" generally implies a circular view with cross hairs. However, the term is technically accurate when describing focus areas in cameras (credit goes to @mawcsco for finding the reference): <http://www.reticles.com/reticles_kr900.htm>. Here's another interesting reference: <http://www.techniquip.com/manuals/DCG-200MManual_r3.pdf>. **Alternative Colloquial: *Crosshair Box*** Although I believe the above terms to be more generally understandable in reference to cameras, scanners and similar apps, the term "crosshair box" does show up colloquially as a [reference to the "pick box"](http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair%20box&x=0&y=0) in AutoDesk's product AutoCAD, for virtual cameras in gaming environments, and in one found reference to the reticle on a telescope: 1. <http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair+box&x=0&y=0> 2. <http://www.garagegames.com/community/forums/viewthread/48233> 3. <http://www.astropix.com/HTML/I_ASTROP/TRACKED/MANUAL.HTM> 4. <http://community.bistudio.com/wiki/Camera.sqs> **iOS Term: *Focus Indicator*** Apple uses a similar element called the "[focus indicator](http://developer.apple.com/library/ios/#DOCUMENTATION/AudioVideo/Conceptual/CameraAndPhotoLib_TopicsForIOS/Articles/TakingPicturesAndMovies.html)" in the camera app, however this square moves to indicate where the focus is, rather than form a fixed frame in the viewfinder. **Other Camera Terms** Cameras use "viewfinders," for the entire viewable area, "[bright line frame](http://www.butkus.org/chinon/chinon/intrafocus_35f-ma/body09.jpg)" and "[frame finder](http://www.mir.com.my/rb/photography/companies/nikon/nikkoresources/RF-Nikkor/RF-Accessories/Nikon-RF-Finders/KelSportFrame_3.jpg)" for the area inside the viewfinder.
Cross hairs are meant for aiming (centering) and are not usually interactive. The rectangular visualization's primary purpose is not centering of focus, but selecting the relevant part of the image for scanning. Theoretically user can change both size and location in the screen, therefore this is not a common cross hair. The rectangular visualization enables the user to see and modify the "region of interest". (See definition of "region of interest" or ROI here [[Wikipedia]](http://en.wikipedia.org/wiki/Region_of_interest), [[Mathworks]](http://www.mathworks.com/help/toolbox/images/f19-13234.html), [[Wolfram]](http://library.wolfram.com/examples/roi/)). I found that this rectange is refered to as ["**viewfinder box**"](http://acer-tr.custhelp.com/app/answers/detail/a_id/16483/~/how-to-install-a-printer-with-acer-print), ["**viewfinder rectange**"](http://areacellphone.com/2010/05/howto-download-install-android-apps-using-qr-codes/), ["**viewfinder area**"](http://www.quickmark.cn/en/Info/android.asp), ["**crosshair box**"](http://www.cadtutor.net/forum/archive/index.php/t-17689.html) (or ["annoying yellow box around crosshair"](http://forums.steampowered.com/forums/showthread.php?t=1718837) in non-QR usage), however a more correct term (which is commonly used in image processing) would be "**region of interest**". Relevent queries: [viewfinder box](https://www.google.com/search?q=%22viewfinder+box%22+qr&hl=en&tbm=isch) [viewfinder rectangle](https://www.google.com/search?q=%22viewfinder+rectangle%22+qr&hl=en&tbm=isch) [viewfinder area](https://www.google.com/search?q=%22viewfinder+area%22+qr&hl=en&tbm=isch)
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
**Colloquial: *Target Area,* \*Focus Area,\* or *Focus Frame*** It looks like "[target area](http://www.google.com/imgres?hl=en&biw=1428&bih=933&tbm=isch&tbnid=3bqqeUAwteODEM%3a&imgrefurl=http://www.androidapps-home.com/quickmark-barcode-scanner-android-6963.html&docid=Nbr4x3pvKwmdGM&imgurl=http://ssl.gstatic.com/android/market/tw.com.quickmark/ss-320-1-7&w=320&h=480&ei=7G7XT6L5DOms8AGi_vyNBQ&zoom=1&iact=hc&vpx=181&vpy=175&dur=953&hovh=275&hovw=183&tx=100&ty=130&sig=106342795571774308654&page=1&tbnh=154&tbnw=104&start=0&ndsp=38&ved=1t:429,r:0,s:0,i:75)" is the most straightforward term. "Focus frame" is the best colloquial phrase from photography, given that it is often referred to as an "AF (autofocus) Frame" or "focus frame" in camera manuals and discussions. There is some reference to "focus area," which is also descriptive and easy to understand: 1. <http://qrganize.com/features.php> 2. <http://www.butkus.org/chinon/chinon/cp-9af/cp-9af.htm> 3. <http://forums.dpreview.com/forums/readflat.asp?forum=1020&message=41383138&changemode=1> 4. <http://www.sds.com/mug/9xi_vfdr.html> 5. <http://www.scoop.it/t/fuji-x-pro1/p/1758069851/do-you-read-the-manual-tip-3-focus-frame-to-center-fujifilm-digital-camera-x-pro1-owner-s-manual> 6. <http://www.scoop.it/t/fuji-x-pro1/p/1884969260/do-you-read-the-manual-tip-7-corrected-af-frame-fujifilm-digital-camera-x-pro1-owner-s-manual> 7. <http://www.sds.com/mug/700si-inf3.html> 8. <http://www.sds.com/mug/9xi_vfdr.html> **Technical: *Reticle* or *Crosshairs*** [Reticle](http://en.wikipedia.org/wiki/Reticle) (or "crosshairs") is a term originating with telescopes, microscopes, and oscilloscopes, to name a few. Because scopes are round, "reticle" generally implies a circular view with cross hairs. However, the term is technically accurate when describing focus areas in cameras (credit goes to @mawcsco for finding the reference): <http://www.reticles.com/reticles_kr900.htm>. Here's another interesting reference: <http://www.techniquip.com/manuals/DCG-200MManual_r3.pdf>. **Alternative Colloquial: *Crosshair Box*** Although I believe the above terms to be more generally understandable in reference to cameras, scanners and similar apps, the term "crosshair box" does show up colloquially as a [reference to the "pick box"](http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair%20box&x=0&y=0) in AutoDesk's product AutoCAD, for virtual cameras in gaming environments, and in one found reference to the reticle on a telescope: 1. <http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair+box&x=0&y=0> 2. <http://www.garagegames.com/community/forums/viewthread/48233> 3. <http://www.astropix.com/HTML/I_ASTROP/TRACKED/MANUAL.HTM> 4. <http://community.bistudio.com/wiki/Camera.sqs> **iOS Term: *Focus Indicator*** Apple uses a similar element called the "[focus indicator](http://developer.apple.com/library/ios/#DOCUMENTATION/AudioVideo/Conceptual/CameraAndPhotoLib_TopicsForIOS/Articles/TakingPicturesAndMovies.html)" in the camera app, however this square moves to indicate where the focus is, rather than form a fixed frame in the viewfinder. **Other Camera Terms** Cameras use "viewfinders," for the entire viewable area, "[bright line frame](http://www.butkus.org/chinon/chinon/intrafocus_35f-ma/body09.jpg)" and "[frame finder](http://www.mir.com.my/rb/photography/companies/nikon/nikkoresources/RF-Nikkor/RF-Accessories/Nikon-RF-Finders/KelSportFrame_3.jpg)" for the area inside the viewfinder.
I think the best term *is* "reticle." Businesses that make the glass used in cameras call them reticles. See the images on this site: <http://www.reticles.com/reticles_kr900.htm>.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
Well going to the actual source of QR codes - the company who invented them ([Denso Corporation](http://en.wikipedia.org/wiki/Denso)) don't seem to have given that a particular name at all. The products that they sell refer to that roughly in equal measure as the '[Reading Area](http://www.denso-adc.com/products/gt15)' or the '[Scanning Area](http://www.denso-wave.com/en/adcd/product/qrcode/handy_terminal/bht-800q.html)'. Even the actual patent for QR codes: ([Optically readable two-dimensional code and method and apparatus using the same](http://worldwide.espacenet.com/publicationDetails/originalDocument?CC=US&NR=5726435A&KC=A&FT=D&ND=7&date=19980310&DB=EPODOC&locale=en_EP)) doesn't detail the actual guide lines, only going as far as to state that it is an 'image pickup device'. You could *possibly* refer to it as a 'CCD Area', as a CCD (Charge-Coupled Device) is the type of image sensor that QR codes use (see this patent: [Optical information reading apparatus](http://www.freepatentsonline.com/y2006/0054844.html) - also from Denso) but that's not really the most intuitive term. So basically, it seems like the specific term is still up-for-grabs. Reticule, 'Reading Area' or 'Guidelines' or whatever makes the most sense to the user really.
Cross hairs are meant for aiming (centering) and are not usually interactive. The rectangular visualization's primary purpose is not centering of focus, but selecting the relevant part of the image for scanning. Theoretically user can change both size and location in the screen, therefore this is not a common cross hair. The rectangular visualization enables the user to see and modify the "region of interest". (See definition of "region of interest" or ROI here [[Wikipedia]](http://en.wikipedia.org/wiki/Region_of_interest), [[Mathworks]](http://www.mathworks.com/help/toolbox/images/f19-13234.html), [[Wolfram]](http://library.wolfram.com/examples/roi/)). I found that this rectange is refered to as ["**viewfinder box**"](http://acer-tr.custhelp.com/app/answers/detail/a_id/16483/~/how-to-install-a-printer-with-acer-print), ["**viewfinder rectange**"](http://areacellphone.com/2010/05/howto-download-install-android-apps-using-qr-codes/), ["**viewfinder area**"](http://www.quickmark.cn/en/Info/android.asp), ["**crosshair box**"](http://www.cadtutor.net/forum/archive/index.php/t-17689.html) (or ["annoying yellow box around crosshair"](http://forums.steampowered.com/forums/showthread.php?t=1718837) in non-QR usage), however a more correct term (which is commonly used in image processing) would be "**region of interest**". Relevent queries: [viewfinder box](https://www.google.com/search?q=%22viewfinder+box%22+qr&hl=en&tbm=isch) [viewfinder rectangle](https://www.google.com/search?q=%22viewfinder+rectangle%22+qr&hl=en&tbm=isch) [viewfinder area](https://www.google.com/search?q=%22viewfinder+area%22+qr&hl=en&tbm=isch)
32,710,883
When I try to debug my app in Android Studio I get a gradle error. I have now idea how I can fix it. Does anyone have any ideas or fixes for me so I can continue debugging my app. I googled it already and people are saying the cause could be that there are duplicate imports in the gradle file but I checked this and there are none. When I rebuilt gradle it is successful but when I debug I get this error. ``` Executing tasks: [:app:assembleDebug] Configuration on demand is an incubating feature. :app:preBuild :app:compileDebugNdk UP-TO-DATE :app:preDebugBuild :app:checkDebugManifest :app:preReleaseBuild :app:prepareComAndroidSupportAppcompatV72220Library UP-TO-DATE :app:prepareComAndroidSupportDesign2220Library UP-TO-DATE :app:prepareComAndroidSupportMediarouterV72200Library UP-TO-DATE :app:prepareComAndroidSupportRecyclerviewV72100Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42221Library UP-TO-DATE :app:prepareComBalysvMaterialmenuMaterialMenu154Library UP-TO-DATE :app:prepareComFacebookAndroidFacebookAndroidSdk460Library UP-TO-DATE :app:prepareComGithubJohnkilAndroidRobototextviewRobototextview240Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServices750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAds750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAnalytics750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppindexing750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppinvite750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppstate750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBase750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesCast750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesDrive750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesFitness750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGames750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGcm750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesIdentity750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesLocation750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesMaps750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesNearby750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPanorama750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPlus750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesSafetynet750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWallet750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWearable750Library UP-TO-DATE :app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig UP-TO-DATE :app:generateDebugAssets UP-TO-DATE :app:mergeDebugAssets UP-TO-DATE :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources UP-TO-DATE :app:processDebugManifest UP-TO-DATE :app:processDebugResources UP-TO-DATE :app:generateDebugSources UP-TO-DATE :app:compileDebugJava UP-TO-DATE :app:preDexDebug UP-TO-DATE :app:dexDebug UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536 at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502) at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277) at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168) at com.android.dx.merge.DexMerger.merge(DexMerger.java:189) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303) at com.android.dx.command.dexer.Main.run(Main.java:246) at com.android.dx.command.dexer.Main.main(Main.java:215) at com.android.dx.command.Main.main(Main.java:106) FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:dexDebug'. > com.android.ide.common.internal.LoggedErrorException: Failed to run command: /Users/x/Development/Android SDK/build-tools/21.1.2/dx --dex --no-optimize --output /Users/app/app/build/intermediates/dex/debug --input-list=/Users/app/app/build/intermediates/tmp/dex/debug/inputList.txt Error Code: 2 Output: UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536 at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502) at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277) at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168) at com.android.dx.merge.DexMerger.merge(DexMerger.java:189) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303) at com.android.dx.command.dexer.Main.run(Main.java:246) at com.android.dx.command.dexer.Main.main(Main.java:215) at com.android.dx.command.Main.main(Main.java:106) * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 42.045 secs ``` My build.gradle: ``` apply plugin: 'com.android.application' apply plugin: 'android-apt' def AAVersion = '3.3.2' def JacksonVersion = '2.5.2' apt { arguments { androidManifestFile variant.outputs[0].processResources.manifestFile // androidManifestFile variant.outputs[0].processResources.manifestFile // if you have multiple outputs (when using splits), you may want to have other index than 0 // you should set your package name here if you are using different application IDs resourcePackageName "com.app" // You can set optional annotation processing options here, like these commented options: // logLevel 'INFO' // logFile '/var/log/aa.log' } } android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.app" minSdkVersion 15 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/NOTICE' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/spring.handlers' exclude 'META-INF/spring.schemas' exclude 'META-INF/spring.tooling' } } repositories { mavenCentral() mavenLocal() maven { url 'http://repo.spring.io/milestone' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.0' compile 'com.android.support:recyclerview-v7:21.0.0' compile 'com.android.support:design:22.2.0' compile( [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: "$JacksonVersion"], [group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: "$JacksonVersion"], [group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: "$JacksonVersion"] ) apt "org.androidannotations:androidannotations:$AAVersion" compile "org.androidannotations:androidannotations-api:$AAVersion" compile "org.springframework.android:spring-android-rest-template:2.0.0.M2" compile "com.squareup.okhttp:okhttp:2.4.0" compile "com.squareup.okhttp:okhttp-urlconnection:2.4.0" compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.readystatesoftware.systembartint:systembartint:1.0.3' compile 'com.github.johnkil.android-robototextview:robototextview:2.4.0' compile 'com.balysv.materialmenu:material-menu:1.5.4' compile 'com.j256.ormlite:ormlite-android:4.48' compile 'com.facebook.android:facebook-android-sdk:4.6.0' compile 'com.google.android.gms:play-services:7.5.0' } ```
2015/09/22
[ "https://Stackoverflow.com/questions/32710883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841903/" ]
Try this : ``` $str = '1.8 to 250'; preg_match_all('!\d+!', $str, $matches); print_r($matches); ``` From this post [Extract numbers from a string](https://stackoverflow.com/questions/6278296/extract-numbers-from-a-string)
Try this: ``` $str = '1.8 to 250'; $string = explode(" ",$str); //print_r($string); for($i = 0;$i < count($string);$i++){ if(is_numeric($string[$i])){ print "\n $string[$i]"; } } ```
49,761,972
Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways. ``` // with a String Literal Type type MyKeyType = 'foo' | 'bar' | 'baz'; // or with a String Enum enum MyKeyType { FOO = 'foo', BAR = 'bar', BAZ = 'baz' } ``` I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check). The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases.
2018/04/10
[ "https://Stackoverflow.com/questions/49761972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6191996/" ]
The key thing to understand is that *the values of string enums are opaque*. The intended use case for a string enum is that you don't want other code to know or care what the literal string backing `MyKeyType.FOO` is. This means that you won't be able to, say, pass the *literal string* `"bar"` to a function accepting a `MyKeyType` -- you'll have to write `MyKeyType.BAR` instead.
One benefit for an enum at development time is that you will see the list of options easily via intellisense: [![enter image description here](https://i.stack.imgur.com/X3IJr.png)](https://i.stack.imgur.com/X3IJr.png) Similarly, you could change an enum value easily using refactoring tools, instead of changing a string everywhere. Edit: In VS 2017 and TypeScript >=3.2.4, intellisense works with string literal types: [![enter image description here](https://i.stack.imgur.com/ZeRsx.png)](https://i.stack.imgur.com/ZeRsx.png)
49,761,972
Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways. ``` // with a String Literal Type type MyKeyType = 'foo' | 'bar' | 'baz'; // or with a String Enum enum MyKeyType { FOO = 'foo', BAR = 'bar', BAZ = 'baz' } ``` I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check). The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases.
2018/04/10
[ "https://Stackoverflow.com/questions/49761972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6191996/" ]
The key thing to understand is that *the values of string enums are opaque*. The intended use case for a string enum is that you don't want other code to know or care what the literal string backing `MyKeyType.FOO` is. This means that you won't be able to, say, pass the *literal string* `"bar"` to a function accepting a `MyKeyType` -- you'll have to write `MyKeyType.BAR` instead.
Well, there is a **difference** between string enums and literal types in the transpiled code. Compare the **Typescript** Code ``` // with a String Literal Type type MyKeyType1 = 'foo' | 'bar' | 'baz'; // or with a String Enum enum MyKeyType2 { FOO = 'foo', BAR = 'bar', BAZ = 'baz' } ``` With the **transpiled JavaScript** Code ``` // or with a String Enum var MyKeyType2; (function (MyKeyType2) { MyKeyType2["FOO"] = "foo"; MyKeyType2["BAR"] = "bar"; MyKeyType2["BAZ"] = "baz"; })(MyKeyType2 || (MyKeyType2 = {})); ``` What you can see is, there is no generated code for the string literal. Because Typescripts Transpiler is only using for type safety while transpiling. At runtime string literals are "generated to dumb" strings. No references between the definition of the literal and the usages. So there is a third alternative called **const enum** Look at this ``` // with a String Literal Type type MyKeyType1 = 'foo' | 'bar' | 'baz'; // or with a String Enum enum MyKeyType2 { FOO = 'foo', BAR = 'bar', BAZ = 'baz' } // or with a Const String Enum const enum MyKeyType3 { FOO = 'foo', BAR = 'bar', BAZ = 'baz' } var a : MyKeyType1 = "bar" var b: MyKeyType2 = MyKeyType2.BAR var c: MyKeyType3 = MyKeyType3.BAR ``` will be transpiled to ``` // or with a String Enum var MyKeyType2; (function (MyKeyType2) { MyKeyType2["FOO"] = "foo"; MyKeyType2["BAR"] = "bar"; MyKeyType2["BAZ"] = "baz"; })(MyKeyType2 || (MyKeyType2 = {})); var a = "bar"; var b = MyKeyType2.BAR; var c = "bar" /* BAR */; ``` **For further playing you can check this [link](http://www.typescriptlang.org/play/index.html#src=%20%20%20%2F%2F%20with%20a%20String%20Literal%20Type%20%0D%0A%20%20%20type%20MyKeyType1%20%3D%20'foo'%20%7C%20'bar'%20%7C%20'baz'%3B%0D%0A%0D%0A%20%20%20%20%2F%2F%20or%20with%20a%20String%20Enum%20%20%20%0D%0A%20%20%20%20enum%20MyKeyType2%20%7B%0D%0A%20%20%20%20%20%20%20FOO%20%3D%20'foo'%2C%0D%0A%20%20%20%20%20%20%20BAR%20%3D%20'bar'%2C%0D%0A%20%20%20%20%20%20%20BAZ%20%3D%20'baz'%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%0D%0A%20%20%20%20%2F%2F%20or%20with%20a%20String%20Enum%20%20%20%0D%0A%20%20%20%20const%20enum%20MyKeyType3%20%7B%0D%0A%20%20%20%20%20%20%20FOO%20%3D%20'foo'%2C%0D%0A%20%20%20%20%20%20%20BAR%20%3D%20'bar'%2C%0D%0A%20%20%20%20%20%20%20BAZ%20%3D%20'baz'%0D%0A%7D%0D%0A%20%20%20%20%0D%0A%0D%0Avar%20a%20%3A%20MyKeyType1%20%3D%20%22bar%22%20%0D%0Avar%20b%3A%20MyKeyType2%20%3D%20MyKeyType2.BAR%0D%0Avar%20c%3A%20MyKeyType3%20%3D%20MyKeyType3.BAR%0D%0A%0D%0A)** I prefer the const enum case, because of the convenient way of typing Enum.Value. Typescript will do the rest for me to get the highest performance when transpiling.
49,761,972
Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways. ``` // with a String Literal Type type MyKeyType = 'foo' | 'bar' | 'baz'; // or with a String Enum enum MyKeyType { FOO = 'foo', BAR = 'bar', BAZ = 'baz' } ``` I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check). The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases.
2018/04/10
[ "https://Stackoverflow.com/questions/49761972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6191996/" ]
The key thing to understand is that *the values of string enums are opaque*. The intended use case for a string enum is that you don't want other code to know or care what the literal string backing `MyKeyType.FOO` is. This means that you won't be able to, say, pass the *literal string* `"bar"` to a function accepting a `MyKeyType` -- you'll have to write `MyKeyType.BAR` instead.
A big downside of enum is that if you use number instead of string, the entirely enum is not safety in my opinion: i can always assign any number value to a variable of this kind ``` enum TYPE {MAN = 1, WOMAN = 2, BOY = 3, GIRL = 4}; let foo: TYPE = TYPE.MAN; foo = 37.14; //no problem for compiler ```