text
stringlengths
8
267k
meta
dict
Q: is there an API for GIT (C++ or other languages) A company asked me to program a GIT wrapper for them. The people there have absolute no versioning systems experience, but it will be incorporated in their daily routine eventually (through my program). I'm planning on using VC++ to create a tiny windows applet that will help ppl in this process. Any thoughts on that? What about a Deamon process checking if people want to commit/push their files? A: There's already TortoiseGit, among other "friendly" interfaces. Don't re-invent the wheel, start by researching what's already available. A: For almost (but not all!) use cases, libgit2 is the easiest way to interact with Git repositories via code. A: Git already has two layers: The plumbing (which you may be interested in) on top of which is built the primary porcelain which provides the user interface. If you want to implement something like git-commit but with slightly different semantics all of the underlying programs like git-write-tree and git-rev-parse are there for you to build on. See also What does the term "porcelain" mean in Git? A: In order to easier the search for documentation hereafter the link to the official. It's about the plumbing and porcelain: https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain
{ "language": "en", "url": "https://stackoverflow.com/questions/7616482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: can not filter values within cakephp model I created a categories model. I also created a project model. The project model belongs to the categories model so when you create a new project, you recieve a category drop down to pick which category you want. One of the categories is "Root" and I do not want this showing in the drop down list. I created my belongsTo method like so project.php MODEL var $belongsTo = array( 'User' => array( 'className' => 'User', 'conditions' => '', 'fields' => '', 'order' => '' ), 'Category' => array( 'className' => 'Category', 'conditions' => array('Category.id '=>'1'), 'fields' => '', 'order' => '' ), ); For my controller I have scaffolding turned on. Here is my categories model Category model class Category extends AppModel { var $name = 'Category'; var $displayField = 'name'; var $actsAs = array('Tree'); var $validate = array( 'name' => array( 'alphanumeric' => array( 'rule' => array('alphanumeric'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'parent_id' => array( 'notempty' => array( 'rule' => array('notempty'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), 'url' => array( 'notempty' => array( 'rule' => array('notempty'), //'message' => 'Your custom message here', //'allowEmpty' => false, //'required' => false, //'last' => false, // Stop validation after this rule //'on' => 'create', // Limit validation to 'create' or 'update' operations ), ), ); var $belongsTo = array( 'ParentCategory' => array( 'className' => 'Category', 'conditions' => '', 'foreignKey' => 'parent_id', 'fields' => '', 'order' => '' ), ); } A: I assume you mean remove Root from the drop down menu cake produces with associations? In which case, try this: $categories = $this->Category->find('list', array('conditions' => array('Category.name !=' => 'Root'))); $this->set(compact('categories')); A: Use 'conditions' => array('Categories !=' =>'1'),, instead. Validation is used in the saving of data, not in finding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jqgrid saveCell issue I'm trying to get an implementation of jquery's jqgrid up and running. All is going well, except for the saveCell function I'm tryin to call. What I want my plugin to do is anytime any of the *_fee fields are edited, I want the subtotal and total fields to autoupdate as well. I've got the visual updating working using getCell and setCell, but the saveCell isn't functioning correctly. saveCell() doesn't actually pass the field data to my php script. The initial saving of the edited fee field works perfectly, but subsequent ajax request when the subtotal and total fields are autochanged is not complete. I get the id and the oper fields, but not the field I actually changed! Here is my code: $("#cust_grid").jqGrid({ url:'/ajax/grid', datatype: 'xml', mtype: 'POST', colNames:['ID','Company', 'Sales','Credits','Voids','Declines','Total Trans','Monthly Fee','Trans Fee','Misc Fee','Subtotal','Total'], colModel :[ {name:'id', index:'id', width:55, search: true}, {name:'company', index:'company', width:100, search: true}, {name:'sales', index:'sales', width:70, search: true}, {name:'credits', index:'credits', width:70, search: true}, {name:'voids', index:'voids', width:70, search: true}, {name:'declines', index:'declines', width:70, search: true}, {name:'total_trans', index:'total_trans', width:70, align:'right', search: true}, {name:'monthly_fee', index:'monthly_fee', width:90, align:'right', editable: true, search: true, formatter: 'number'}, {name:'trans_fee', index:'trans_fee', width:70, align:'right', editable: true, search: true, formatter: 'number'}, {name:'misc_fee', index:'misc_fee', width:70, align:'right', editable: true, search: true, formatter: 'number'}, {name:'subtotal', index:'subtotal', width:90, align:'right', search: true}, {name:'total', index:'total', width:90, align:'right', search: true} ], pager: '#pager', rowNum:25, rowList:[10,25,50,100], sortname: 'id', sortorder: 'asc', viewrecords: true, gridview: true, caption: 'Our Customers', height: 600, altRows: true, cellEdit: true, cellsubmit: "remote", cellurl: "/ajax/editCell", afterSaveCell: function (rowid, cellname, value, iRow, iCol) { var transFee = $('#cust_grid').jqGrid('getCell', rowid, 'trans_fee'); var totalTrans = $('#cust_grid').jqGrid('getCell', rowid, 'total_trans'); var subtotal = transFee * totalTrans; subtotal = subtotal.toFixed(2); //alert(subtotal); var monthlyFee = $('#cust_grid').jqGrid('getCell', rowid, 'monthly_fee'); //alert(monthlyFee); var total = Number(subtotal) + Number(monthlyFee); //alert(total); total = total.toFixed(2); $('#cust_grid').jqGrid('setCell', rowid, 'subtotal', subtotal); alert("iRow=" + iRow + " iCol=" + iCol); $('#cust_grid').jqGrid('saveCell', iRow, 10); alert("cell saved!"); $('#cust_grid').jqGrid('setCell', rowid, 'total', total); $('#cust_grid').jqGrid('saveCell', iRow, 11); } }); $("#cust_grid").jqGrid('navGrid','#pager', {edit:false,add:false,del:false,search:true},{},{},{}, { closeAfterSearch:true, closeOnEscape:true, }, {} ); }); The first ajax request contains: Array ( [trans_fee] => 15.13 [id] => 1 [oper] => edit ) But the subsequent ajax request only contains: Array ( [id] => 1 [oper] => edit ) Because the subsequent ajax request don't contain the actual changed field data, I can't save it! Does anyone have tips with this? Thanks! A: I think there are misunderstanding what saveCell method do. It works only together with editCell and can't be used just for sending of some cell to the server. After you call [editCell] the current content of the cell will be saved in the internal savedRow parameter. The input field will be created and the user are able to change the cell content. If one later call saveCell method the content of savedRow parameter will be compared with the current cell content. If there are differences then the changes will be sent to the server. So you try to use saveCell method in a wrong way. You can't send the new cell value which you changed before with respect of setCell method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework Inserting Initial Data On Rebuild I am using Entity Framework code-first with a MySQL data source. I've defined ContactType.cs as follows: public class ContactType { [Key] public int ContactTypeId { get; set; } [Required, StringLength(30)] public string DisplayName { get; set; } } My question is, after I rebuild the database, how can I have EF to insert (without SQL) some contact types into the database. Normally, the DB is rebuilt as a blank schema, but I'd like to add contact types like (Home,Mobile,Office,Fax). A: You create a custom database initializer and overwrite the Seed method public class MyContextInitializer : DropCreateDatabaseIfModelChanges<MyContext> { protected override void Seed(MyContext context) { context.ContactTypes.Add(new ContactType { DisplayName = "Home" }); context.ContactTypes.Add(new ContactType { DisplayName = "Mobile" }); context.ContactTypes.Add(new ContactType { DisplayName = "Office" }); context.ContactTypes.Add(new ContactType { DisplayName = "Fax" }); //EF will call SaveChanges itself } } Then you register this initializer for your derived context MyContext: Database.SetInitializer<MyContext>(new MyContextInitializer()); This is a static method of the Database class and should be called somewhere once at application startup. You can also put it into a static constructor of your context to make sure that the intializer is set before you create the first context instance: static MyContext() { Database.SetInitializer<MyContext>(new MyContextInitializer()); } Instead of the base initializer DropCreateDatabaseIfModelChanges<T> you can also derive from DropCreateDatabaseAlways<T> or CreateDatabaseIfNotExists<T> if that better meets your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Using iScroll prevents the keyboard from showing on my device I am using iScroll for providing iPhone style scrolling. But, when clicking on the textboxes, the keyboard does not show up. While trying to find the possible cause, I found that removing the iScroll script, makes it work normal, but in that case I miss the scrolling functionality. Is this a bug in iScroll. If yes, is there a tested work-around? Or is there any alternative for iScroll? Thanks in advance. A: At least in iScroll 4, you can add this code to enable clicking of input fields. See the demo on Form-fields in the examples folder. <script type="text/javascript"> var myScroll; function loaded() { myScroll = new iScroll('wrapper', { useTransform: false, onBeforeScrollStart: function (e) { var target = e.target; while (target.nodeType != 1) target = target.parentNode; if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') e.preventDefault(); } }); } document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false); document.addEventListener('DOMContentLoaded', loaded, false); </script> A: I was able to solve the error. The problem was with the CSS. I thought may be the CSS is somehow creating the problem. I concluded this on the basis that when I commented the CSS for wrapper and scroller, the keyboard showed up... but keeping them, the keyboard didn't work. I was using bottom: 0px;, which seemed to be somehow preventing the keyboard from showing. Removing bottom: 0px; solved my problem. Hope this helps others. A: I added the following code to _start in iScroll 4.2 to solve this problem: if (e && e.target && e.target.tagName) { var bFocusField = ('|INPUT|TEXTAREA|BUTTON|SELECT|' .indexOf('|' + e.target.tagName + '|') >= 0); if (bFocusField || that.focusField) { if (bFocusField) { that.focusField = e.target; } else { that.focusField.blur(); that.focusField = null; } e.defaultPrevented = false; e.returnValue = true; return true; } } Code is inserted below the initialization part of the function (that.moved = false; ... that.dirY = 0;). Tested it on iPad 1 (iOS 5.1) and iPad 3 (iOS 6). The onscreen keyboard does not seem to interfere with iScroll (I do an iScroll.refresh() every 5 seconds). A: I believe this solution is optimal Tweak the code in iscroll.js, ( as follows ) onBeforeScrollStart: function (e) { //e.preventDefault(); if (e.target.nodeName.toLowerCase() == "select" || e.target.tagName.toLowerCase() == 'input' || e.target.tagName.toLowerCase() == 'textarea'){ return; } },
{ "language": "en", "url": "https://stackoverflow.com/questions/7616496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there any nipype interface for avscale (FSL script)? I am trying to use nipype to analyze transformation matrixes that were created by FSL. FSL has a script called "avscale" that analyzes those transformation matrixes (*.mat files). I was wondering whether nipype has any interface that wrap that script and enable to work with its output. Thanks A: Based on the docs and the current source the answer is no. Also, avscale has also not been mentioned on the nipy-devel mailing list since at least last February. It's possible that Nipype already wraps something else that does this (perhaps with a matlab wrapper?) You could try opening an issue or asking the the mailing list. As long as you're trying to use Python (with nipype and all), maybe the philosophy of the nipype project is that you should just use numpy/scipy for this? Just a guess, I don't know the functions to replicate this output with those tools. It's also possible that no one has gotten around to adding it yet. For the uninitiated, avscale takes this affine matrix: 1.00614 -8.39414e-06 0 -0.757356 0 1.00511 -0.00317841 -0.412038 0 0.0019063 1.00735 -0.953364 0 0 0 1 and yields this or similar output: Rotation & Translation Matrix: 1.000000 0.000000 0.000000 -0.757356 0.000000 0.999998 -0.001897 -0.412038 0.000000 0.001897 0.999998 -0.953364 0.000000 0.000000 0.000000 1.000000 Scales (x,y,z) = 1.006140 1.005112 1.007354 Skews (xy,xz,yz) = -0.000008 0.000000 -0.001259 Average scaling = 1.0062 Determinant = 1.01872 Left-Right orientation: preserved Forward half transform = 1.003065 -0.000004 -0.000000 -0.378099 0.000000 1.002552 -0.001583 -0.206133 0.000000 0.000951 1.003669 -0.475711 0.000000 0.000000 0.000000 1.000000 Backward half transform = 0.996944 0.000004 0.000000 0.376944 0.000000 0.997452 0.001575 0.206357 0.000000 -0.000944 0.996343 0.473777 0.000000 0.000000 0.000000 1.000000
{ "language": "en", "url": "https://stackoverflow.com/questions/7616497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I add a method to an object instance with a variable from the current scope (Ruby)? This is hard to explain as a question but here is a code fragment: n = "Bob" class A end def A.greet puts "Hello #{n}" end A.greet This piece of code does not work because n is only evaluated inside A.greet when it is called, rather than when I add the method. Is there a way to pass the value of a local variable into A.greet? What about if n was a function? A: Use metaprogramming, specifically the define_singleton_method method. This allows you to use a block to define the method and so captures the current variables. n = "Bob" class A end A.define_singleton_method(:greet) do puts "Hello #{n}" end A.greet A: You can use a global ($n = "Bob")... A: Although I prefer Nemo157's way you can also do this: n = "Bob" class A end #Class.instance_eval "method" A.instance_eval "def greet; puts 'Hello #{n}' end" #eval Class.method eval "def A.greet2; puts 'Hi #{n}' end" A.greet A.greet2
{ "language": "en", "url": "https://stackoverflow.com/questions/7616499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SVN (TortoiseSVN / SlikSVN) - Server certificate changed: connection intercepted? I was getting this error when trying to commit changes to my repository. I could commit changes a few files at a time, but if I tried too many, the commit would fail. I thought maybe if I renewed the SSL certificate, perhaps that would help (it was going to expire in a few weeks anyway, but was currently valid). After doing this and restarting Apache, same thing. I also tried to restart the server: same thing. Then I tried to delete all of the cached certificates and credentials from Tortoise SVN and try again. This time, I can do nothing - even "svn info" reports: svn: OPTIONS of __URL__: Server certificate changed: connection interceptd? (__BASE_REPO_URL__) This from slik SVN command line, after providing the correct credentials. The only useful solution I found online (untested by me) was to checkout a new working copy, but this means I would have to merge my changes in to the fresh working copy by hand, and that's not very exciting. Any ideas? Thanks! EDIT: I am also unable to check out a new working copy. Same error as above. A: The issue is that the SVN client is caching the old server identity and doing a direct comparison of the whole certificate to see whether there's been a change. You've changed it by renewing (fair enough) but now you need to purge that local cache so that you don't compare with the old version. (Apparently, the configuration is somewhere in %USERPROFILE%\AppData\Roaming\Subversion\config but I can't personally verify this or say exactly what you're looking for in there.) A: Solved. Some time back I was having trouble with commits/checkouts when a large number of files were involved. I cannot remember all of the details (I think it had something to do with per-directory repository access), but I remember that modifying my Apache SSL configuration and turning off TLSv1 solved the issue. Evidently, that fix caused this new error which only showed up after several months and hundreds of commits, hmmm...: Caused this problem: SSLProtocol -aLL +SSLv2 +SSLv3 (no TLS!) Fixed this problem: SSLProtocol aLL Note: SSLProtocol aLL is the default ;) I don't know if this will cause the original problem to return or not, as that old access restriction is no longer necessary and has been removed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can a ksh script determine the full path to itself, when sourced from another? How can a script determine it's path when it is sourced by ksh? i.e. $ ksh ". foo.sh" I've seen very nice ways of doing this in BASH posted on stackoverflow and elsewhere but haven't yet found a ksh method. Using "$0" doesn't work. This simply refers to "ksh". Update: I've tried using the "history" command but that isn't aware of the history outside the current script. $ cat k.ksh #!/bin/ksh . j.ksh $ cat j.ksh #!/bin/ksh a=$(history | tail -1) echo $a $ ./k.ksh 270 ./k.ksh I would want it echo "* ./j.ksh". A: If it's the AT&T ksh93, this information is stored in the .sh namespace, in the variable .sh.file. Example sourced.sh: ( echo "Sourced: ${.sh.file}" ) Invocation: $ ksh -c '. ./sourced.sh' Result: Sourced: /var/tmp/sourced.sh The .sh.file variable is distinct from $0. While $0 can be ksh or /usr/bin/ksh, or the name of the currently running script, .sh.file will always refer to the file for the current scope. In an interactive shell, this variable won't even exist: $ echo ${.sh.file:?} -ksh: .sh.file: parameter not set A: I believe the only portable solution is to override the source command: source() { sourced=$1 . "$1" } And then use source instead of . (the script name will be in $sourced). A: The difference of course between sourcing and forking is that sourcing results in the invoked script being executed within the calling process. Henk showed an elegant solution in ksh93, but if, like me, you're stuck with ksh88 then you need an alternative. I'd rather not change the default ksh method of sourcing by using C-shell syntax, and at work it would be against our coding standards, so creating and using a source() function would be unworkable for me. ps, $0 and $_ are unreliable, so here's an alternative: $ cat b.sh ; cat c.sh ; ./b.sh #!/bin/ksh export SCRIPT=c.sh . $SCRIPT echo "PPID: $$" echo "FORKING c.sh" ./c.sh If we set the invoked script in a variable, and source it using the variable, that variable will be available to the invoked script, since they are in the same process space. #!/bin/ksh arguments=$_ pid=$$ echo "PID:$pid" command=`ps -o args -p $pid | tail -1` echo "COMMAND (from ps -o args of the PID): $command" echo "COMMAND (from c.sh's \$_ ) : $arguments" echo "\$SCRIPT variable: $SCRIPT" echo dirname: `dirname $0` echo ; echo Output is as follows: PID:21665 COMMAND (from ps -o args of the PID): /bin/ksh ./b.sh COMMAND (from c.sh's $_ ) : SCRIPT=c.sh $SCRIPT variable: c.sh dirname: . PPID: 21665 FORKING c.sh PID:21669 COMMAND (from ps -o args of the PID): /bin/ksh ./c.sh COMMAND (from c.sh's $_ ) : ./c.sh $SCRIPT variable: c.sh dirname: . So when we set the SCRIPT variable in the caller script, the variable is either accessible from the sourced script's operands, or, in the case of a forked process, the variable along with all other environment variables of the parent process are copied for the child process. In either case, the SCRIPT variable can contain your command and arguments, and will be accessible in the case of both sourcing and forking. A: You should find it as last command in the history.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can you set a maximum limit to an integer (C++)? If I never want an integer to go over 100, is there any simple way to make sure that the integer never exceeds 100, regardless of how much the user adds to it? For example, 50 + 40 = 90 50 + 50 = 100 50 + 60 = 100 50 + 90 = 100 A: Here is a fairly simple and fairly complete example of a simple ADT for a generic BoundedInt. * *It uses boost/operators to avoid writing tedious (const, non-assigning) overloads. *The implicit conversions make it interoperable. *I shunned the smart optimizations (the code therefore stayed easier to adapt to e.g. a modulo version, or a version that has a lower bound as well) *I also shunned the direct templated overloads to convert/operate on mixed instantiations (e.g. compare a BoundedInt to a BoundedInt) for the same reason: you can probably rely on the compiler optimizing it to the same effect anyway Notes: * *you need c++0x support to allow the default value for Max to take effect (constexpr support); Not needed as long as you specify Max manually A very simple demonstration follows. #include <limits> #include <iostream> #include <boost/operators.hpp> template < typename Int=unsigned int, Int Max=std::numeric_limits<Int>::max()> struct BoundedInt : boost::operators<BoundedInt<Int, Max> > { BoundedInt(const Int& value) : _value(value) {} Int get() const { return std::min(Max, _value); } operator Int() const { return get(); } friend std::ostream& operator<<(std::ostream& os, const BoundedInt& bi) { return std::cout << bi.get() << " [hidden: " << bi._value << "]"; } bool operator<(const BoundedInt& x) const { return get()<x.get(); } bool operator==(const BoundedInt& x) const { return get()==x.get(); } BoundedInt& operator+=(const BoundedInt& x) { _value = get() + x.get(); return *this; } BoundedInt& operator-=(const BoundedInt& x) { _value = get() - x.get(); return *this; } BoundedInt& operator*=(const BoundedInt& x) { _value = get() * x.get(); return *this; } BoundedInt& operator/=(const BoundedInt& x) { _value = get() / x.get(); return *this; } BoundedInt& operator%=(const BoundedInt& x) { _value = get() % x.get(); return *this; } BoundedInt& operator|=(const BoundedInt& x) { _value = get() | x.get(); return *this; } BoundedInt& operator&=(const BoundedInt& x) { _value = get() & x.get(); return *this; } BoundedInt& operator^=(const BoundedInt& x) { _value = get() ^ x.get(); return *this; } BoundedInt& operator++() { _value = get()+1; return *this; } BoundedInt& operator--() { _value = get()-1; return *this; } private: Int _value; }; Sample usage: typedef BoundedInt<unsigned int, 100> max100; int main() { max100 i = 1; std::cout << (i *= 10) << std::endl; std::cout << (i *= 6 ) << std::endl; std::cout << (i *= 2 ) << std::endl; std::cout << (i -= 40) << std::endl; std::cout << (i += 1 ) << std::endl; } Demo output: 10 [hidden: 10] 60 [hidden: 60] 100 [hidden: 120] 60 [hidden: 60] 61 [hidden: 61] Bonus material: With a fully c++11 compliant compiler, you could even define a Userdefined Literal conversion: typedef BoundedInt<unsigned int, 100> max100; static max100 operator ""_b(unsigned int i) { return max100(unsigned int i); } So that you could write max100 x = 123_b; // 100 int y = 2_b*60 - 30; // 70 A: Yes. As a bare minimum, you could start with this: template <int T> class BoundedInt { public: explicit BoundedInt(int startValue = 0) : m_value(startValue) {} operator int() { return m_value; } BoundedInt operator+(int rhs) { return BoundedInt(std::min((int)BoundedInt(m_value + rhs), T)); } private: int m_value; }; A: Try this: std::min(50 + 40, 100); std::min(50 + 50, 100); std::min(50 + 60, 100); std::min(50 + 90, 100); http://www.cplusplus.com/reference/algorithm/min/ Another option would be to use this after each operation: if (answer > 100) answer = 100; A: You can write your own class IntegerRange that includes overloaded operator+, operator-, etc. For an example of operator overloading, see the complex class here. A: The simplest way would be to make a class that holds the value, rather than using an integer variable. class LimitedInt { int value; public: LimitedInt() : value(0) {} LimitedInt(int i) : value(i) { if (value > 100) value = 100; } operator int() const { return value; } LimitedInt & operator=(int i) { value = i; if (value > 100) value = 100; return *this; } }; You might get into trouble with results not matching expectations. What should the result of this be, 70 or 90? LimitedInt q = 2*60 - 30; A: C++ does not allow overriding (re-defining) operators on primitive types. If making a custom integer class (as suggested above) does not fall under your definition of a "simple way", then the answer to your question is no, there is no simple way to do what you want. A: I know it's an old post but I think it could still be usefull for some people. I use this to set upper and lower bound: bounded_value = max(min(your_value,upper_bound),lower_bound); You could use it in a function like this: float bounded_value(float x, float upper, float under){ return max(min(x,upper),lower); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Calculate mean and standard deviation from a vector of samples in C++ using Boost Is there a way to calculate mean and standard deviation for a vector containing samples using Boost? Or do I have to create an accumulator and feed the vector into it? A: If performance is important to you, and your compiler supports lambdas, the stdev calculation can be made faster and simpler: In tests with VS 2012 I've found that the following code is over 10 X quicker than the Boost code given in the chosen answer; it's also 5 X quicker than the safer version of the answer using standard libraries given by musiphil. Note I'm using sample standard deviation, so the below code gives slightly different results (Why there is a Minus One in Standard Deviations) double sum = std::accumulate(std::begin(v), std::end(v), 0.0); double m = sum / v.size(); double accum = 0.0; std::for_each (std::begin(v), std::end(v), [&](const double d) { accum += (d - m) * (d - m); }); double stdev = sqrt(accum / (v.size()-1)); A: Improving on the answer by musiphil, you can write a standard deviation function without the temporary vector diff, just using a single inner_product call with the C++11 lambda capabilities: double stddev(std::vector<double> const & func) { double mean = std::accumulate(func.begin(), func.end(), 0.0) / func.size(); double sq_sum = std::inner_product(func.begin(), func.end(), func.begin(), 0.0, [](double const & x, double const & y) { return x + y; }, [mean](double const & x, double const & y) { return (x - mean)*(y - mean); }); return std::sqrt(sq_sum / func.size()); } I suspect doing the subtraction multiple times is cheaper than using up additional intermediate storage, and I think it is more readable, but I haven't tested the performance yet. A: It seems the following elegant recursive solution has not been mentioned, although it has been around for a long time. Referring to Knuth's Art of Computer Programming, mean_1 = x_1, variance_1 = 0; //initial conditions; edge case; //for k >= 2, mean_k = mean_k-1 + (x_k - mean_k-1) / k; variance_k = variance_k-1 + (x_k - mean_k-1) * (x_k - mean_k); then for a list of n>=2 values, the estimate of the standard deviation is: stddev = std::sqrt(variance_n / (n-1)). Hope this helps! A: Using accumulators is the way to compute means and standard deviations in Boost. accumulator_set<double, stats<tag::variance> > acc; for_each(a_vec.begin(), a_vec.end(), bind<void>(ref(acc), _1)); cout << mean(acc) << endl; cout << sqrt(variance(acc)) << endl;   A: I don't know if Boost has more specific functions, but you can do it with the standard library. Given std::vector<double> v, this is the naive way: #include <numeric> double sum = std::accumulate(v.begin(), v.end(), 0.0); double mean = sum / v.size(); double sq_sum = std::inner_product(v.begin(), v.end(), v.begin(), 0.0); double stdev = std::sqrt(sq_sum / v.size() - mean * mean); This is susceptible to overflow or underflow for huge or tiny values. A slightly better way to calculate the standard deviation is: double sum = std::accumulate(v.begin(), v.end(), 0.0); double mean = sum / v.size(); std::vector<double> diff(v.size()); std::transform(v.begin(), v.end(), diff.begin(), std::bind2nd(std::minus<double>(), mean)); double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0); double stdev = std::sqrt(sq_sum / v.size()); UPDATE for C++11: The call to std::transform can be written using a lambda function instead of std::minus and std::bind2nd(now deprecated): std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; }); A: My answer is similar as Josh Greifer but generalised to sample covariance. Sample variance is just sample covariance but with the two inputs identical. This includes Bessel's correlation. template <class Iter> typename Iter::value_type cov(const Iter &x, const Iter &y) { double sum_x = std::accumulate(std::begin(x), std::end(x), 0.0); double sum_y = std::accumulate(std::begin(y), std::end(y), 0.0); double mx = sum_x / x.size(); double my = sum_y / y.size(); double accum = 0.0; for (auto i = 0; i < x.size(); i++) { accum += (x.at(i) - mx) * (y.at(i) - my); } return accum / (x.size() - 1); } A: 2x faster than the versions before mentioned - mostly because transform() and inner_product() loops are joined. Sorry about my shortcut/typedefs/macro: Flo = float. CR const ref. VFlo - vector. Tested in VS2010 #define fe(EL, CONTAINER) for each (auto EL in CONTAINER) //VS2010 Flo stdDev(VFlo CR crVec) { SZ n = crVec.size(); if (n < 2) return 0.0f; Flo fSqSum = 0.0f, fSum = 0.0f; fe(f, crVec) fSqSum += f * f; // EDIT: was Cit(VFlo, crVec) { fe(f, crVec) fSum += f; Flo fSumSq = fSum * fSum; Flo fSumSqDivN = fSumSq / n; Flo fSubSqSum = fSqSum - fSumSqDivN; Flo fPreSqrt = fSubSqSum / (n - 1); return sqrt(fPreSqrt); } A: In order to calculate the sample mean with a better presicion the following r-step recursion can be used: mean_k=1/k*[(k-r)*mean_(k-r) + sum_over_i_from_(n-r+1)_to_n(x_i)], where r is chosen to make summation components closer to each other. A: //means deviation in c++ /A deviation that is a difference between an observed value and the true value of a quantity of interest (such as a population mean) is an error and a deviation that is the difference between the observed value and an estimate of the true value (such an estimate may be a sample mean) is a residual. These concepts are applicable for data at the interval and ratio levels of measurement./ #include <iostream> #include <conio.h> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { int i,cnt; cout<<"please inter count:\t"; cin>>cnt; float *num=new float [cnt]; float *s=new float [cnt]; float sum=0,ave,M,M_D; for(i=0;i<cnt;i++) { cin>>num[i]; sum+=num[i]; } ave=sum/cnt; for(i=0;i<cnt;i++) { s[i]=ave-num[i]; if(s[i]<0) { s[i]=s[i]*(-1); } cout<<"\n|ave - number| = "<<s[i]; M+=s[i]; } M_D=M/cnt; cout<<"\n\n Average: "<<ave; cout<<"\n M.D(Mean Deviation): "<<M_D; getch(); return 0; } A: Create your own container: template <class T> class statList : public std::list<T> { public: statList() : std::list<T>::list() {} ~statList() {} T mean() { return accumulate(begin(),end(),0.0)/size(); } T stddev() { T diff_sum = 0; T m = mean(); for(iterator it= begin(); it != end(); ++it) diff_sum += ((*it - m)*(*it -m)); return diff_sum/size(); } }; It does have some limitations, but it works beautifully when you know what you are doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "103" }
Q: Discrepancy between Google Chrome and Firefox I'm getting different results for this fiddle on Google Chrome (14.0.835.186) and Firefox (6.0.2). Can anyone explain the discrepancy? What is the behaviour determined by the specifications? EDIT: On Firefox I see [0], [0, 1], etc. On Chrome I see [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], etc. I'm using Mac OS 10.6.8. A: Firefox is more technically correct in this case as it outputs the state of the object at each point in the loop whereas Chrome is apparently waiting until the end of the loop to output each console.log, but I'm not aware of a standards specification that covers the console host object. See this jsFiddle: http://jsfiddle.net/jfriend00/LRGP2/ to show that this is only console.log that has this odd behavior. A: See: * *Your example with console.log before the loop *Your example using document.write *Bizarre console.log behaviour in Chrome Developer Tools It's an odd behavior or the console, though I can't tell you why. Edit: Just to make sure it's clear, this is a 'bug' in the console only, there is no problem with the way the arrays are created in Chrome. A: You are logging a live object. Try the code below (fiddle) and see the difference: var i, test = []; for(i=0; i<5; i++) { test.push(i); console.log( test.toString() ); // notice .toString() addition } Btw, same and aggravated example can be seen in Opera Dragongfly - arrays are even clickable and expandable there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Dynamic setting of Log4j level across multiple JVMs I am working in an application has a number of plain vanilla Java components, each of which runs in a separate JVM. All these components use Log4j and there is no option to change to another logging library. As the title implies, I am looking for an "easy" way to dynamically apply a Log4j logging level across all components/JVMs. By "easy", I mean without rewriting the source code (otherwise, one can use, for instance, an interface to get/set the logging level, and have all classes implement that interface). There are articles on the web about using JMX (for instance, via the LoggerDynamicBean class (http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/jmx/LoggerDynamicMBean.html) of the Log4j distribution. An interesting such article describes how to implement this using an application server (Tomcat): http://www.devx.com/Java/Article/32359/1954. The application server seems necessary as an implementation of the MBeanServer class, to which all the loggers will be registered by Log4j as MBeans. Is there any implementation that does this dynamic logging level setting, across multiple JVMs, either via JMX, or via any other means? A: Keep it simple. Point all the JVMs to the same log4j configuration file use this to have them reload occasionally. PropertyConfigurator.configureAndWatch( yourConfigFile, yourReloadInterval);
{ "language": "en", "url": "https://stackoverflow.com/questions/7616519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to execute a .sql script from bash Basically, I need to setup a database from a bash script. I have a script db.sql that does all this. Now how do I run this script from bash? Database system is mysql A: If you want to run a script to a database: mysql -u user -p data_base_name_here < db.sql A: You simply need to start mysql and feed it with the content of db.sql: mysql -u user -p < db.sql
{ "language": "en", "url": "https://stackoverflow.com/questions/7616520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "67" }
Q: Update table with LINQ SOLVED look below code snippet. I have a problem with updating tables, The code shows no faults but it don't act as expected, it does not put any information in the Log Table. some explenation, i have a table called User with a FK on LogID and a table called Log with PK on LogID so that should be correct, the Log has a column called TimesLoggedIn and one called LastLogedin. and i want to update them accordingly. User logid = db.Users.Single(p => p.UserID == loginID); logid.Log.LastLogedin= DateTime.UtcNow; if (logid.Log.TimesLoggedIn == null) { logid.Log.TimesLoggedIn = 1; } else { logid.Log.TimesLoggedIn = logid.Log.TimesLoggedIn + 1; } db.SubmitChanges(); had an embarrassing fault in my code, i had Response.Redirect("ControlPanel"); placed before i ran the LINQ not after. A: I'm using Entity Framework, so I might be wrong. But maybe the Log isn't loaded at all. Try this: var options = New DataLoadOptions(); options.LoadWith<Users>(x => x.Log); db.LoadOptions = options; // then your code: User logid = db.Users.Single(p => p.UserID == loginID); logid.Log.LastLogedin= DateTime.UtcNow; ....
{ "language": "en", "url": "https://stackoverflow.com/questions/7616522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert HTML into mailto body Possible Duplicate: Is it possible to add an HTML link in the body of a MAILTO link As I saw here: Is it possible to add an HTML link in the body of a MAILTO link "However even if you use plain text it's possible that some modern mail clients would render the resulting link as a clickable link anyway, though." How can I write mailto with HTML body that will work and will be parsed in GMail or Outlook for example? A: The accepted answer to the question you link to states clearly that you can't have HTML in mailto: mails. And that's pretty much all there is to say about it. Certain elements like links may get highlighted automatically by the mail client if it chooses to do so, but that doesn't mean HTML becomes possible in mailto E-Mails. Sorry.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Operator overloading equivalent in C++ for PHP, echo/print class variable for default output I don't know how to really ask this because I am fairly new to programming in comparison to many of you. What I am looking for is a default printing or echoing of a class. I'll give you the c++ equivalent. ClassName varClass(param); cout << "Default print: " << varClass << endl; As you can see in that brief example, instead of having to call varClass.customPrintFunction(), I only had to use the variable name. What I need is the php equivalent to that. What in php would allow me to do this: $address = new Address(param); echo "Default print: " . $address . "<br />"; Instead of: echo "Default print: " . $address->customPrintFunction() . "<br />"; I hope I was clear enough. If there isn't an equivalent, if you could give me what would be my best option instead. Thanks in advanced. A: You can define a __toString method that defines the behavior of the object in case it is cast to a string. public function __toString() { return $this->customPrintFunction(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Serializing form in jquery and passing it into php I have been trying for the last couple of days to serialize a form in jquery and pass it to php. For some reason it just doesn't work... Question, What steps do you take to serialize a form in Jquery... I get the id of the form pass it into $('#fomrID').serialize()... And it still doesn't work. When I debugg with firebug All I get is an empty string... Do you use the name or the Id of the form. Do you use e.disableDefalut or whatever that is? I can't figure out why I can't serialize my form please help $('#profilepicbutton').change(function(){ alert("Boy I hate PHP"); var formElement = $('#profilepicinput').attr('value'); dataString = $("#registerpt3").serialize(); $.ajax({ type: "POST", url: "register3.php", data: dataString, //"profilePic="+formElement, success: function(data){ alert( "Data Saved: " + data ); $.ajax({ type: "POST", url: "retrievePic.php", data: "", success: function(data){ alert(data); var image = new Image(); $(image).load(function(){ console.log("we have uploaded this image"); }).attr('src', 'images/'); alert(""); }, error: function(msg){ alert(""); } }); }, error:function(msq){ alert("" + msg); } } ); }); <form id="registerpt3" name="registerpt3" enctype="multipart/form-data" action="register3.php" onSubmit="" method="post"> <input name="profilepicinput" type="file" id="profilepicbutton" /> </form> A: According to http://api.jquery.com/serialize For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized. Also, simply calling serialize won't actually upload the picture for you. If you want to do an asynchronous picture upload (or any file for that matter) I'd suggest looking into something like Uploadify: http://www.uploadify.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7616531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to forward a REST web service using C# (WCF)? There is a web service that can only be consumed via http and a client that can only consume https web services. Therefore I need some intermediary that forwards on requests received in https and returns responses in http. Supposing that the intermediary is completely dumb save for the fact that it knows where the web service endpoint is (i.e. it doesn't know what the signature of the service is, it just knows that it can communicate with it via an http web request, and it listens on some https uri, forwarding on anything it receives), what is the most simple way of achieving this? I've been playing around with this all day and am not sure how to achieve the "dumb" bit, i.e. not knowing the signature for passing back the verbatim response. A: A dumb intermediary is essentially a proxy. Your best bet might to be just use standard asp.net pages (instead of shoehorning into service functionality like ASMX or WCF which are just going to fight you) so you can receive the request exactly as-is and process it in a simple way using standard request/response. You can make use of HttpWebRequest class to forward the request on to the other endpoint. * *Client requests https://myserver.com/forwarder.aspx?forwardUrl=http://3rdparty.com/api/login *myserver.com (your proxy) reads querystring forwardUrl and any POST or GET request included. *myserver.com requests to http://3rdparty.com/api/login and passes along GET or POST data sent from the client. *myserver.com takes response and sends back as response to other endpoint (essentially just Response.Write contents out to the response) You would need to write forwarder.aspx to process the requests. Code for forwarder.aspx would be something like this (untested): protected void Page_Load(object sender, EventArgs e) { var forwardUrl = Request.QueryString["forwardUrl"]; var post = new StreamReader(Request.InputStream).ReadToEnd(); var req = (HttpWebRequest) HttpWebRequest.Create(forwardUrl); new StreamWriter(req.GetRequestStream()).Write(post); var resp = (HttpWebResponse)req.GetResponse(); var result = new StreamReader(resp.GetResponseStream).ReadToEnd(); Response.Write(result); // send result back to caller }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What's the correct .csv format to make a pie chart in Highcharts? I have external data that I'd like to make into a pie chart with Highchart. I want to dump the data into a .csv file, but what is the format? This documentation only shows how to format .csv files for bar graphs: http://highcharts.com/documentation/how-to-use#preprocessing What if I want to make a pie chart? A: Actually, there is no correct csv format for highcharts. Highcharts only accepts data in one of these three formats. The goal of the data-preprocessing is to transform the data into a supported javascript array format. Quoting the reference: data : Array An array of data points for the series. The points can be given in three ways: * *A list of numerical values. In this case, the numberical values will be interpreted and y values, and x values will be automatically calculated, either starting at 0 and incrementing by 1, or from pointStart and pointInterval given in the plotOptions. If the axis is has categories, these will be used. Example: data: [0, 5, 3, 5] *A list of arrays with two values. In this case, the first value is the x value and the second is the y value. If the first value is a string, it is applied as the name of the point, and the x value is incremented following the above rules. Example: data: [[5, 2], [6, 3], [8, 2]] *A list of object with named values. In this case the objects are point configuration objects as seen under options.point. Example: data: [{ name: 'Point 1', color: '#00FF00', y: 0 }, { name: 'Point 2', color: '#FF00FF', y: 5 }] Defaults to "". A: Found the answer on Highcharts' forum: http://highslide.com/forum/viewtopic.php?f=9&t=8614&hilit=pie+chart+.csv Make sure you don't have an extra new line at the end of your .csv file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Applying Spree decorator H guys, first of all let me tell u I am new to spree, so my question might sound stupid to most of you. I want to customize for example the "index" method in the home_controller.rb, I know the right way is to use a decorators. So I have created this file app/controller/home_controller_decorator.rb. I have in there # app/controller/home_controller_decorator.rb HomeController.class_eval do def index # Empty method end end The original spree index method looks like def index @searcher = Spree::Config.searcher_class.new(params) @products = @searcher.retrieve_products respond_with(@products) end I expect that when I restart the server with the _decorator added it will display me no products on the home page, or will crash. When applying this decorator and starting the server I get this message agop@linux-as2q:~/Desktop/spp> rails server -p 3000 /home/agop/Desktop/spp/app/controllers/home_controller_decorator.rb:1:in `<top (required)>': uninitialized constant Spree::BaseController (NameError) from /home/agop/Desktop/spp/lib/spree_site.rb:5:in `block in <class:Engine>' from /home/agop/Desktop/spp/lib/spree_site.rb:4:in `glob' from /home/agop/Desktop/spp/lib/spree_site.rb:4:in `<class:Engine>' from /home/agop/Desktop/spp/lib/spree_site.rb:2:in `<module:SpreeSite>' from /home/agop/Desktop/spp/lib/spree_site.rb:1:in `<top (required)>' from /home/agop/Desktop/spp/config/application.rb:11:in `<class:Application>' from /home/agop/Desktop/spp/config/application.rb:10:in `<module:Spp>' from /home/agop/Desktop/spp/config/application.rb:9:in `<top (required)>' from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/commands.rb:28:in `require' from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/commands.rb:28:in `block in <top (required)>' from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/commands.rb:27:in `tap' from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.9/lib/rails/commands.rb:27:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>' I am probably not writing the decorator in the way spree expects. What is the correct way to apply this decorator on the home_controller.rb index method? A: This is because HomeController inherits from Spree::BaseController which isn't loaded at this point in time due to some unknown reason. You should be able to fix it by putting require 'spree/base_controller' at the top of your decorator. Could you please also submit a GitHub issue for this on http://github.com/spree/spree? It would be helpful for anybody else who ran into this issue too. A: ActiveSupport::Concern is a clean way to decorate existing classes. But note, that caches are not cached in development mode, so you'll need to add something like the code below in config/environments/development.rb to ensure that your decorate methods persist. config.to_prepare do #SomeModel.send(:include, SomeDecorator) end Here are more details on this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Get selected item in listbox and call another function storing the selected for it I have a canvas that calls createCategoryMeny(x) when it is clicked. This function just creates a Toplevel() window, def createCategoryMenu(tableNumber): ##Not interesting below: categoryMenu = Toplevel() categoryMenu.title("Mesa numero: " + str(tableNumber)) categoryMenu.geometry("400x400+100+100") categoryMenu.focus() categoryMenu.grab_set() Label(categoryMenu, text="Elegir categoria \n Mesa numero: " + str(tableNumber)).pack() ## RELEVANT CODE BELOW: listbox = Listbox(categoryMenu, width=50, height=len(info.listaCategorias)) listbox.pack(pady=20) for item in info.listaCategorias: listbox.insert(END, item) listbox.selection_set(first=0) ##My attempt to solve it callback = lambda event, tag= "ThisShouldBeTheSelected!!": do(event, tag) listbox.bind("<Double-Button-1>", callback) Then the do function: def do(event, tag): print tag This successfully prints `"ThisShouldBeTheSelected!!"``. And this is where I am utterly stuck. I cant get the double clicked element (the selected one). I want to pass it as tag=. I have tried: listbox.curselection() Which always prints ('0',) If I remove listbox.selection_set(first=0), I only get this: () So the questions are: * *How can I get the selected item (the double clicked one) *(Not so important) Is it reasonable to pass it to the other function like I do? Note: I found this: 8.5. Why doesn't .listbox curselection or selection get return the proper item when I make a button binding to my listbox? The best way to get the selected item during a button click event on a listbox is to use the following code: bind .listbox { set item [%W get [%W nearest %y]] } This ensures that the item under the pointer is what will be returned as item. The reason .listbox curselection can fail is because the items in curselection are not set until the Listbox class binding triggers, which is after the instance bindings by defaults. This is the same reason for which selection get can fail, but it will also fail if you set the -exportselection option to 0. I'm not sure if it's helpful, I don't really understand what it is saying. A: While You have only one listbox to manage with, it's quite good to use something like this (Python 3): import tkinter as tk root = tk.Tk() box = tk.Listbox(root) box.insert(tk.END, 'First') box.insert(tk.END, 'Second') box.insert(tk.END, 'Third') box.pack() def onselect(event): w = event.widget idx = int(w.curselection()[0]) value = w.get(idx) print(value) box.bind('<<ListboxSelect>>', onselect) root.mainloop() But when You add another listbox, or\and meet a situation, where listbox loses its selection, IndexError is raised. To avoiding it, and to manage different callbacks for different listboxes I suggest something like this: import tkinter as tk root = tk.Tk() box = tk.Listbox(root) box.insert(tk.END, 'First') box.insert(tk.END, 'Second') box.insert(tk.END, 'Third') box.pack() box2 = tk.Listbox(root) box2.insert(tk.END, 'First') box2.insert(tk.END, 'Second') box2.insert(tk.END, 'Third') box2.pack() def on_first_box(idx, val): print('First box idx: %s, value: %s' % (idx, val)) def on_second_box(idx, val): print('Second box idx: %s, value: %s' % (idx, val)) def onselect(event, listbox): w = event.widget try: idx = int(w.curselection()[0]) except IndexError: return if listbox is box: return on_first_box(idx, w.get(idx)) if listbox is box2: return on_second_box(idx, w.get(idx)) box.bind('<<ListboxSelect>>', lambda e: onselect(e, box)) box2.bind('<<ListboxSelect>>', lambda e: onselect(e, box2)) root.mainloop() A: For one, don't use lambda. It's useful for a narrow range of problems and this isn't one of them. Create a proper function, they are much easier to write and maintain. Once you do that, you can call curselection to get the current selection. You say you tried that but your example code doesn't show what you tried, so I can only assume you did it wrong. As for the rather unusual advice to use nearest... all it's saying is that bindings you put on a widget happen before default bindings for that same event. It is the default bindings that set the selection, so when you bind to a single button click, your binding fires before the selection is updated by the default bindings. There are many ways around that, the best of which is to not bind on a single click, but instead bind on <<ListboxSelect>> which will fire after the selection has changed. You don't have that problem, however. Since you are binding on a double-click, the selection will have been set by the default single-click binding and curselection will return the proper value. That is, unless you have your own single-click bindings that prevent the default binding from firing. Here's a simple example that prints out the selection so you can see it is correct. Run it from the command line so you see stdout: import Tkinter as tk class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) lb = tk.Listbox(self) lb.insert("end", "one") lb.insert("end", "two") lb.insert("end", "three") lb.bind("<Double-Button-1>", self.OnDouble) lb.pack(side="top", fill="both", expand=True) def OnDouble(self, event): widget = event.widget selection=widget.curselection() value = widget.get(selection[0]) print "selection:", selection, ": '%s'" % value if __name__ == "__main__": app = SampleApp() app.mainloop() A: For spyder and python 3.6 this following code worked. import tkinter as tk root = tk.Tk() root.geometry("612x417") root.title("change label on listbox selection") root.resizable(0,0) root.configure(background='lightgrey') #Show selected currency for from in label frmcur_text = tk.StringVar() frmcur = tk.Label(root, textvariable=frmcur_text, font="Helvetica 10 bold", anchor='w', background='lightgrey').place(x=195,y=50) def onselect(evt): # Note here that Tkinter passes an event object to onselect() w = evt.widget index = int(w.curselection()[0]) value = w.get(index) # print ('You selected item %d: "%s"' % (index, value)) frmcur_text.set(value) #Create listboxes for xurrency selection listbox1 = tk.Listbox(root, font="Helvetica 11 bold", height=3, width=10) listbox2 = tk.Listbox(root, font="Helvetica 11 bold", height=3, width=10) listbox1.place(x=300,y=50) listbox2.place(x=300,y=125) for i in range(20): i = i + 1 listbox1.insert(1, i) listbox2.insert(1, i) listbox1.bind('<<ListboxSelect>>', onselect) cs = listbox1.curselection() frmcur_text.set(cs) root.mainloop()
{ "language": "en", "url": "https://stackoverflow.com/questions/7616541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: God messing with Date Operations This is a weired think. Follow my steps: Without god, on console: > d=Date.parse("2010-02-01") => Mon, 01 Feb 2010 > d+1.day => Tue, 02 Feb 2010 Perfect. Then, I go to my Gemfile and add gem 'god' and run bundle install After that, on console again: > d=Date.parse("2010-02-01") => Mon, 01 Feb 2010 > d+1.day => Sun, 23 Aug 2246 Do you know what could be happening? A: Odd that this is happening in a console. I could have understood it in other scenarios, where 1.day is being used as an input in one place and extracted for use somewhere else, since 1.day is the Fixnum 86400, with some special metadata (#steps) mixed into it. Date treats, for example, + 1 to mean "add one day". Rails adds some behaviour so that it understands the 1.day thing (86400 "seconds", but with a step of [1, :days]) to actually mean + 1 instead of + 86400. This is what you're losing: ruby-1.9.2-p290 :171 > d = Date.parse("2010-02-01") => #<Date: 2010-02-01 (4910457/2,0,2299161)> ruby-1.9.2-p290 :172 > d + 86400 => #<Date: 2246-08-23 (5083257/2,0,2299161)> ruby-1.9.2-p290 :173 > So the value 1.day is being interpreted as a Fixnum, rather than a Fixnum with ActiveSupport::Duration. irb(main):001:0> Date.parse("2010-02-01") + 1.day.to_i => Sun, 23 Aug 2246 So if you're using this 1.day value in a context where it is not being immediately consumed, don't... use the Fixnum 1 instead ;) A: "god" makes a mess of Dates. This is a problem with "god". A gem used with Rails should not alter Rails conventions. If Date.current - 4.days does one thing without "god", then it should do that with "god". Period. A: According to the GitHub open issue, i tried this solution : Gemfile gem 'god', :require => false Instead of : gem 'god' The everything seem to work again : 1.9.3p0 :001 > d = Date.parse('2012-04-16') => Mon, 16 Apr 2012 1.9.3p0 :002 > d + 1.day => Tue, 17 Apr 2012
{ "language": "en", "url": "https://stackoverflow.com/questions/7616545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Specify what kind of object will be created at runtime of a program I have a set of java subclasses which all extend the same superclass. They contain exactly the same methods and make the same computations on input data of different type. That means that one is responsible to deal with int, another with double, another with int Array, List etc. Objects of each type should be created at runtime of the program according to the input data each time. What is the best way to specify what kind of object (of the referred subclasses) will be created each time while the program is running? It seems not possible to use something like type checking since the data could be of different type (class). Do I need a separate class that is responsible exclusively for this task, something that serves as an object generator? If so, is there a hint available about what would be the form and functionality of such a class? Thank you. A: I'm not sure I understood your question correctly as it's not very clear, some examples of your class and of what you trying to accomplish would help. Anyway, what I got from it is that you should check the Visitor pattern. http://en.wikipedia.org/wiki/Visitor_pattern In simpler words, I would separate the actions you want to make with each type, and have one class for each one of these (instead of having all these as methods in all your subclasses). And you would do something like that: yourSubclass.accept(yourAction) A visit method would be defined on the Visitor interface, once for each type of Subclass you have. And each of your action class would have to implement what to do for each one of these. And the accept method, in your superclass, would just call visit from the action. If this is not what you asked, sorry :) A: Here's an example with "sum". The sum of a single number is just that number. The sum of a collection of them is the sum of all numbers in that collection. interface Summable { double sum(); } class IntegerSum implements Summable { int i; IntegerSum(int i) { this.i = i; } public double sum() { return (double)i; } } class DoubleSum implements Summable { double d; DoubleSum(double d) { this.d = d; } public double sum() { return d; } } class ListSum<? extends Number> implements Summable { List<? extends Number> list; ListSum(List<? extends Number> list) { this.list = list; } public double sum() { double d = 0; for(Number n : list) d += n; return d; } } Now you just need a FACTORY method: class SummableFactory { public static Summable summableFor(double d) { return new DoubleSum(d); } public static Summable summableFor(int i) { return new IntegerSum(i); } public static Summable summableFor(List<? extends Number> list) { return new ListSum(list); } private SummableFactory() { } } A: maybe a factory like: abstract class Super { abstract void foo(); } class I extends Super { void foo() { System.out.println(this); } } class D extends Super { void foo() { System.out.println(this); } } class Factory { static Super create(Class clazz) { if(clazz.equals(Integer.class)) return new I(); else if(clazz.equals(Double.class)) return new D(); else return null; } } public class Main { public static void main(String[] args) { Factory.create(Integer.class).foo(); Factory.create(Double.class).foo(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: simple field update mysql I have a field with unixtime in seconds and I need it to be in milliseconds. Just a simple query to update the columns time and changetime by multiplying by 1000. I had a script to do this, but lost it. Totally having a Friday. A: UPDATE yourtable SET `time` = `time` * 1000, `changetime` = `changetime` * 1000 A: If you just want to update all your current rows then: update tablename set column_name=column_name*1000 where 1 A: Update yourtable Set column=column*1000 Replace 'yourtable' and 'column' by the actual names, obviously.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting started in OpenCV, recommendation for API functions to use I'm just getting started with OpenCV and I'm planning to build a robot with computer vision. I am looking to make this robot recognize classes of objects as well as individual instances. In a sense, a Haar-like feature capability for general classes and BIGG for specific instances. I am essentially looking to make something like this: http://www.youtube.com/watch?v=fQ59dXOo63o in the video, kinect is used, but I'll only be using a single camera. If you watch the video, you'll see that the kinect is shown an object and learns after a few seconds to recognize the new object. This is essentially what I want to do; instead of creating thousands of templates and training the software all at once, I want to make this process a semi manual one where the robot learns a single object at a time. I have no limitation on the type of object to be learned, everything is fair game. Because I'm dealing with a potentially large amount of objects that will be trained, I'm worried about performance issues. If I have 10,000 objects trained, I would imagine that my laptop might choke on some of the algorithms. I am currently pretty overwhelmed by all the different techniques that the documentation has and I've little idea of what do use. How would you guys tackle this problem? thanks A: Here are the questions you've asked about (whether you realize it or not): * *Object detection *Object classification *Object recognition *Segmentation *Normalization *Machine learning Each is an entire subject unto itself, and there is no "right" answer for your needs. You need to experiment and find that magical combination of algorithms that works well for your problem domain. Also, The kinect has an advantage that a normal camera doesn't, which is depth. Plain old 2D recognition is ridiculously hard. However in the spirit of giving a useful answer, check out the V1 algorithm by Nicolas Pinto which simulates the object detection capabilities of humans. http://pinto.scripts.mit.edu/Code/Code
{ "language": "en", "url": "https://stackoverflow.com/questions/7616553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create R heatmap with no margins whatsoever I'm trying to do something ostensibly simple: create a heatmap (i.e. 2D histogram) image with specified pixel-by-pixel dimensions (3600x3600) with no margins or axis labels whatsoever. I can successfully create a matrix of my data using the hist2d function. However, when I plot using the following code, I get an image file that is indeed 3600x3600 but actually includes x- and y-axis tickmarks and some whitespace on the edges. Annoyingly, this whitespace is not isotropic -- there are different amounts on different sides -- so I can't just make the initial image a bit larger, read it into PhotoShop, and clip it down to 3600x3600 so as to encompass just the plot area pixels (laborious though that would be). par(mar=c(0,0,0,0)) # this *should* eliminate all margins, leaving only the plot area... right? png("filename.png", w=3600, h=3600) image(my_matrix, col=heat.colors(16)) dev.off() Strangely, those labels and whitespace do not appear if I just plot the image in a Quartz window (I'm on a MacBook Pro, FYI): image(my_matrix, col=heat.colors(16)) # opens new window that looks perfect! This would work fine, but there's no way (that I know of) to specify this plot's size in pixels, just in inches (via pin). So I can't just save out this plot window to get the exact PNG I want. I've spent several days on this already and am getting nowhere. Any help? Is there some weirdness with how the par(mar) parameter interacts with certain plotting "devices" or something?... A: If I put the par call after the device activation, it works (along with setting axes = FALSE to get rid of the axes: png("~/Desktop/so/heatmap.png",w=400,h=400) par(mar = c(0,0,0,0)) require(grDevices) # for colours x <- y <- seq(-4*pi, 4*pi, len=27) r <- sqrt(outer(x^2, y^2, "+")) image(z = z <- cos(r^2)*exp(-r/6), col=gray((0:32)/32),axes = FALSE) dev.off() Obviously, I used smaller image dimensions in this example. This example code is from ?image. A: Do the par(mar=c(0,0,0,0)) after the call to png rather than before.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make buttons unclickable behind a small UIView? I have a strange problem. I have 3 level of views : - MainView - containerview - subview -some buttons -some buttons I've made a animation to make my subview appears and disappear by clicking a button in the master view. The following is a part of the code to make the subview disappeared and reappeared : [UIView animateWithDuration:0.4 //begin animation delay:0.1 options:UIViewAnimationCurveEaseIn animations:^{ [UIView transitionWithView:containerview duration:0.4 options:UIViewAnimationOptionTransitionCurlUp animations:^{ [subView removeFromSuperview] ;} completion:nil]; containerview.alpha = 0; } completion:^(BOOL finished){ saveButton.hidden = true; saveDAVButton.hidden = true; saveDBButton.hidden = true; loadButton.hidden = false; openDAVButton.hidden = false; openDBButton.hidden = false; [UIView transitionWithView:containerview duration:0.4 options:UIViewAnimationOptionTransitionCurlDown animations:^{ [containerview addSubview:subView] ;} completion:nil]; containerview.alpha = 1; } ]; This animation works perfectly. The only problem is that even when the subview is visible (so subview buttons as well), i can click buttons behind the subview! (buttons from the master view). That makes buttons from the subview hard to use, because they overlap buttons from masterview. Any idea how to make element behind the subview unclickable? I already tried to make buttons from master view disable and hidden, but even then, i can't use overlapping buttons from subview! Thank you for your help. UPDATE I've found what the problem is. Actually, i have again to make my post clearer. Here is the hierarchy of the views, with there position and size : - MainWindow (0,0,768,1024) - MainView (0,0,768,80) (this is actually a top tool bar) - containerview (500,40,120,80) - subview (500,40,120,80) (will act as a post it : curl up and down...) So, the problem is that the bottom of my subview is going outside of MainView. Nothing happen when a click to buttons place at the bottom of subview. In fact, i am clicking on MainWindow! Hafl of subview is unclickable... Before changing all my code, is there a way to make accessible bottom of subview even if he is part of MainView? Or do i have to move it in MainWindow? Thank you again... A: Switch the view's userInteractionEnabled property. A: Possibly the problem is that your buttons from the master view are in front of the containerView. Try: [MainView bringSubviewToFront:containerView]; Or in interface builder rearrange the order of containerView and the buttons that are in the main view. But I don't know, setting the buttons to hidden should make them hidden and unclickable, and prevent them from blocking touches to views behind them. A: Seeing your latest edit, perhaps you could check your clipsToBounds property (though getting everything to work right when things are outside a parent's bounds can be tricky — I can’t recall now but I may have given up and changed my containment hierarchy).
{ "language": "en", "url": "https://stackoverflow.com/questions/7616563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to display array elements php For example; in PHP the auto-global $_SERVER. How do I display the elements or keys that it has? I am unable to find out how online. A: $keys = array_keys($somearray); Is that what you're looking for? Or are you just looking for $somearray['somekey']? A: For debugging I assume? There are a couple ways, but I always do something like this: die(print_r($_SERVER)); A: Look into var_dump() and print_r. Both options should provide what you're looking for without having additional clarification for your request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load pdo object in a class php I have a single file I have my database connection (PDO) in. And as PDO is a class (library) or whatever, I don't feel the need of a database class (Or should I build one?) Anyway I want to load the pdo object, so I can use the functions in another class, but I'm not sure of how to do it. pdo_object.php //single php db connection file here.. $dbh = ... user.php class User { function login() { //do pdo query here... } } Do I need to inject the $dbh on every single class that needs database connection? A: "I don't understand your question. In User->login(), just put your PDO logic." - Don't I need to load in the dbh somehow in the class? There is no single answear to that! If your class is going to execute the logic (practically speaking doing an mysql_query) then you had to provide the connection handler. On the other hand your class does not execute the query but does for example some tasks like these: bulding the queries, applying the logic, checking if query data given by user is correct etc then no need to load the handler cause an other class will need it. I still believe these kind of questions (about designing) are very tricky and philosophic, general etc unless they are very specific, and yours is not that much. And as PDO is a class (library) or whatever, I don't feel the need of a database class (Or should I build one?) In practice we do build a database class and not just for puting the pdo handler there only, but because there are so many things that can be defined apriori and help you a lot. You might have more than a database handler (one for public use and for internal for example), you might have your own methods check this from an old project: public function getValueLike($dbh, $table,$col_name, $value ) { $col_name = '`'. $col_name . '`'; $sql = 'SELECT '. $col_name .' FROM '. $table .' where '. $col_name ." like ? limit 2" ; //prepare,execute $stmt = $dbh->prepare($sql ); $stmt->execute(array('%'.$value.'%')); //we want it is an array with int keys $stmt->setFetchMode(PDO::FETCH_NUM); $tmp = $stmt->fetchAll(); //get all values $res[] = $tmp[0];//get the first value $res[] = count($tmp);//get the count //return the 1st value found, also the count which at most can be 2 return $res ; } all these things including usernames, passwords, database servers etc etc wouldn't it be nice to be in one place (instead of being spread around), under a class that is easilly accessible, can apply access restriction etc. These are some arguments to justify my point. If you decide to build a class you call the class only once at the very begining and then just pass the object around. * *Go for MVC, choose a good one, the structure is mostly predefined and it will force you apply some cool stuff and make you a better programmer. *As for database handler I suggest as a minimum that you make it a singleton (static object) and pass the object around whenever needed an even better solution is to go with the non static way using a registry. Where you only pass the registry object somewhere and everything you need is accessible. If you cannot go into MVC just try to build a custom registry it will save a lot of time. There are good tutorials out there!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7616567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fastest programming language for computing large numbers? If I wanted to compute numbers with hundreds of millions of digits (positive integers), which programming language would be best suited for that? Currently I'm using python and the script is running and it was easy to code, but I have concerns for its speed. I don't really know much about assembly at all so while it MAY be the fastest, I would rather not use that. Is C the best choice here? The specific operations I have to use are *, -, % (mod), exponentiation, equality testing (if statements), and basic looping and some sort of outputting capability (console output for example). Many thanks. A: You can use GMP with plain C, but note that a lot of dynamic languages use it for arbitrary precision numbers, python too. You might not gain much by using C. A: GMP library with C/C++. http://gmplib.org/ A: Here is your resource to read up on. This refutes the argument that C is fastest, unless you use the C99 restrict feature. If anything C++ is faster than C. It really comes down to the compiler understanding when two separate but sequential operations 'read' reference the same memory location. This allows the compiler to reorder the operations for optimization. It appears Fortran is best at doing this. http://en.wikipedia.org/wiki/Pointer_aliasing Also you can see here that Fortran blows C++ away at the Mandelbrot routine. But when it comes to text manipulation C++ appears to be tops. http://shootout.alioth.debian.org/u32/fortran.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7616570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Alternatives to Pass both Key and Value By Reference: Can someone explain to me why you can't pass a key as reference? Ex: if(is_array($where)){ foreach($where as &$key => &$value){ $key = sec($key); $value = sec($value); } unset($key, $value); } Throws: Fatal error: Key element cannot be a reference in linkstest.php on line 2 Can I do something similar using array_map? All I want to do is iterate over an associative array, and escape both the key and value with my sec() function. Array map is difficult for me to understand: I have tried many things with array_map, but I can't get it to act on the keys directly. Would I get any performance benefit using array map than just using a foreach loop? What I don't like about foreach is that I can't act on the array directly, and have to deal with creating temporary arrays and unsetting them: foreach($where as $key => $value){ $where[secure($key)] = secure($value); } This might fail if it finds something to escape in the key, adding a new element, and keeping the unescaped one. So am I stuck with something like this? $temparr = array(); foreach($where as $key => $value){ $temparr[secure($key)] = secure($value); } $where = $temparr; unset($temparr); Any alternatives? A: Can someone explain to me why you can't pass a key as reference? Because the language does not support this. You'd be hard-pressed to find this ability in most languages, hence the term key. So am I stuck with something like this? Yes. The best way is to create a new array with the appropriate keys. Any alternatives? The only way to provide better alternatives is to know your specific situation. If your keys map to table column names, then the best approach is to leave the keys as is and escape them at their time of use in your SQL. A: why is it a problem to do that? Make it a function. A function takes an input and gives an output. Your function input will be your "unsecured" array. Your output will be the result of securing the array. Then you just do $where = secureMyArray($where); That's why you have the ability to make functions...
{ "language": "en", "url": "https://stackoverflow.com/questions/7616572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: jQuery SimplyScroll plugin breaks on some zoom levels You can actually see this effect on the SimplyScroll demo page: use Safari, Chrome or Firefox, and zoom out to the point that page elements are very small, and the scroller stops moving. I've tested and experimented, and it appears that the scrollLeft value is being incremented within a setInterval loop, but it doesn't "stick", and just stays at the previous scroll value instead. Even more strangely, altering the scroll value manually from the console works just fine. Here is the relevant snippet: self.interval = setInterval(function() { // snip // increment by 1 pixel self.$clip[0].scrollLeft += self.o.speed; // scrollLeft value is unchanged // snip },self.intervalDelay); // usually set to 41 I've tried replacing setInterval with requestAnimationFrame, and also drastically turning down the speed, and no results; I'm stumped. Any ideas on why zoom level is affecting the ability to scroll within a timer callback? A: I figured it out: it looks like it has do with what constitutes a "pixel" when zoomed out; a single-pixel change evaluates to being less than one pixel, which leads to no change. I plan to file a bug report with the developer; for now, I've implemented the following hack workaround: self.interval = setInterval(function() { // snip var elem = self.$clip[0]; var scrollLeft = elem.scrollLeft // increment by 1 pixel elem.scrollLeft += self.o.speed; // Zoom out hack: raise pixel values until a change actually takes place if(elem.scrollLeft == scrollLeft) { elem.scrollLeft += (self.o.speed + 1); if(elem.scrollLeft == scrollLeft) elem.scrollLeft += (self.o.speed + 2); } // snip },self.intervalDelay); A: step 1: Add function below fixScrollNotRunWhenBrowserZoomout: function(){ var self = this; var speed = self.o.speed; var sp = self.$clip[0].scrollLeft; var intervalHandle = setInterval(function(){ self.$clip[0].scrollLeft += speed; if (Math.floor(self.$clip[0].scrollLeft) !== sp || speed == 100){ clearInterval(intervalHandle); self.o.speed = speed; } speed++; }, 100); } Step 2: call it on init function init: function() { this.$items = this.$list.children(); this.$clip = this.$list.parent(); //this is the element that scrolls this.$container = this.$clip.parent(); this.$btnBack = $('.simply-scroll-back',this.$container); this.$btnForward = $('.simply-scroll-forward',this.$container); this.fixScrollNotRunWhenBrowserZoomout();
{ "language": "en", "url": "https://stackoverflow.com/questions/7616579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pyramid 1.2 on Google App Engine causes import error I'm trying to run Pyramid on GAE by following the steps outlined here. Everything works fine on dev server, but when deployed to Google's servers, the following error occurs: <type 'exceptions.ImportError'>: cannot import name BaseRequest Traceback (most recent call last): File "/base/data/home/apps/.../0-0-1.353634463095353211/main.py", line 9, in <module> from pyramid.config import Configurator File "/base/data/home/apps/.../0-0-1.353634463095353211/lib/dist/pyramid/__init__.py", line 1, in <module> from pyramid.request import Request File "/base/data/home/apps/.../0-0-1.353634463095353211/lib/dist/pyramid/request.py", line 6, in <module> from webob import BaseRequest This is probably caused by the fact that GAE uses WebOb 0.9 while Pyramid uses WebOb 1.1 (it resides under lib/dist/webob in my project), since BaseRequest is missing in 0.9. In the main.py file there is this fragment: sys.path.insert(0,'lib/dist') but it seems to help only for dev server case. I there a way to force GAE runtime to use version 1.1 included in my application? A: It's not really a solution, per-se, but we're about to release the new Python runtime, Python 2.7, which includes updated versions of libraries, including webob 1.1. Perhaps you could target your app against that, instead of against the 2.5 runtime? A: Apart from the runtime update, I found another workaround. I've renamed the WebOb 1.1 module from webob to webobx and made pyramid reference the renamed webobx module. Not very elegant and will have to be repeated if I get to upgrade pyramid, but works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Next occurrence of something, down the DOM tree I'm having the hardest time trying to reference the next occurrence of an element with an ID containing a specific string. Basically, I have a link, and I need to show() the NEXT div acting as a container for editing. <div> <a href="#" id="link-1">Link</a> // go from here </div> <div id="form-container-1" class="hidden"> // to here <form> ... </form> Important to note: I'm not just targeting one id ... the purpose of the "1" within the form-container id is because there are several. I'm using the "contains" selector id*="form-container" A: If it directly proceeds the current item, then will work. Try using a combination of parent() and next() then. This way you will be able to reference the containing div and then find the next div. Working example: http://jsfiddle.net/PdatP/ jQuery: $('a').click(function(){ $(this).parent().next().show(); }); A: This will get the next sibling and show that element $('#link-1').next().show(); if its not exactly the next element you can use siblings method like; $('#link-1').siblings('#form-container-1').show(); Or if you want to show all elements that contain form-container in their ids $('#link-1').siblings('[id*="form-container"]').show(); A: If you want to dynamically find the correct form to show based on the id then something like: $('a').click( function() { formId = $(this).attr('id').split('-')[1]; $('#form-container-'+formId).show(); }); Alternatively, if you want to find the next form after each link: $('a').click( function() { $(this).next('form').show(); }); Both of these, it would be advisable to add a unique class to links that will show forms and update the selectors accordingley. A: $("#link-1").parent().next().show();
{ "language": "en", "url": "https://stackoverflow.com/questions/7616587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Sharing local ehcache among multiple Tomcat webapps I have 2 different webapps running in the same Tomcat 6 instance. Both share a library which uses hibernate for persistence. I want to enable Hibernate 2nd level caching with ehcache, but I don't want each of the webapps to have its own cache. Any idea how I might implement this? I installed ehcache-core into $CATALINA_HOME/lib and each spring application is configuring hibernate to use ehcache like this: <property name="hibernateProperties"> <props> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</prop> </props> </property> Both apps are using ehcache, but each still has its own distinct cache (modify an item in one app and the stale value still appears in the other app) My ehcache.xml (also in $CATALINA_HOME/lib) looks like this: <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" name="mySharedCache" updateCheck="false" monitoring="autodetect" dynamicConfig="false"> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"> </defaultCache </ehcache> More details: * *Tomcat 6 *Spring 3.0.5 *Hibernate 3.6.5 *EhCache 2.4.5 A: It is possible to configure EhCache for use in clustered environment. Each app will have its own cache but changes to one cache are replicated to the others in the cluster. To use JGroups for this purpose you can add something like the following to your ehcache.xml: <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory" properties="connect=UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32; mcast_send_buf_size=150000;mcast_recv_buf_size=80000): PING(timeout=2000;num_initial_members=6): MERGE2(min_interval=5000;max_interval=10000): FD_SOCK:VERIFY_SUSPECT(timeout=1500): pbcast.NAKACK(gc_lag=10;retransmit_timeout=3000): UNICAST(timeout=5000): pbcast.STABLE(desired_avg_gossip=20000): FRAG: pbcast.GMS(join_timeout=5000;join_retry_timeout=2000; shun=false;print_local_addr=true)" propertySeparator="::"/> Then add the following inside your defaultcache element: <cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory" properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true, replicateUpdatesViaCopy=true, replicateRemovals=true"/> I learnt about this from a chapter in Java Persistence with Hibernate which I would recommend reading. It says that the above example is from the EhCache documentation. If you don't want each app to have its own cache then read up on Infinispan.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Alternative for Postmessage and sendmessage i have a program which is using several threads to execute some task. Each thread is having a bunch of task to execute. after executing one of them, each thred will call a post message to main screen to update logs. Now i have sixty thousand tasks ten thousand for each thread - six threads- after executing each task thread is calling post messages. but because of these post messages my application becomes very busy and looks like it hanged. if i remove post messages...every thing works fine. But i cannot call the procedure directly because it uses ui controls and ui controls are not thread safe and calling procedure directly from thread will lead to other errors. so is there any alternative available for postmessage and send message. Thanks, bASIL A: You are going to struggle to find anything better than PostMessage. My guess is that your problem is that you are updating UI too frequently and your queue is becoming saturated because you cannot service it quickly enough. How about skipping updates if you updated less than a second ago say? If that restores responsiveness then you can consider a more robust solution. A: The problem is that there are two message queues for posted messages. The result of this is that your posted messages are always processed before any Paint, Input, or Timer messages. This means that you are flooding the message queue with a few hundred thousand messages. These messages will always get processed before paint and user messages - making your application appear to hang. The common way to solve this is to use a timer; have your code start a very short duration (e.g. 0 ms) timer. Clarification Timer messages (WM_TIMER), like Paint messages (WM_PAINT) and Input messages (e.g. WM_MOUSEMOVE, WM_KEYDOWN) are processed after posted messages. Timer messages specifically are processed after input and paint messages. This means that your application will respond to user events and paint requests before it handles the next WM_TIMER message. You can harness this behavior by using a Timer (and it's WM_TIMER message), rather than posting a message yourself (which would always take priority over paint and input messages). When timers fire they send a WM_TIMER message. This message will always be handled after any input and paint messages; making your application appear responsive. The other upside of setting a timer is that it forces you to "queue up" all the items you have processed in a (thread safe) list. You combine a few thousand work items into one "timer", saving the system from having to generate and process thousands of needless messages. Bonus Chatter ...messages are processed in the following order: * *Sent messages *Posted messages *Input (hardware) messages and system internal events *Sent messages (again) *WM_PAINT messages *WM_TIMER messages Update: You should not have a timer polling, that's just wasteful and wrong. Your threads should "set a flag" (i.e. the timer). This allows your main thread to actually go idle, only waking when there is something to do. Update Two: Pseudo-code that demonstrates that order of message generation is not preserved: //Code is public domain. No attribution required. const WM_ProcessNextItem = WM_APP+3; procedure WindowProc(var Message: TMessage) begin case Message.Msg of WM_Paint: PaintControl(g_dc); WM_ProcessNextItem: begin ProcessNextItem(); Self.Invalidate; //Invalidate ourselves to trigger a wm_paint //Post a message to ourselves so that we process the next //item after any paints and mouse/keyboard/close/quit messages //have been handled PostMessage(g_dc, WM_ProcessNextItem, 0, 0); end; else DefWindowProc(g_dc, Message.Msg, Message.wParam, Message.lParam); end; end; Even though i generate a WM_ProcessNextItem after i generate a WM_PAINT message (i.e. Invalidate), the WM_PAINT will never get processed, because there is always another posted message before it. And as MSDN says, paint messages will only appear if there are no other posted messages. Update Three: Yes there is only message queue, but here's why we don't care: Sent and posted messages The terminology I will use here is nonstandard, but I'm using it because I think it's a little clearer than the standard terminology. For the purpose of this discussion, I'm going to say that the messages associated with a thread fall into three buckets rather than the more standard two: What I'll call them Standard terminology =========================== ============================= Incoming sent messages Non-queued messages Posted messages \_ Input messages / Queued messages In reality, the message breakdown is more complicated than this, but we'll stick to the above model for now, because it's "true enough." The Old New Thing, Practical Development Throughout the Evolution of Windows by Raymond Chen ISBN 0-321-44030-7 Copyright © 2007 Pearson Education, Inc. Chapter 15 - How Window Messages Are Delivered and Retrieved, Page 358 It's easier to imagine there are two message queues. No messages in the "second" one will be read until the "first" queue is empty; and the OP is never letting the first queue drain. As a result none of the "paint" and "input" messages in the second queue are getting processed, making the application appear to hang. This is a simplification of what actually goes on, but it's close enough for the purposes of this discussion. Update Four The problem isn't necessarily that you are "flooding" the input queue with your messages. Your application can be unresponsive with only one message. As long as you have one posted message in the queue, it will be processed before any other message. Imagine a series of events happen: * *Mouse is moved (WM_MOUSEMOVE) *Mouse left button is pushed down (WM_LBUTTONDOWN) *Mouse left button is released (WM_LBUTTONUP) *The user moves another window out of the way, causing your app to need to repaint (WM_PAINT) *Your thread has an item ready, and Posts a notification (WM_ProcessNextItem) Your application's main message loop (which calls GetMessage) will not receive messages in the order in which they happened. It will retrieve the WM_ProcessNextItem message. This removes the message from the queue, leaving: * *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_PAINT While you process your item the user moves the mouse some more, and clicks randomly: * *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_PAINT *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP In response to your WM_ProcessNextItem you post another message back to yourself. You do this because you want to process the outstanding messages first, before continuing to process more items. This will add another posted message to the queue: * *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_PAINT *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_ProcessNextItem The problem starts to become apparent. The next call to GetMessage will retrieve WM_ProcessNextItem, leaving the application with a backlog of paint and input messages: * *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_PAINT *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP *WM_MOUSEMOVE *WM_MOUSEMOVE *WM_LBUTTONDOWN *WM_LBUTTONUP The solution is to take advantage of the out-of-order processing of messages. Posted messages are always processed before Paint/Input/Timer messages: don't use a posted message. You can think of the message queue as being divided into two groups: Posted messages and Input messages. Rather than causing the situation where the "Posted" messages queue is never allowed to empty: Posted messages Input messages ================== ===================== WM_ProcessNextItem WM_MOUSEMOVE WM_LBUTTONDOWN WM_LBUTTONUP WM_PAINT You an use a WM_TIMER message: Posted messages Input messages ================== ===================== WM_MOUSEMOVE WM_LBUTTONDOWN WM_LBUTTONUP WM_PAINT WM_TIMER Nitpickers Corner: This description of two queues isn't strictly true, but it's true enough. How Windows delivers messages in the documented order is an internal implementation detail, subject to change at any time. It's important to note that you're not polling with a timer, that would be bad™. Instead you're firing a one-shot timer as a mechanism to generate a WM_TIMER message. You're doing this because you know that timer messages will not take priority over paint or input messages. Using a timer has another usability advantage. Between WM_PAINT, WM_TIMER, and input messages, there is out-of-order processing to them as well: * *input messages, then *WM_PAINT, then *WM_TIMER If you use a timer to notify your main thread, you can also be guaranteed that you will process paint and user input sooner. This ensures that your application remains responsive. It's a usability enhancement and you get it for free. A: Instead of posting messages, you can put messages in a thread safe queue. In your main thread, use a timer event to drain the queue. To remain responsive though, do not stay in the timer event too long. In many cases I have found this better than posting messages. In Delphi XE there is a class called TThreadedQueue which you can use. Edit : I uploaded a sample sort application utilizing different thread to GUI techniques. See ThreadedQueueDemo A: I have done this many times. Have the posted message from the threads update a "cache" on the main form. Have a timer on the main form (set to around 100 ms, or less if you need to) update the main form from the cache. This way the amount of work done per posted message is very small, so the application will spend less time processing and your application will appear "responsive". A: You can create a new thread for updating logs and in the log threads call TLogThread.Synchronize to update the UI controls that are in the main app thread... or just call TWorkerThread.Synchronize to update the logs from your worker threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Glassfish instead of WebLogic for Oracle Forms 11g application Is it possible to use Glassfish instead of WebLogic for Oracle Forms 11g application? Is there any container/plugin/whatever for Glassfish to use with Oracle Forms 11g? Both Glassfish and WebLogic are J2EE servers, so...? A: Oracle 11g applications are not certified on GlassFish Server, so you definitely would not have a supported configuration, and I highly doubt it would technically work without some porting effort by Oracle. For example, no JRF layer exists for GlassFish.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I access the read permissions for built in verticals? According to http://developers.facebook.com/docs/beta/authentication/read/, I can prompt a user for the permission "user_actions.music" and have access to their actions on the open graph. I've enabled the Enhanced Auth Dialog setting on my test app but am receiving an invalid parameter error when I try to prompt a user for that permission. I've also tried prompting the user for "user_actions" and experience the same error. Is this permission not active yet, even though I'm a developer or am I asking for this permission incorrectly? A: The Open Graph isn't live to users yet. Only developers of your app should be able to grant these permissions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CCNet web dashboard scripts being passed as text/plain My web dashboard for cruisecontrol.net seems to be rendering incorrectly. I am getting mostly java-script errors and I'm unsure why this is happening. Most of the errors are like this: Resource interpreted as Script but transferred with MIME type text/plain. There are other errors present but I believe this is caused by the scripts being interpreted incorrectly. Does anyone know why this could be happening? A: This was a configuration error with IIS. The static content role service had not been installed. After doing so MIME types are now being delivered correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nginx, fastcgi and open sockets I'm experimenting using fastcgi on nginx, but I've run into some problems. Nginx doesn't reuse connections, it gives 0 in BeginRequest flags, so the application should close the connection after the request has finished. I have the following code for closing: socket.shutdown(SocketShutdown.BOTH); socket.close(); The problem is that the connections are not actually closed.. They linger on as TIME_WAIT, and nginx (or something) wont't keep opening new connections. My guess is I'm doing something wrong when closing the sockets, but I don't know what.. On a related note - how can I get nginx to keep connections open? This is using nginx 1.0.6 and D 2.055 EDIT: Haven't gotten any closer, but I also checked the linger option, and it's off: linger l; socket.getOption(SocketOptionLevel.SOCKET, SocketOption.LINGER, l); assert(l.on == 0); // off getOption returns 4 though.. No idea what that means. The return value is undocumented. EDIT: I've also tried using TCP_NODELAY on the last message sent, but this didn't have any effect either: socket.setOption(SocketOptionLevel.SOCKET, SocketOption.TCP_NODELAY, 1); EDIT: nginx 1.1.4 supportes keep alive connections. This doesn't work as expected though.. Is correctly report that the server is responsible for connection lifetime management, but it still creates a new socket for each request. A: NGINX proxy keepalive Regarding nginx (v1.1) keepalive for fastcgi. The proper way to configure it is as follows: upstream fcgi_backend { server localhost:9000; keepalive 32; } server { ... location ~ \.php$ { fastcgi_keep_conn on; fastcgi_pass fcgi_backend; ... } } TIME_WAIT TCP TIME_WAIT connection state has nothing to do with lingers, tcp_no_delays, timeouts, and so on. It is completely managed by the OS kernel and can only be influenced by system-wide configuration options. Generally it is unavoidable. It is just the way TCP protocol works. Read about it here and here. The most radical way to avoid TIME_WAIT is to reset (send RST packet) TCP connection on close by setting linger=ON and linger_timeout=0. But doing it this way is not recommended for normal operation as you might loose unsent data. Only reset socket under error conditions (timeouts, etc.). What I would try is the following. After you send all your data call socket.shutdown(WRITE) (this will send FIN packet to the other party) and do not close the socket yet. Then keep on reading from the socket until you receive indication that the connection is closed by the other end (in C that is typically indicated by 0-length read()). After receiving this indication, close the socket. Read more about it here. TCP_NODELAY & TCP_CORK If you are developing any sort of network server you must study these options as they do affect performance. Without using these you might experience ~20ms delays (Nagle delay) on every packet sent over. Although these delays look small they can adversely affect your requests-per-second statistics. A good reading about it is here. Another good reference to read about sockets is here. About FastCGI I would agree with other commenters that using FastCGI protocol to your backend might not be very good idea. If you care about performance then you should implement your own nginx module (or, if that seems too difficult, a module for some other server such as NXWEB). Otherwise use HTTP. It is easier to implement and is far more versatile than FastCGI. And I would not say HTTP is much slower than FastCGI. A: Hello simendsjo, The following suggestions might be completely off target. I use NginX myself for development purposes; however, I’m absolutely not an expert on NginX. NginX Workers Nevertheless, your problem brought back to memory something about workers and worker processes in NginX. Among other things, the workers and worker processes in NginX, are used to decrease latency when workers blockend on disk I/O and to limit number of connections per process when select()/poll() is used. You can find more info here. NginX Fcgiwrap and socket Another pointer might be the following code, although this example is specific for Debian. #!/usr/bin/perl use strict; use warnings FATAL => qw( all ); use IO::Socket::UNIX; my $bin_path = '/usr/local/bin/fcgiwrap'; my $socket_path = $ARGV[0] || '/tmp/cgi.sock'; my $num_children = $ARGV[1] || 1; close STDIN; unlink $socket_path; my $socket = IO::Socket::UNIX->new( Local => $socket_path, Listen => 100, ); die "Cannot create socket at $socket_path: $!\n" unless $socket; for (1 .. $num_children) { my $pid = fork; die "Cannot fork: $!" unless defined $pid; next if $pid; exec $bin_path; die "Failed to exec $bin_path: $!\n"; } You can find more information about this solution here. A: Set the socket timeout as low as it can go and then close the socket. If you try to write anything to the socket after that what happens? It is possible to push unescaped binary to signal a close connection through, forcing it to end. That's how IE became known as Internet Exploder
{ "language": "en", "url": "https://stackoverflow.com/questions/7616601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: replace the class with new class without keeping the Newclass same where ever we are taking that from I want to replace the code with new code. I used replaceWith to replace the function.But it removes the new class from where it was before . I want that class to stay in where ever it was before and need to replace the another class. How to do it?? Ex: $('.popinner').insertAfter($('.rContentPopUp')); when I do this".rContentPopUp" is replacing the 'popinner' class. BUt ".rContentPopUp" was removed from old structure where ever it was there. A: In jQuery you can pass a class name to the removeClass function eg... $('#element name').removeClass('classToRemove'); doing this will just remove that class from the element leaving all existing classes. Then you can simply call addClass to add in your new class. I believe this is what you want to do?
{ "language": "en", "url": "https://stackoverflow.com/questions/7616608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Javascript to pull the url of a hyperlink with a class attribute There will be only one link of a particular class on the page. I'm trying to write a javascript snippet that will find this: <a href="http://www.stackoverflow.com" class="linkclass"> ... </a> and return a string consisting of this: http://www.stackoverflow.com Thanks in advance everyone. A: Try the following var url = (function() { var all = document.getElementsByTagName("a"); for (var i in all) { var cur = all[i]; if (cur.getAttribute('class') === "linkclass") { return cur.getAttribute('href'); } } return undefined; })(); Note: If there is only ever one element of that class it would be much more efficient to give the element a unique id instead of a class. The code would then be much simpler var url = document.getElementById('theUniqueId').getAttribute('href'); A: If there will be only one instance of a particular class then use an id and grab them with document.getElementById("linkID").href; If you can't do that then using the classes: var links = document.getElementsByTagName("a"); var ref = ""; for(var i = 0; i < links.length; i++) { if(links[i].className == "linkClass") { ref = links[i].href; break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reassign key bindings in emacs to run cscope I'm trying to install xcscope for xemacs on my linux machine at work. Unfortunately emacs is pre-configured to install some of my work related .el files. Because of this the "C-c s" prefix doesnt work for cscope, since its bound to printing my company logo. I have currently put (define-key global-map "\C-cs" nil) so that it atleast doesn't print my company logo. But when I try to use it for any cscope commands it doesn't do anything. This is a copy of my .emacs file: (load-library "Company_XXXXX") (define-key global-map "\C-cs" nil) (load-file "/usr/share/emacs/site-lisp/xcscope.el") (require 'xcscope) I tried to check the reverse so when I do a "C-h w: cscope-find-this-file" to check what its bound to, it keeps telling me "cscope-find-this-file is not on any key". Is there any way in which i can tell emacs to bind "C-c s" to cscope ? A: Have you enabled the minor-mode? M-x cscope-minor-mode The library adds some hooks to enable the minor-mode but it's not clear where you are trying to run this. Also, this has nothing to do with your global-map. The minor-mode should override the global binding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to do generic division without raising exception I want to do safe division for any type T, which I don't want to raise CPU/FPU exception, for example if a float is divided by zero it should return infinity (+/-INF). Should I write my own function? or is there any standard C++ function that I can use? if I need to write my own function, does this function is right? template<typename T> bool isSameSign(const T& a, const T& b) { return ((((a)<0)==((b)<0))&&(((a)>0)==((b)>0))); } template<typename T> T safeDiv (const T& lhs, const T& rhs) { if(std::abs(rhs) > std::numeric_limits<T>::epsilon) { if(std::abs(lhs) > std::numeric_limits<T>::epsilon) { return lhs/rhs; } else { return std::numeric_limits<T>::quiet_NaN(); } } else if(isSameSign<T>(lhs,rhs)) { return std::numeric_limits<T>::infinity(); } else { return -std::numeric_limits<T>::infinity(); } } A: If a float is divided by zero, mathematically speaking, it is undefined, not infinity. The reason is the law of limits. As you divide by a smaller and smaller number greater than zero, you tend to approach positive infinity, and as you divide by a smaller and smaller negative number you tend toward negative infinity.... On a number line those are opposites, and you can't define one thing as both of those opposites. The function 1/x is therefore undefined at 0. Returning negative or positive infinity would be incorrect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: height vs line-height styling What is the difference between using these two when dealing with text that will never be more than a single line? They both can produce similar results on the screen from what I can see in regards to the elements on top or on the bottom of the element. Why use line-height at all if so? Height would make more sense to use. Edit: An example of this a stylized button created from a div with text inside. This will never be multiline. So would line-height be needed for compatibility reasons? or anything I don't know about? Thanks! A: height is the vertical measurement of the container. line-height is the distance from the top of the first line of text to the top of the second. If used with only one line of text I'd expect them to produce similar results in most cases. I use height when I want to explicitly set the container size and line-height for typographic layout, where it might be relevant if the user resizes the text. A: If you wrap the text in a div, give the div a height, and the text grows to be 2 lines (perhaps because it is being viewed on a small screen like a phone) then the text will overlap with the elements below it. On the other hand, if you give the div a line-height and the text grows to 2 lines, the div will expand (assuming you don't also give the div a height). Here is a fiddle that demonstrates this. A: Assuming the text is smaller than the container: Setting the line-height on the container specifies the minimum height of line-boxes inside it. For 1 line of text, this results in the text vertically centered inside the container. If you set height on the container then the container will grow vertically, but the text inside it will start on the first (top) line inside it. A: height = line-height + padding-top + padding-bottom A: For practical purposes in the case you cite (never wrapping to more than one line) line-height will vertically center the text. Be careful about that assumption though as the user ultimately controls the font-size. A: Easily understand by seeing this example. .height { height: 20px; } .lheight { line-height: 15px; } .lheightbigger { line-height: 35px; } <h2>Height</h2> <div class="height"> This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. This is demo text. </div><br> <h2>Line Height with less space</h2> <div class="lheight"> This is demo text showing line height example. This is demo text showing line height example. This is demo text showing line height example. This is demo text showing line height example. This is demo text showing line height example.This is demo text showing line height example. </div> <h2>Normal Text</h2> <div> This is normal text. This is normal text. This is normal text. </div> <h2>Line Height with more space</h2> <div class="lheightbigger"> This is normal text. This is normal text.This is normal text. This is normal text. This is normal text.This is normal text. This is normal text. This is normal text.This is normal text. </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7616618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Stactic Analyizer Memory Leak Warning for UISwitch I have the following code where each object is a UISwitch IBOutlet property. I'm nor sure why I am getting a memory leak warning for each line when using xcode analyzer. - (IBAction)copyEntirePreviousNoteButtonClicked:(id)sender { self.myUISwitch1.on = TRUE; self.myUISwitch2.on = TRUE; } - (IBAction)updateButtonClicked:(id)sender { NSMutableDictionary *copyOptions = [[[NSMutableDictionary alloc] init] autorelease]; if (self.myUISwitch1.on) { [copyOptions setValue:@"ON" forKey:@"myUISwitch1"]; } if (self.myUISwitch2.on) { [copyOptions setValue:@"ON" forKey:@"myUISwitch2"]; } } Update with full code: @property (nonatomic, retain) IBOutlet UISwitch *copy_hp_cchpi; @property (nonatomic, retain) IBOutlet UISwitch *copy_hp_history; - (IBAction)copyEntirePreviousNoteButtonClicked:(id)sender { self.copy_hp_cchpi.on = YES; self.copy_hp_history.on = TRUE; } - (IBAction)updateButtonClicked:(id)sender { NSMutableDictionary *copyOptions = [[[NSMutableDictionary alloc] init] autorelease]; if (self.copy_hp_cchpi.on) { [copyOptions setValue:@"ON" forKey:@"copy_hp_cc_history_present_illness"]; } if (self.copy_hp_history.on) { [copyOptions setValue:@"ON" forKey:@"copy_hp_med_fam_social_history"]; } int rcode = [MyAPIDataSource copyPreviewAppointmentClinicalInfo:[MyAPIDataSource getCurrentAppointmentId] copyOptions:copyOptions]; if (rcode) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to copy last appointment information. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } else { //Send Notifications to other screens that clinical info was copied from last appointment to current one. [[NSNotificationCenter defaultCenter] postNotificationName:@"LastAppointmentLoadedHandler" object:self]; [self dismissModalViewControllerAnimated:YES]; } } A: After a lot of head scratching... By convention, any Objective C method that contains the word 'copy' is expected to return a retained object. The same applies for the method prefixes 'init' and 'new'. The static analyzer knows about this convention and is complaining that your copyEntirePreviousNoteButtonClicked method does not return a retained object. The solution is not to name your methods containing the word 'copy' unless you really mean it. Stick to the Objective C method naming conventions. Change the name of your method and the problem will go away.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update Android kernel with zImage? I have changed Android kernel settings and re-built it. I was trying to replace the original kernel installed on my device(Galaxy Tab 7.0) to the new kernel I built. I have zImage on my host machine and I have sdcard in my device. Thanks in advance..
{ "language": "en", "url": "https://stackoverflow.com/questions/7616625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: working out geoloction lat long Given a shape not just a circle or a square or triangle, but a shape with any number of edges, if the shape were to be drawn on a map how would I find if Lat long coordinates where within that shape? A: wikipedia to the rescue. Describes solution in the Cartesian plane but that could be transferred to lat/long...
{ "language": "en", "url": "https://stackoverflow.com/questions/7616627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generating mip levels for a 2D texture array I've got a simple (I think) question about OpenGL texture arrays. I create my texture array with something like the following: glTexImage3D( GL_TEXTURE_2D_ARRAY, 0, formatGL, width, height, slices, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); Note that I don't want to actually load any images into it yet. I'm just creating the structure that I'll be filling with data later on. So my questions are: * *How do I generate the mip chain for each "slice" of the texture array? I don't want to physically generate the mip, I just want to complete the texture by telling it about the mip. I can do this with 2D textures simply by calling the glTexImage2D function with the mip level, size and also passing in a nullptr. I can't see how to do this with the glTexImage3D function given there's no "slice" parameter. The OpenGL superbible example only loads a .bmp into the first mip level for each texture in the array. Is it correct to say that using glTexSubImage3D, passing in a nullptr, will create the mip level I want for a given texture in the array? *Documentation at khronos.org on glGenerateMipMap specifies GL_TEXTURE_2D or GL_TEXTURE_CUBE_MAP only. So is it correct to say I can't use this method for 2D texture arrays? Here's what I do with 2D textures to create the mip chain: size_t i = 0, mipSizeX = width, mipSizeY = height; while(mipSizeX >= 1 || mipSizeY >= 1) { // Generate image for this mip level glTexImage2D( GL_TEXTURE_2D, i, formatGL, mipSizeX, mipSizeY, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); // Go to the next mip size. mipSizeX >>= 1; mipSizeY >>= 1; // and the next mipmap level. i++; } A: I can do this with 2D textures simply by calling the glTexImage2D function with the mip level, size and also passing in a nullptr. I can't see how to do this with the glTexImage3D function given there's no "slice" parameter. Why not? glTexImage3D takes a mipmap level, just like glTexImage2D. It takes a size, which in 2D is two dimensions, but in 3D is three dimensions. Indeed, the only difference between the two functions is the number of dimensions that they take (and therefore the possible target parameters). And there is a "slice" parameter; you used it with glTexImage3D in the call you showed us. There, it's called depth. The difference between 3D textures and 2D array textures is that the depth does not change in lower mipmaps for 2D arrays. Each mipmap of the array has the same number of "slices" as every other mipmap. Documentation at khronos.org If it's at "khronos.org" and not "opengl.org", then it's almost certainly talking about OpenGL ES, which does not have array textures (later note: ES 3.0 added array textures). I honestly don't know how to be any clearer without actually writing your code for you. size_t i = 0, mipSizeX = width, mipSizeY = height; while(mipSizeX >= 1 || mipSizeY >= 1) { // Generate image for this mip level glTexImage3D( GL_TEXTURE_2D_ARRAY, i, formatGL, mipSizeX, mipSizeY, arrayCount, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); // Go to the next mip size. mipSizeX >>= 1; mipSizeY >>= 1; // and the next mipmap level. i++; } Also, you need to check that the mipmap sizes have a minimum value of 1. Because (1 >> 1) == 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I map table inheritance in a legacy database? I am finding it very difficult to map a legacy database. Here is the scenario: A contractor applies for a new license. The license is queried and displayed. The contractor modifies any information that needs to be modified. And upon completion an application is saved to the database. A license belongs to either a business or an owner, this is a one to any polymorphic association. The License itself holds a TableID and RecordID that are used to make the association. Licenses have many Applications. There are several types of Applications in this System, so there is an "ApplicationCommon" table and an "LicenseApplication" table. This particular application is a for a license. The ApplicationCommon and The LicenseApplication share the same primary key. In other words the ApplicationCommon id is the same and the LicenseApplication id. So this is table inheritance (or so I think). Because of the weird polymorphic association with the business, I have to query for the business data separately from the license (Or so I think, kind of new to nHibernate). Once I have the license and the business I try to make a new application, that is when the system fails. Here is the exception that I get: "object references an unsaved transient instance - save the transient instance before flushing. Type: LicenseApplication, Entity: LicenseApplication" Here are the mappings: public LicenseApplicationMap() { Table("Applications_LicenseApplication"); Id(x => x.ID).Column("intApplicationID").Not.Nullable(); Map(x => x.TableID).Column("intTableID").Nullable(); Map(x => x.RecordID).Column("intRecordID").Nullable(); References(x => x.Type).Column("intLicenseTypeID").Not.Nullable(); Map(x => x.InsuranceExpiresOn).Column("dtInsuranceExpiresOn"); Map(x => x.WCInsuranceExpiresOn).Column("dtWCInsuranceExpiresOn"); Map(x => x.Updated).Column("dtUpdated"); Map(x => x.AuthorizedRepresentativeFirstName).Column("strAuthRepFirstName"); Map(x => x.AuthorizedRepresentativeLastName).Column("strAuthRepLastName"); Map(x => x.AuthorizedRepresentativeGreeting).Column("strAuthRepGreeting"); HasOne(x => x.ApplicationCommon).ForeignKey("intApplicationID").Cascade.All(); References(x => x.License).Column("intLicenseID"); HasMany(x => x.Officers).KeyColumn("intApplicationID"); HasMany(x => x.Designees).KeyColumn("intApplicationID"); } . public LicenseCommonMap() { Table("Licensing_LicenseCommon"); Id(x => x.ID).Column("intLicenseID").Not.Nullable(); Map(x => x.TableID).Column("intTableID").Nullable(); Map(x => x.RecordID).Column("intRecordID").Nullable(); Map(x => x.LicenseNumber).Column("strNumber"); References(x => x.Type).Column("intLicenseTypeID").Not.Nullable(); References(x => x.Status).Column("intLicenseStatusID").Not.Nullable(); Map(x => x.StartsOn).Column("dtStartsOn"); Map(x => x.EndsOn).Column("dtEndsOn"); Map(x => x.CreatedOn).Column("dtCreatedOn"); Map(x => x.RenewedOn).Column("dtRenewedOn"); Map(x => x.InsuranceExpiresOn).Column("dtInsuranceExpiresOn"); Map(x => x.WorkmansCompensationExpiresOn).Column("dtWCInsuranceExpiresOn"); Map(x => x.LastUpdated).Column("dtLastUpdated"); HasMany(x => x.Applications).KeyColumn("intLicenseID"); } . public ApplicationCommonMap() { Table("Applications_ApplicationCommon"); Id(x => x.ID).Column("intApplicationID"); References(x => x.Type).Column("intApplicationTypeID"); References(x => x.Status).Column("intApplicationStatusID"); References(x => x.LicenseApplication).Column("intApplicationID").Cascade.All(); } . public BusinessMap() { Table("Core_Business"); Id(x => x.ID).Column("intBusinessID").GeneratedBy.Identity(); Map(x => x.BusinessName).Column("strBusinessName").Not.Nullable(); Map(x => x.PhoneNumber).Column("strPhoneNumber").Not.Nullable(); Map(x => x.FaxNumber).Column("strFaxNumber").Not.Nullable(); Map(x => x.EmailAddress).Column("strEmailAddress").Not.Nullable(); Map(x => x.YearOrganized).Column("strYearOrganized").Not.Nullable(); Map(x => x.LastUpdated).Column("dtLastUpdated").Not.Nullable(); Map(x => x.PhysicalAddr1).Column("strPhysicalAddr1").Not.Nullable(); Map(x => x.PhysicalAddr2).Column("strPhysicalAddr2").Nullable(); Map(x => x.PhysicalCity).Column("strPhysicalCity").Not.Nullable(); Map(x => x.PhysicalState).Column("strPhysicalState").Not.Nullable(); Map(x => x.PhysicalCountry).Column("strPhysicalCountry").Not.Nullable(); Map(x => x.PhysicalZip).Column("strPhysicalZip").Not.Nullable(); Map(x => x.MailingAddr1).Column("strMailingAddr1").Not.Nullable(); Map(x => x.MailingAddr2).Column("strMailingAddr2").Nullable(); Map(x => x.MailingCity).Column("strMailingCity").Not.Nullable(); Map(x => x.MailingState).Column("strMailingState").Not.Nullable(); Map(x => x.MailingCountry).Column("strMailingCountry").Not.Nullable(); Map(x => x.MailingZip).Column("strMailingZip").Not.Nullable(); } And finally, I am using .Net MVC, AutoMapper and S#rpArch, so here is my controller action, and my query. SaveLicense and SaveQuery bother perform the same logic, SaveOrUpdate, then Flush. [HttpPost] [Transaction] public ActionResult Edit(int id, LicenseViewModel applicationData) { // 1. Get the current license. var license = _licenseService.GetLicenseCommon(id); // 2. Make changes to license that where made during application process Mapper.Map<LicenseViewModel , LicenseCommon>(applicationData, license); var business = _licenseService.GetBusiness(license.RecordID); Mapper.Map<LicenseViewModel , Business>(applicationData, business); business.LastUpdated = DateTime.Now; // 3. Create a new application and add it to the license var application = new LicenseApplication(); Mapper.Map<LicenseViewModel , LicenseApplication>(applicationData, application); application.Updated = DateTime.Now; application.InsuranceExpiresOn = DateTime.Parse(applicationData.GeneralLiabilityExpiration); application.WCInsuranceExpiresOn = DateTime.Parse(applicationData.WorkmansCompensationExpiration); application.TableID = 33; application.RecordID = license.RecordID; // 4. Save the license and it's applications to the database. license.Business = business; //Don't think this works at all... license.Applications.Add(application); application.License = license; ///////////////// BOOM THIS IS WHERE IT BLOWS UP ////////////////////// _licenseService.SaveLicense(license); _businessService.SaveBusiness(business); // 5. Convert the modified license and it's newly created application to an LicenseViewModel Mapper.Map<LicenseCommon, LicenseViewModel >(license, applicationData); // 6. return json or error message return Json(applicationData); } Please tell me what is wrong with my mappings. A: HasMany(x => x.Applications).KeyColumn("intLicenseID"); is missing a .Cascade.All() so saving the license also saves changes to Applications. And .Inverse would be good too to tell NH that Application is responsible for the association. And also // class LicenseCommon public void Add(LicenseApplication application) { application.License = license; application.TableID = 33; application.RecordID = license.RecordID; Applications.Add(application); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby on Rails 3: How to access an attribute of each record in a has_many query I wasn't sure how to phrase it in the title, but what I'm trying to do the following. I have 2 models that have the following relationships: class Campaign < ActiveRecord::Base has_many :points end class Point < ActiveRecord::Base belongs_to :campaign end Now, the Point model has a "locale" attribute and I want to be able to put all the "locales" of every point of a specific campaign into an array, or collection, or whatever without having to do something like locales = Array.new campaign.points.each do |p| locales << p.locale end I was thinking of something along the lines of campaign.points.locales. Is there some nice Rails way of doing this query, or do I just have to iterate over the collection? Thanks for any help. EDIT: Also because the relationship is actually a "has_many through" relationship, this method doesn't work, as I get many repeated locales if I try to iterate in that simple way. It sounds like it should be some type of join, but I'm not sure. A: I'd do: campaign.points.map(&:locale) A: campaign.points.map {|p| p.locale} should do the trick. A: You could do what those guys said. Put a .uniq at the end of them and end up with the correct solution, or; let me lead you astray with ActiveRecord fun (and possibly failure, since I can't test to see if it works here). But you'll be able to run campaign.points.locales just like you wanted. class Campaign < ActiveRecord::Base has_many :points do def locales select('DISTINCT(locale)').map(&:locale) end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7616643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Parameter is not type-compatible with formal parameter when method is called from FM A static public class method, zcl_abc=>dosomething, has an importing parameter it_lines type TLINE_T optional And there is a FM called zfm_dosame. It has a parameter TABLES IT_LINES TYPE TLINE_T OPTIONAL zfm_dosame calls zcl_abc=>dosomething and tries to pass it_lines to it_lines. However, syntax error: IT_LINES is not type-compatible with formal parameter IT_LINES. This error drives me crazy. I have no idea how come... Please help! A: The TABLES part of a function interface creates internal tables with header line at runtime. So in order to pass the entire table, instead of just one work area, you should pass IT_LINES[] instead of IT_LINES to the method you're calling. A: It is difficult to tell without more information like the full source code of your function module, function group, and class, but I'll take a guess: Most likely your type TLINE_T is not a global type, but is instead defined locally (and differently) in both the function group of the function module and in the class. Try double-clicking on the type TLINE_T in both places and see where that brings you. If it brings you to a global type (which you should also be able to see in SE11) in both places, then I'm wrong and there is something else going on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Tooltip with jquery and css How can make a tooltip with jquery and css for following HTML? (i mean, this is that when mouse enter on li a displaying content class show_tooltip) <ul> <li> <a href="#">about</a> <div class="show_tooltip"> put returns between paragraphs </div> </li> <li> <a href="#">how</a> <div class="show_tooltip"> for linebreak add 2 spaces at end </div> </li> </ul> A: $("li a").mouseover(function(){ $(this).next().fadeIn(); }) $("li a").mouseout(function(){ $(this).next().fadeOut(); }) A: why not just do this? :) <ul> <li> <a href="#" title="put returns between paragraphs">about</a> </li> <li> <a href="#" title="for linebreak add 2 spaces at end">how</a> </li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/7616654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: UIView transitionWithView doesn't work Here is viewDidLoad from the main view controller in the test project: - (void)viewDidLoad { [super viewDidLoad]; UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 300)]; [self.view addSubview:containerView]; UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]; [redView setBackgroundColor:[UIColor redColor]]; [containerView addSubview:redView]; UIView *yellowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]; [yellowView setBackgroundColor:[UIColor yellowColor]]; [UIView transitionWithView:containerView duration:3 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{ [redView removeFromSuperview]; [containerView addSubview:yellowView]; } completion:NULL]; } The yellow box just appears. There is no animation, no matter which UIViewAnimationOption I try. Why??? EDIT: I've also tried using performSelector withDelay to move the animation out of viewDidLoad and into another method. Same result - no animation. Also tried this: [UIView transitionFromView:redView toView:yellowView duration:3 options:UIViewAnimationOptionTransitionFlipFromLeft completion:NULL]; Still, the yellow view just appears. No animation. A: After some testing it appears that you cannot create the container view and set up the animation within the same runloop and have things work. In order to make your code work, I first created the containerView and the redView in the viewDidLoad method. Then I put your animation into the viewDidAppear method. So that I could reference the containerView and the redView from the viewDidAppear method, I made them properties. Here is the code for an ST_ViewController.m file that will perform the animation you wanted. @interface ST_ViewController () @property (nonatomic, strong) UIView *containerView; @property (nonatomic, strong) UIView *redView; @end @implementation ST_ViewController - (void)viewDidLoad { [super viewDidLoad]; [self setContainerView:[[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 300)]]; [[self view] addSubview:[self containerView]]; [self setRedView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]]; [[self redView] setBackgroundColor:[UIColor redColor]]; [[self containerView] addSubview:[self redView]]; } -(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; UIView *yellowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]; [yellowView setBackgroundColor:[UIColor yellowColor]]; [UIView transitionWithView:[self containerView] duration:3 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^(void){ [[self redView] removeFromSuperview]; [[self containerView] addSubview:yellowView]; } completion:nil]; } @end A: Don't put this in viewDidLoad. viewDidLoad is called when the view is fully loaded into memory, but not yet displayed on screen. Try putting the above code in viewDidAppear: which is called when the view has appeared on screen. Edit: a side note, if performSelector:withDelay: fixes something, that means you're trying to do that thing wrong. You need to refactor somehow. performSelector:withDelay: is the wrong way to solve problems 99.999% of the time. As soon as you place this code on a different speed device (new iPhone, old iPhone) it will mess up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: TableLayout not shrink all images I am trying to to create a table of 8x5 images as: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TableLayout table = new TableLayout(this); table.setStretchAllColumns(true); table.setShrinkAllColumns(true); for(int i = 0; i < 6; i++){ TableRow card = new TableRow(this); card.setGravity(Gravity.CENTER); for(int j = 0; j < 5; j++){ TableRow.LayoutParams paramsCard = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); paramsCard.setMargins(CARDS_MARGIN,CARDS_MARGIN,CARDS_MARGIN,CARDS_MARGIN); ImageView imgCard = new ImageView(this); imgCard.setImageResource(R.drawable.dos); imgCard.setLayoutParams(paramsCard); card.addView(imgCard); } table.addView(card); } setContentView(table); table.setBackgroundDrawable(getResources().getDrawable(R.drawable.background)); } But in the last row I get the images smaller, why? I apparently set table.setStretchAllColumns(true); table.setShrinkAllColumns(true); http://dl.dropbox.com/u/3340490/device-2011-10-01-002223.png A: I bet you, your TableView is in a LinearLayout or something which wouldn't overflow of the available screen - so the last views are shrunk to have everything fit in there - maybe... Can you make sure your TableView is in a ScrollView and see if this happens? -serkan A: If u have given the Margin or padding to the Outer Layout which is parent of the TableLayout, then set it. It will happend sometimes just because u have given some marginn and some padding to the Parent layout of the TableLayout. Hope it will help you. Thanks. A: Eventually I use a LinearLayout with the weigths set to 1 to auto adjust to the screen size. TableLayout doesnt work very well at adjusting images.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fit two divs side by side horizontally? How to sit two divs side by side horizontally using css, where the direction of the container DIV is from right to left ? A: <div style="float:right;"> Right div </div> <div> Left div </div> A: <div style="width:960px;overflow:hidden;"> <div style="float:right;width:600px;overflow:hidden;"> //right DIV </div> <div style="float:right;width:360px;overflow:hidden;"> //left DIV </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7616663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Google Maps API v3: Custom styles for infowindow I've tried many of the examples from the google maps reference and from other stackoverflow questions, but I haven't been able to get custom styles on my infowindow. I am using something very similar to what was done in this other stackoverflow answer Here it is working/editable: http://jsfiddle.net/3VMPL/ In particular, I would like to have square corners instead of the rounded. A: If you can't use infobox and need to customise the infowindow you can access it using css. It's not pretty, relies heavily on first:child/last:child psuedo selectors and obviously on whether google ever decides to change their map html structure. Hopefully the below css can help someone else out in a bind when they're forced to deal with infowindow. /* white background and box outline */ .gm-style > div:first-child > div + div > div:last-child > div > div:first-child > div { /* we have to use !important because we are overwritng inline styles */ background-color: transparent !important; box-shadow: none !important; width: auto !important; height: auto !important; } /* arrow colour */ .gm-style > div:first-child > div + div > div:last-child > div > div:first-child > div > div > div { background-color: #003366 !important; } /* close button */ .gm-style > div:first-child > div + div > div:last-child > div > div:last-child { margin-right: 5px; margin-top: 5px; } /* image icon inside close button */ .gm-style > div:first-child > div + div > div:last-child > div > div:last-child > img { display: none; } /* positioning of infowindow */ .gm-style-iw { top: 22px !important; left: 22px !important; } A: Update: Refer to this answer for the state of the infobox source code migration to github. How about using the Infobox plugin rather than using the usual Infowindow? I put up a complete example in a jsfiddle example here. The main thing about the infobox is that you can create your infobox within your page's html, giving you complete control over how it looks using css (and some javascript options, if necessary). Here's the html for the infobox: <div class="infobox-wrapper"> <div id="infobox1"> Infobox is very easy to customize because, well, it's your code </div> </div> The idea here is the "infobox-wrapper" div will be hidden (i.e., display:none in your css) and then in your javascript you will initialize an Infobox object and give it a reference to your "infobox" (inside the hidden wrapper) like so: infobox = new InfoBox({ content: document.getElementById("infobox1"), disableAutoPan: false, maxWidth: 150, pixelOffset: new google.maps.Size(-140, 0), zIndex: null, boxStyle: { background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/examples/tipbox.gif') no-repeat", opacity: 0.75, width: "280px" }, closeBoxMargin: "12px 4px 2px 2px", closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif", infoBoxClearance: new google.maps.Size(1, 1) }); This is just an example of some of the available options. The only required key is content - the reference to the infobox. And to open the info window: google.maps.event.addListener(marker, 'click', function() { infobox.open(map, this); map.panTo(loc); }); And to further demonstrate the flexibility of the InfoBox, this jsfiddle has an image with a css transition as the "info box". And one final tip: Don't use the class "infobox" in your html. It is rather unfortunately used by the plugin when the infobox is actually generated. A: I wanted to have a transparent contact form popup on google map marker click. I made it finally with the help of infobox plugin and this post. That's what I made. Anyone can download and use the source from here A: You can style the infoWindow by styling the .gm-style-iw class. #map-canvas { .gm-style { > div:first-child > div + div > div:last-child > div > div { &:first-child > div, &:first-child > div > div > div, &:last-child, &:last-child > img { display: none !important; } } .gm-style-iw { top: 20px !important; left: 130px !important; background: #fff; padding: 10px; height: 40px; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Faster way to jump to specific autocomplete option Say somewhere in my Vim buffer that I have the following: function foo() { return 'funday, funky, funnel cake'; } Now I want to create a new function below this.. I start typing fun and hit Tab to bring up my autocomplete menu. In that menu, I get (in this hypothetical order): funday funnel function funky Normally, I would Ctrl + n twice to highlight function, which isn't a big deal.. but what if I have 20 results and I want to get to the 10th result really fast. Is there any known way (or plugin) to quickly jump to specific values in a Vim autocomplete menu? Update: Using a hack, I found a way to jump by X autocomplete options: " j/k for up and down in autocomplete menu inoremap <expr> j ((pumvisible())?("\<C-n>"):("j")) inoremap <expr> k ((pumvisible())?("\<C-p>"):("k")) " Hack to jump down x positions inoremap <expr> 2 ((pumvisible())?("\<C-n><C-n>"):("2")) inoremap <expr> 3 ((pumvisible())?("\<C-n><C-n><C-n>"):("3")) inoremap <expr> 4 ((pumvisible())?("\<C-n><C-n><C-n><C-n>"):("4")) However, my vimscript is gross. Anyone got a better way to do this? A: As far as quickly jumping to a specific autocomplete, I have the following workflow. In my .vimrc: set completeopt=longest,menuone The longest option prevents the first match from being automatically selected. This means Vim will wait for you to finish typing the rest of the word, and the completion popup will automatically narrow as you type more characters of the word. In your example, you would type fun, hit Tab, to bring up your autocomplete menu. At this point, you would still see: funday funnel function funky ...but now the first choice (funday) would no longer be automatically chosen. You could then type "c", which would narrow the list to: function This is the fastest way that I know of, using pure Vim, anyway. I tend to like pure Vim solutions, myself. :) EDIT: Realized that I forgot to include "menuone" at the end of the line in my .vimrc file. This causes Vim to show the autocomplete menu, even if there was only one match. You would need either "menuone" or "menu" in the set completeopt line in order to actually see the popup with completions. A: maybe you are interested in neocomplcache plugin
{ "language": "en", "url": "https://stackoverflow.com/questions/7616671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: BootupReceiver in Android 3.1 I want to know if there are any changes in boot up event in Android 3.1+, I do not recieve it in 3.1 whereas on android 2.2 it works fine A: Yes Starting from Android 3.1, the system's package manager keeps track of applications that are in a stopped state and provides a means of controlling their launch from background processes and other applications. More details here http://developer.android.com/sdk/android-3.1.html#launchcontrols
{ "language": "en", "url": "https://stackoverflow.com/questions/7616676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access 2007 vba How to link a query to a button that will fill a field in a form? Since everyone has been so helpful to me as a Access/SQL/VBA newbie, I thought I'd try another question. I'm building a system tracking form for some of our information assurance processes and I've got a button on a form that I want to take a CSV formatted field called Affected_Machine_Name from Table B and insert it into the Affected_Machine_Name field in Table A, which is what the form is based off of. The query (All_Machine_Names) I wrote to try to do this looks like: INSERT INTO TableA ( Affected_Machine_Name.[Value] ) SELECT TableB.Affected_Machine_Name FROM TableA, TableB; After doing some research in one of the other posts, I have it linked into the button using the VBA onClick as follows: Public Sub All_Button() Screen.ActiveDatasheet!Affected_Machine_Name = DoCmd.OpenQuery "All_Machine_Names" End Sub My current problem is I get a syntax error for the sub function and I have no clue why because the error box provides no useful details. For that matter, I'm not even sure if my query is right, as I was trying to copy some of the other posts for how to do inserts. I think I'm not referencing the individual records as when I just run the query by itself, it wants to mod all 180 records instead of just the one I have highlighted. Any help that can be provided would be greatly appreciated! Thanks! UPDATE: Since I've been looking into the options for how to complete this and think I need to close this question and redefine my issue. Thank you to all who provided some hints and direction. A: I'm going to assume you have a unique machine ID (the PK?) on your form and you'd like the Affected_Machine_Name from table B where the Machine_ID (or whatever the ID/PK is) equals the current machine record from table A. Let's assume your form is BOUND (not just based off of) to TableA and the ID field in both tables is named Machine_ID. If that were the case then the following should work in the code for a button on the form: me!Affected_Machine_Name = dlookup("Affected_Machine_Name", "TableB", "Machine_ID = " & me!Machine_ID In that code "me!" is a way to reference the fields of the bound table for the currently selected record. Dlookup returns data from a table with the arguments dlookup(field,table,condition). So that will return the machine name from TableB that has the same ID as the current record in the form. (Side question: Why are you storing CSV data in a database instead of breaking it out into a separate table?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7616677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I force a read to pass So I am writing a simple shell. The relevant codes are posted below. void sig_int_handler(int signum) { if (pid == -1) // do nothing else kill(...); } signal(SIGINT, sig_int_handler); .. while(1) { pid = -1; printf(COMMAND_PROMPT); input_len = read(...); if only enter is pressed: continue; // parse inputs pid = fork(); if (pid == 0) { // Do child process operations } else if (pid > 0) { // Parent waits for child } else {..} } But now when I press ctrl+c, it properly exits the child. However, if I press ctrl+c in regular terminal, it prints out "ctrl+c" on stdout, but then it doesn't do anything. How do I force a linefeed into read so that it gives me another prompt? A: I'm assuming you're trying to write something like a shell here. If so: You shouldn't have to process ^C in your shell. If you set up a new process group for the child process (using setpgid() and TIOCSPGRP), only it will receive SIGINT.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Algorithm to match a sequence in a given n*m matrix I have a matrix which is of n*m dimension and i intend to match a set of numbers with the given matrix. It is pretty straight forward if the pattern falls in the vertical or horizontal column of the matrix , but if the pattern falls in a diagonal fashion , i am unable to detect it. For example , if i had to match a given pattern of [-1 , -1 , -1 ] in the following matrix 0 0 0 -1 0 0 0 -1 0 0 0 -1 0 0 0 1 0 -1 -1 -1 In the above case i shud be able to detect the -1 group in the diagonal fashion as well as the one in the last row. I can also have a input where in -1 0 0 -1 0 0 -1 0 0 0 0 -1 -1 0 0 1 0 -1 -1 -1 In this case the diagonal from right to left is to be detected and the last row sequence too. Basically on a given sequence i must be able to detect its presence , which could be present in either a vertical way or horizontal or diagonal way. My Problem: The algorithm has to detect the "all" sequences irrespective of whether its horizontal, vertical or diagonally present. Also , do remember the matrix dimensions are N*M so it could be of any size. A: I'll note that you could (somewhat exhaustively) iterate over the n row by m column matrix (treated as a single vector) with different strides -- 1, m-1, m, m+1. At each stride start at every position (up to the point where that stride would run off the end of the vector) and see if you have a match. This at least eliminates having four different algorithms for the horizontal, vertical, and the two diagonals. Pretty ugly in terms of algorithm order, though -- pretty much N-squared. (Well, maybe not. You can qualify the starting cell with a single loop, for all four possibilities. So, once a start has been found, check the four strides. So you should be able to check for everything with one basic pass through the matrix.) A: Regardless of optimization techniques, a more generic version of this problem is as such: You have an array of elements where each element is a number and its relative positioning in relation to eachother. E.g. a left-to-right list of the numbers 60,50,40,30 would look like (60,0,0) (50,1,0) (40,2,0) (30,3,0). If this were a top-to-bottom list, it would be (60,0,0) (50,0,1) (40,0,2) (30,0,3). If it were top-left to bottom-right diagonal, it would be (60,0,0) (50,1,1) (40,2,2) (30,3,3). So, in this manner, the problem has been made more generic: You want to find a list of numbers in generic coordinate-specifiable orientations within a matrix. The general algorithm then looks like this: For each configuration For each coordinate of the matrix For each element in the list and corresponding local coordinate Add the local coordinate to the coordinate within the matrix If the value at that coordinate in the matrix does not match go to next configuration We found a match! Prosperity and happiness! The devil, as usual, is in the details. Specifically, in this case, you don't actually want to go over all of the coordinates of the matrix. What you REALLY want is to go over all coordinates that when added to the pattern will produce a possibility of a match while not going outside of the matrix. (That way there's far less error checking to do.) This is a simple 2D clipping problem. Find your lowest X and Y and highest X and Y in the relative positioning values of a configuration. If you're using a zero-index based matrix, you want your starting coordinates to be -lowX, -lowY and your maximum coordinates to be matrixMaxX - 1 - highX, matrixMaxY - 1 - highY. The added benefit is that you can add any shape you want, not just up/down/left/right/four diagonals. But it's up to you. A: Though it's an old question, I hope my answer could help someone. While working on a tic-tac-toe project, I tried to generalize a solution which I think could work for your question too. This implementation will look for "line patterns" (which means it only works for a sequence of elements on an horizontal/vertical/diagonal line. function lookForCombinationsOnGrid(grid, ...args) { /* This function looks for a linear sequence of elements (x, o, undefined) on the grid. It returns an array of all beginning and ending coordinates (x, y) for the corresponding pattern. Inputs: - grid, a system of coordinates with an x-axis and an inverted y-axis. - elements can be any sort of built-in objects. */ let sequence = []; sequence.push(args[0]); args.reduce(function (accumulator, currentValue, currentIndex, args) { return sequence.push(currentValue); }); console.log("sequence =", sequence); let testedArr; // Look for this combination horizontally. let result1 = []; for (i = 0; i < grid.length; i++) { for (j = 0; j <= grid[i].length - sequence.length; j++) { testedArr = []; for (k = 0; k < sequence.length; k++) { testedArr.push(grid[i][j + k]); } if (testedArr.join() === sequence.join()) { let start = [j, i]; let end = [j + sequence.length - 1, i]; result1.push([start, end]); } } } console.log("Found", result1.length, "results horizontally. "); // Look for this combination vertically. let result2 = []; for (i = 0; i < grid[0].length; i++) { for (j = 0; j <= grid.length - sequence.length; j++) { testedArr = []; for (k = 0; k < sequence.length; k++) { testedArr.push(grid[j + k][i]); } if (testedArr.join() === sequence.join()) { let start = [i, j]; let end = [i, j + sequence.length - 1]; result2.push([start, end]); } } } console.log("Found", result2.length, "results vertically. "); // Look for this combination diagonally. let result3 = []; for (i = 0; i <= grid.length - sequence.length; i++) { for (j = 0; j <= grid[i].length - sequence.length; j++) { testedArr = []; for (k = 0; k < sequence.length; k++) { testedArr.push(grid[i + k][j + k]); } if (testedArr.join() === sequence.join()) { let start = [j, i]; let end = [j + sequence.length - 1, i + sequence.length - 1]; result3.push([start, end]); } } } console.log("Found", result3.length, "results diagonally (left to right). "); // and diagonally the other way... let result4 = []; for (i = 0; i <= grid.length - sequence.length; i++) { // line i = 0 for (j = grid[i].length-1 ; j >= 0 + sequence.length-1; j--) { // column j = 1 testedArr = []; for (k = 0; k < sequence.length; k++) { testedArr.push(grid[i + k][j - k]); // + 1 line to i, -1 col to j } if (testedArr.join() === sequence.join()) { let start = [j, i]; let end = [j - sequence.length + 1, i + sequence.length - 1]; result4.push([start, end]); } } } console.log("Found", result4.length, "results diagonally (right to left). "); let result = result1.concat(result2); result = result.concat(result3); result = result.concat(result4); return result; } grid = [[1, 1, 3], [1, 1, 1], [1, 1, 1], [0, 1, 1]]; console.log(lookForCombinationsOnGrid(grid, 1, 1, 1, 0 )); I hope this can help someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python: print "word" in [] == False Going a bit mental here trying to work out what this does in python: print "word" in [] == False Why does this print False? A: Just like you can chain operators in 23 < x < 42, you can do that with in and ==. "word" in [] is False and [] == False evaluates to False. Therefore, the whole result is "word" in [] == False "word" in [] and [] == False False and False False A: Perhaps a more clear example of this unusual behaviour is the following: >>> print 'word' in ['word'] True >>> print 'word' in ['word'] == True False Your example is equivalent to: print ("word" in []) and ([] == False) This is because two boolean expressions can be combined, with the intention of allowing this abbreviation: a < x < b for this longer but equivalent expression: (a < x) and (x < b) A: Just to add to Mark Byers great answer >>> import dis >>> dis.dis(lambda: 'word' in [] == False) 1 0 LOAD_CONST 1 ('word') 3 BUILD_LIST 0 6 DUP_TOP 7 ROT_THREE 8 COMPARE_OP 6 (in) 11 JUMP_IF_FALSE_OR_POP 21 14 LOAD_GLOBAL 0 (False) 17 COMPARE_OP 2 (==) 20 RETURN_VALUE >> 21 ROT_TWO 22 POP_TOP 23 RETURN_VALUE >>> dis.dis(lambda: ('word' in []) == False) 1 0 LOAD_CONST 1 ('word') 3 LOAD_CONST 2 (()) 6 COMPARE_OP 6 (in) 9 LOAD_GLOBAL 0 (False) 12 COMPARE_OP 2 (==) 15 RETURN_VALUE
{ "language": "en", "url": "https://stackoverflow.com/questions/7616691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I invoke the constructor of a Scala abstract type? I'm trying to figure out how to invoke a constructor for a Scala abstract type: class Journey(val length: Int) class PlaneJourney(length: Int) extends Journey(length) class BoatJourney(length: Int) extends Journey(length) class Port[J <: Journey] { def startJourney: J = { new J(23) // error: class type required but J found } } Is this even feasible? I'm familiar with Scala manifests but I'm not clear how they could help here. Likewise I can't figure out how to do the same with a companion object's apply() constructor: object Journey { def apply() = new Journey(0) } object PlaneJourney { def apply() = new PlaneJourney(0) } object BoatJourney { def apply() = new BoatJourney(0) } class Port[J <: Journey] { def startJourney: J = { J() // error: not found: value J } } Any thoughts gratefully received! A: Your class needs an implicit constructor parameter to get the Manifest. Then you can call erasure to get the Class and call newInstance, which reflectively calls the nullary constructor if there is one. class J[A](implicit m:Manifest[A]) { def n = m.erasure.newInstance() } new J[Object].n As of Scala 2.10, the erasure property in the manifest is deprecated. def n = m.runtimeClass.newInstance() does the same thing, but without warnings. A: There is no direct way to invoke the constructor or access the companion object given only a type. One solution would be to use a type class that constructs a default instance of the given type. trait Default[A] { def default: A } class Journey(val length: Int) object Journey { // Provide the implicit in the companion implicit def default: Default[Journey] = new Default[Journey] { def default = new Journey(0) } } class Port[J <: Journey : Default] { // use the Default[J] instance to create the instance def startJourney: J = implicitly[Default[J]].default } You will need to add an implicit Default definition to all companion objects of classes that support creation of a default instance. A: My inclination is that this cannot be done. I am far from a Scala guru, but my reasoning is this: * *You have a class Port with a type argument T where T must inherit from Journey (but T does not have to be exactly Journey, this is important). *Within Port, you define a method which creates a new T. This class has no idea what T is, and therefore what T's constructor looks like. *Because you don't know what arguments T's constructor takes, you don't know what arguments to pass to it. The solutions to this problem are handled very nicely in another question, so I will point you there for them rather than repeating here: Abstract Types / Type Parameters in Scala
{ "language": "en", "url": "https://stackoverflow.com/questions/7616692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Overlapping trees in L-system forest I created an a program using python's turtle graphics that simulates tree growth in a forest. There's 3 tree patterns that are randomly chosen, and their starting coordinates and angles are randomly chosen as well. I chose some cool looking tree patterns, but the problem I'm having is that many of the trees are overlapping, so instead of looking like a forest of trees, it looks like a bad 5 year old's painting. Is there a way to make this overlapping less common? When you look at a forest, some trees and their leaves do overlap, but it definitely doesn't look like this: Since there's a lot of randomization involved, I wasn't sure how to deal with this. Here's my code: import turtle import random stack = [] #max_it = maximum iterations, word = starting axiom such as 'F', proc_rules are the rules that #change the elements of word if it's key is found in dictionary notation, x and y are the #coordinates, and turn is the starting angle def createWord(max_it, word, proc_rules, x, y, turn): turtle.up() turtle.home() turtle.goto(x, y) turtle.right(turn) turtle.down() t = 0 while t < max_it: word = rewrite(word, proc_rules) drawit(word, 5, 20) t = t+1 def rewrite(word, proc_rules): #rewrite changes the word at each iteration depending on proc_rules wordList = list(word) for i in range(len(wordList)): curChar = wordList[i] if curChar in proc_rules: wordList[i] = proc_rules[curChar] return "".join(wordList) def drawit(newWord, d, angle): #drawit 'draws' the words newWordLs = list(newWord) for i in range(len(newWordLs)): cur_Char = newWordLs[i] if cur_Char == 'F': turtle.forward(d) elif cur_Char == '+': turtle.right(angle) elif cur_Char == '-': turtle.left(angle) elif cur_Char == '[': state_push() elif cur_Char == ']': state_pop() def state_push(): global stack stack.append((turtle.position(), turtle.heading())) def state_pop(): global stack position, heading = stack.pop() turtle.up() turtle.goto(position) turtle.setheading(heading) turtle.down() def randomStart(): #x can be anywhere from -300 to 300, all across the canvas x = random.randint(-300, 300) #these are trees, so we need to constrain the 'root' of each # to a fairly narrow range from -320 to -280 y = random.randint(-320, -280) #heading (the angle of the 'stalk') will be constrained #from -80 to -100 (10 degrees either side of straight up) heading = random.randint(-100, -80) return ((x, y), heading) def main(): #define the list for rule sets. #each set is iteration range [i_range], the axiom and the rule for making a tree. #the randomizer will select one of these for building. rule_sets = [] rule_sets.append(((3, 5), 'F', {'F':'F[+F][-F]F'})) rule_sets.append(((4, 6), 'B', {'B':'F[-B][+ B]', 'F':'FF'})) rule_sets.append(((2, 4), 'F', {'F':'FF+[+F-F-F]-[-F+F+F]'})) #define the number of trees to build tree_count = 50 #speed up the turtle turtle.tracer(10, 0) #for each tree... for x in range(tree_count): #pick a random number between 0 and the length #of the rule set -1 - this results in selecting #a result randomly from the list of possible rules. rand_i = random.randint(0, len(rule_sets) - 1) selected_ruleset = rule_sets[rand_i] #unpack the tuple stored for this ruleset i_range, word, rule = selected_ruleset #pick a random number inside the given iteration_range to be the #iteration length for this command list. low, high = i_range i = random.randint(low, high) #get a random starting location and heading for the tree start_position, start_heading = randomStart() #unpack the x & y coordinates from the position start_x, start_y = start_position #build the current tree createWord(i, word, rule, start_x, start_y, start_heading) if __name__ == '__main__': main() A: From my understanding of an L-system there's a whole grammar that isn't randomly chosen. Could you provide details as to how your grammars work? I would imagine that you can somewhat restrict which directions your trees grow into by making a limited, closed-ended set of productions that go anywhere more than 90 degrees from the starting angle. But then you can't totally randomize the starting angle... You probably need to just randomize it within a certain range? Of course if you have an L-system that just generates everything randomly, it's just gonna look like a bunch of noise. There's a purpose to putting a restriction on your initial conditions; every grammar has a start symbol, and you need to take advantage of your start symbol to generate stuff that makes sense. I'd imagine that you want your start symbol to always point up. But I haven't studied L-systems in a long time, so take my answer with a grain of salt. Edit: That's an interesting restriction to impose, in that it sound like something that trees do naturally. In nature I think it happens because only a certain amount of sunlight can get through to a given patch of ground, so if a tree is already growing somewhere, nothing else can do so. Being an AI guy, I love turning real-world solutions into interesting heuristics. What kind of a heuristic are we looking for here? Well, a "patch of ground" in a 2-d coordinate system is just a range of x-coordinates. Maybe have something that makes growth lose impetus if there's too much stuff within some arbitrary x range of a growing leaf? (not a python xrange, but a range of x-coordinates, some "delta" value if you will.) A: I think the problem lies more in the regularity of features among the trees themselves, rather than their placement per se. A possible solution would be to add mutations. For a global control of "stunted growth", you could suppress say 5% of the production applications. This should give sparser trees that follow the model more loosely. For finer control, you can suppress each production with a different weight. Check out The Algorithmic Beauty of Plants section 1.7 Stochastic L-systems for more. They use probability to select among several variants of single rule.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Searching for unicode surrogates in Acrobat Pro using javascript I wanted to search for Japanese text using the Acrobat Javascript API (search.query). Everything works fine except for the code range 0xD800~0xDFFF (Unicode surrogate code points). I have tried copy and pasting the text I want to search for into my .js file and have also tried entering the surrogate code points, in either case they appear as a "." in the search window. Here are my questions: * *Why does the text appear as a dot in Acrobat? *Is there any way to search for surrogates through Acrobat Javascript? Edit: More information: In Acrobat, hit "Ctrl+J" to launch the debugger and type search.query("\uDBCE\uDE2F", "ActiveDoc"); and hit "Ctrl+Enter". You should see two dots (i.e., "..") in the search window (at least with Acrobat 9). The peculiar thing is that, if you type app.alert("\uDBCE\uDE2F"); it displays the character (a box) that I want to search for. A: Have you tried entering correct pairs of surrogates? Stand-alone code units in the surrogate area don't make any sense, and can't be rendered. Nothing to with Acrobat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Read a file and store arbitrary values into a variable in bash script I'm new to bash scripting and I'm having a hard time to figure out this problem. I have about two hundred files that follow this pattern: ANÁLISE DA GLOSA FUNGICIDA A ANÁLISE RESULTA EM: S='Glosa02626354' = "agente que destrói ou previne o crescimento de fungos" {antifúngico: O I]antifúngico clássico utilizado no tratamento não previne a disseminação típica da infecção., agente antifúngico: Os resultados sugerem a utilização terapêutica do extrato do limão como I]agente antifúngico na Odontologia., fungicida: A duração do ]fungicida no carpete tem garantia de cinco anos., antimicótico: Os grupos nomearam o I]antimicótico e realizaram campanha de lançamento fictícia, com material técnico de divulgação e brindes., agente antimicótico: Em caso de infecção, deverá ser instituído o uso de um I]agente antimicótico.} Chave: FUNGICIDA <noun.artifact> ILI: 02626354 Sense 1 {02626354} <noun.artifact> antifungal, antifungal agent, fungicide, antimycotic, antimycotic agent -- (any agent that destroys or prevents the growth of fungi) => {13935705} <noun.substance> agent -- (a substance that exerts some force or effect) => {00005598} <noun.Tops> causal agent, cause, causal agency -- (any entity that causes events to happen) => {00001740} <noun.Tops> entity -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving)) In this case, I have to store the following values between braces: ‘antifúngico’, ‘agente antifúngico’, ‘fungicida’, ‘antimicótico’ and ‘agente antimicótico’ in one variable. Those words will of course be different in every file. For comparison, here's another file: ANÁLISE DA GLOSA VIA ÁPIA A ANÁLISE RESULTA EM: S='Glosa02634922' = "estrada da antiga Roma, na Itália, extendendo-se ao sul, de Roma a Brindisi; iniciada em 312 AC" {Via Ápia: Toda a I]Via Apia era conhecida quer pela sua extensão, quer pela sua extraordinária beleza.} Chave: VIA ÁPIA <noun.artifact> ILI: 02634922 Sense 1 {02634922} <noun.artifact> Appian Way#1 -- (an ancient Roman road in Italy extending south from Rome to Brindisi; begun in 312 BC) => {03390668} <noun.artifact> highway#1, main road#1 -- (a major road for any form of motor transport) => {03941718} <noun.artifact> road#1, route#2 -- (an open way (generally public) for travel or transportation) => {04387207} <noun.artifact> way#6 -- (any artifact consisting of a road or path affording passage from one place to another; "he said he was looking for the way out") => {00019244} <noun.Tops> artifact#1, artefact#1 -- (a man-made object taken as a whole) => {00016236} <noun.Tops> object#1, physical object#1 -- (a tangible and visible entity; an entity that can cast a shadow; "it was full of rackets, balls and other objects") => {00001740} <noun.Tops> entity#1 -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving)) => {00002645} <noun.Tops> whole#2, whole thing#1, unit#6 -- (an assemblage of parts that is regarded as a single entity; "how big is that part compared to the whole?"; "the team is a unit") => {00016236} <noun.Tops> object#1, physical object#1 -- (a tangible and visible entity; an entity that can cast a shadow; "it was full of rackets, balls and other objects") => {00001740} <noun.Tops> entity#1 -- (that which is perceived or known or inferred to have its own distinct existence (living or nonliving)) Here, the variable will have just one value, the string ‘Via Ápia’. Update: I found a way to single out the lines that are relevant using some regular expression wizardry: grep ':*\.,' file_name.txt The output of this command for the first example is {antifúngico: O I]antifúngico clássico utilizado no tratamento não previne a disseminação típica da infecção., agente antifúngico: Os resultados sugerem a utilização terapêutica do extrato do limão como I]agente antifúngico na Odontologia., fungicida: A duração do ]fungicida no carpete tem garantia de cinco anos., antimicótico: Os grupos nomearam o I]antimicótico e realizaram campanha de lançamento fictícia, com material técnico de divulgação e brindes., A: If you just want to assign the result of your regex match to a variable in bash, then this should do it: myVar=$(cat file_name.txt|grep ':*\.,') EDIT: This may get you a bit closer: myVar=$(cat file_name.txt|grep ':*\.,'|./x.pl) Where x.pl is: #!/usr/bin/perl while (<STDIN>) { my @x = split /,/; foreach (@x) { print $1 . "\n" if /\{?\W*(.*?)\:/; } } That will extract the 4 words you want, separated by newlines. I'm still not entirely clear if that's what you want though. A: If you have GNU grep, you may have good luck with grep -Po '(?<={)[^:]+(?=:)'
{ "language": "en", "url": "https://stackoverflow.com/questions/7616699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I fix the bug in the sudoSlider jQuery plugin? I am using the sudoSlider jQuery plugin to make a html slider on my site. I have created buttons at the bottom that work as slide choosers but when it slides across it bounces back again. This is the site: http://vermilionsite.com/RedFox/index.html I can't figure out why this is happening! A: i created SudoSlider You have asked this question before, and i think i know what you mean now. Is the problem that: 1: When you click one of the bottom buttons, the slider start the automatic slideshow again after about 6 seconds? Or is it 2: that the slider doesn't stop after it reaches the 3. slide? Solution to the first problem is to remove this line: "resumePause: 6000," Solution to the second problem is to remove this line: "resumePause: 6000,", and add the following to the SudoSlider configuration: " afterAniFunc: function(t){if(t==3) sudoSlider.stop;} Next time, be more specific.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Order of python notifications with notify() Let's say I have the following code: master_lock = Lock() x = Condition(master_lock) y = Condition(master_lock) z = Condition(master_lock) def foo_z(): with master_lock: x.notify() y.notify() z.wait() def foo_y(): with master_lock: x.notify() z.notify() y.wait() When you notify one monitor before another, is there any assurance that a thread of the first monitor will be awoken before that of the second, or is the order completely irrelevant to the order in which the calls were made? In this example, in foo_z, could you rely on a thread waiting on x to run before y, and x before z in foo_y? A: No there is no assurance to the order since the code is executing in multiple threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Israel streets names storage with API to c#? I write c# code that gets as an input string an Israeli address plus additional data. I want to match only the address. i.e. "CompanyA 02-4673889 myStreet 8, myCity" "Best X-store myStreet 877 indestirial area myCity" I thought that my c# could search for a city from a 70 cities list I have and then match for a street name. 1)Does someone know where can I find streets list for isaeli cities? 2) Can someone think of a better way of fetching the data from the string? A: The only way to truly and accurately parse address data is by using an online address validation service. The problem with addresses, and especially international addresses, is that there is no real standard. The other problem is that addresses are not "self validating" which means you can't tell if an address is good or even formatted properly by just looking at it. There are a few services out there that do address verification, and I believe there are a few that handle Israeli addresses. Among those providers there are two basic ways to get your addresses cleaned. You can use their "batch scrubbing" capabilities where you upload a file and receive it back within a few minutes (or days), depending upon the provider. Or you could hook into their address verification web service API each time you receive an address. The correct answer depends upon your business needs and how immediate you need a response. Most web service APIs will return the various component parts of an address--including street name--which allows you to perform your desired business function. I should mention that I'm the founder of SmartyStreets. We do address verification for addresses in the United States. I realize you're trying to do Israeli addresses, but the domain knowledge I'm sharing here on the topic is generally universal in nature.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Backbone Collection produces error when receiving server response I'm making a twitter client for my own friends, and im making it using Backbone.js and a php backend using Twitter oAuth API. So here's the scenario: * *user authenticates *backbone app initializes and sends a first request: window.timeline.fetch(); *window.timeline is a backbone collection and its url is: /connect/timeline/ *server returns 10 recent tweets in json and window.timeline adds them using Tweet model, and saves last Tweet id in a variable. *backbone view renders and shows them and triggers a timer *Timer starts ticking and runs window.timeline.fetch({add: true}); every 10 seconds, and adds /ID/ add the end of the fetch URL, to tell twitter API return tweets since that ID *since I passed the add option, when server returns the object, it triggers "add" event and I bind it to a method which adds every tweet and the top of the list and saves the last tweet id to use in next timer tick. the problem is tweeter sometimes returns the same tweet twice (like RT's and stuff), and since that ID exists in backbone collection, it produces this error: Uncaught Error: Can't add the same model to a set twice,119896811958833150 and exits the program. how can I control this situation? or is there a better way to do this? window.Tweet = Backbone.Model.extend({}); window.Timeline = Backbone.Collection.extend({ model: Tweet, url: function(){ var id = (window.lastId) ? window.lastId + "/?" + Math.floor(Math.random()*99999) : ""; return "/connect/timeline/" + id; } }); Thanks (and sorry for my English) A: Well you certainly have a race condition. If you manage to send two requests and have a very slowly responding server you might get the same tweet twice. I'm not sure if that's the problem in your case but it certainly is an option. Given this is the source of your problem, you have at least two options to solve it: * *Maintain some flag that would indicate whether you're in a process of waiting for a server response. This will allow you to prevent sending two requests concurrently from the same client instance. NOTE: This is not the same as synchonous requests. The latter blocks your UI! *You could also check whether a tweet with the returned id already exists and only then proceed. However this is a little bit dangerous because it might hide a deeper problem with your implementation. EDIT I think you're problem is simply that url /timeline/SOME-ID-HERE returns all the newest tweets until the given id inclusive. I've checked the contents of the requests that your applications sends. The first one /timeline is long and ends with an id 119912841942802432. And this is the only id that is returned in your second request. What I don't understand is how does the ID in the address relate to ids of your tweets. The second request address is /timeline/119912841942802430. On the other hand 119912841942802430 doesn't match anything in the results. 119912841942802432 (notice 2 instead of 0 at the end) does.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent multiple instances of Activity but still use onActivityResult I have an activity that I want to exist only once, no matter how many times it is opened. Previously I was using launchMode singleTask, and everything was working great. However, now I need to be using onActivityResult, which for some reason is incompatible with launchMode singleTask. Do you know of a way to replicate what either of them does. A: My Main activity is also a singleTask but I'm certainly startingActivitiesForResults from my Main activity and getting back results. Here is my manifest declaration: <activity android:name=".activities.Main" android:theme="@android:style/Theme.Light" android:screenOrientation="portrait" android:launchMode="singleTask" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> Here is my onActivityResult: @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent){ super.onActivityResult(requestCode, resultCode, intent); // blah blah checking if if the requestCode and resultCode are good // } I'm sure you're setting the result in the other Activities... So just cross check your code with mine, let's see if we can find the problem. * *make sure onActivityResult is "protected" when you're overriding it. Hope this helps -serkan A: You can use FLAG_ACTIVITY_REORDER_TO_FRONT, which will bring the launched activity to the front of it's task's stack instead of creating a new instance. Note that the result will be delivered to the first activity that called startActivityForResult. This answer provides a good example of how this works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: access QWebPage object from WebView QML element Is there a way to access the QWebPage object from WebView's underlying QWebView object? QWebView has: QWebPage * QWebView::page () const src: http://doc.qt.nokia.com/4.7-snapshot/qwebview.html#page However it doesn't seem to be exposed in QML A: I haven't tryed it, but ... In qdeclarativewebview_p.h at line 59 there is defined as public: 159 QWebPage *page() const; 160 void setPage(QWebPage *page); So you should be able to access this at least from C++ (but not directly from QML). If you need it in QML, you can inherit the original QDeclarativeWebView and expose this property for access in QML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the proper way to handle asynchronicity in nodeunit? I'm brand-spanking new to the whole stack - javascript, node.js, coffeescript, nodeunit. Think I should do it step by step? You're probably right, but I still am not going to do it. Here is the test file: testCase = require('nodeunit').testCase Server = require('./web').WebServer Client = require('../lib/client').Client Request = require('../lib/request').Request OPTIONS = {host: 'localhost', port: 8080, path: '/', method: 'GET'} SERVER = new Server OPTIONS.port CLIENT = new Client REQUEST = new Request OPTIONS SERVER.start() # asynchronous! module.exports = testCase setUp: (callback) -> callback() tearDown: (callback) -> callback() testResponseBodyIsCorrect: (test) -> test.expect 1 process.nextTick -> CLIENT.transmit REQUEST #asynchronous! process.nextTick -> test.equal REQUEST.body, /Ooga/ test.done() Internally, it is just a wrapper around the http library. I am using node 0.4.11. This does not actually work. There are two asynchronous calls here. If I do this manually in the coffee REPL, it works -- but nodeunit is much faster than I am, so I run into something which, to be clever, I'll call a race condition. grin Here is the implementation of 'transmit': Http = require 'http' exports.Client = class Client transmit: (request, callback = null) -> req = Http.request request.options, (res) -> res.setEncoding 'utf8' res.on 'data', (chunk) -> request.appendToResponseBody chunk req.end() console.log "Request sent!" I need to make sure the server gets bound to the port before I run the test, and I need to make sure ".transmit" has finished its internal callbacks to get the response before I do the assertion. What is the clean way (or at least the way that works) to do this? A: Whenever you do something asynchronous, you should put the rest of your code in the callback from that async function. So instead of CLIENT.transmit REQUEST process.nextTick -> ... do CLIENT.transmit REQUEST, (response) -> ... (I'm assuming that your CLIENT.transmit method is implemented in such a way that it calls a callback with the response it gets—it should!) Now, if you're trying to test the client and the server at the same time, then you should use an EventEmitter—I think that you'll find that your SERVER object already is one, since it inherits from Node's http.Server type. Since http.Server objects fire a request event whenever they receive a request, you can do things like SERVER.on 'request', (request) -> test.equals REQUEST.body, request.body Pretty nice, right? Node-style asynchronicity can be mind-bending, but it gives you an amazing array of options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Win32 memory allocation with large alignment I need to allocate large regions of memory (megabytes) with large alignments (also potentially in the megabyte range). The VirtualAlloc family of functions don't seem to provide options to do this. What I do on Linux to achieve this is to mmap a larger region - large enough to guarantee that a sufficiently large region with the required alignment will be contained in it - and then munmap the regions at the beginning and the end of the large region that are not needed. As an example, let's say I need 4 megabytes, aligned on a 1 megabyte boundary (i.e. the start of the region having zeroes in the lowest 20 bits). I'd mmap 5 megabytes. Let's say I get the region 0x44ff000-0x49ff000. Within that region is contained the region 0x4500000-0x4900000, which is aligned on a 1 megabyte boundary. I would then munmap 0x44ff000-0x4500000 and 0x4900000-0x49ff000. Can I do something similar on Win32? If I use VirtualProtect with PAGE_NOACCESS, will the memory be freed? Is there a better solution? A: Yes, you can use the same technique. VirtualAlloc a large range as MEM_RESERVE. Find the sub-range that is appropriately aligned and call VirtualAlloc a second time on the sub-range with MEM_COMMIT. A: Have a look at the source for _aligned_malloc in the windows/MSVC crt, its very simple to use the same method to align virtual memory, i'd would even go so far as to say, just replace its internal malloc call (same goes for _aligned_free), this allows allocation with only a single system call. However, why do you need such massive alignment? Are you trying to abuse address bit patterns for fast memory block slabs?
{ "language": "en", "url": "https://stackoverflow.com/questions/7616719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Deconstructing types in Haskell I've defined the following type in Haskell: data AE = Num Float | Add AE AE | Sub AE AE | Mult AE AE | Div AE AE deriving(Eq, Read, Show) Now how do I deconstruct it? Specifically, how would I complete a function as follows: testFunct :: AE -> something testFunct expression | if type Num = do this | if type Add = then do this etc. Also, how would I get the data out of the type? For instance, if I have Sub AE1 AE2 how would I extract AE2? A: What you're looking for is called 'pattern matching'. It let's you deconstruct types, by matching them against a given pattern. In your case, you could say: testFunct (Num x) = ... testFunct (Add a b) = ... testFunct (Sub a b) = ... You should work through a good haskell book, like LYAH or Programming in Haskell.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to enable GZip compression in a self-hosted RESTful WCF webservice? I have a RESTful WCF web service written in C# using .NET 4.0, and I'd like the responses to be compressed using GZip or deflate. (I might need to support compression for requests too, but that is not yet a requirement). It will be deployed as a windows service, i.e. self-hosted WCF service, as IIS hosting is not an option. My searches have so far come up short. Most hits are either for turning on compression in IIS or writing a custom message encoder for a SOAP based service, neither or which fit my scenario. If you have any pointers for how to do this, it would be greatly appreciated! A: You really need to go for the custom encoder route (sample with code at http://msdn.microsoft.com/en-us/library/ms751458.aspx) if you want to do GZip compression in a self-hosted scenario (on 4.5 it looks like there is support for compression on the binary encoding, per the announcement at the MSDN WCF Forums, but it doesn't exist out-of-the-box for 4.0). Why doesn't the custom encoder work for your scenario?
{ "language": "en", "url": "https://stackoverflow.com/questions/7616725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Regex(sed): How to form replace pattern according to a variable? I need to append a ".dev" or a ".prd" to a machine name depending on which domain they're in. The domain can be determined in the machine name, since they all follow the same pattern: hostd(..) for dev machines and hostp(..) for production machines. Here's an example of what I want: ============================= | input | output | |=============|=============| | hostd01 | hostd01.dev | |-------------|-------------| | hostp03 | hostp03.prd | ============================= I'm new to sed, so I don't know how elegant is the solution I found (below). Isn't there a way to do it in one line? sed -e 's/\([dp]\)\(..\)/\1\2.\1/' -e 's/d$/dev/' -e 's/p$/prd/' A: $ sed '/d/{s/$/\.dev/} ; /p/{s/$/\.prv/}' input hostd01.dev hostp03.prv
{ "language": "en", "url": "https://stackoverflow.com/questions/7616726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I combine multiple operator statements into one statement in PHP? For example, I've always did something like if($word=='hi' || $word=='test' || $word=='blah'... This can become quite long. If there a simple way to combine these statements into one statement? A: The best way I can think of is using in_array(): $possible = array('hi', 'test', 'blah'); if (in_array($word, $possible)) { ... http://php.net/manual/en/function.in-array.php A: The short answer is no. The long answer is: you can create an array of strings $words = array('hi', 'test', 'blah'); and then do if (array_search($word, $words) !== false) do smth. A: If you have multiple exclusive conditions like that, switch syntax is pretty clean: switch ($word) { case 'hi': case 'test': case 'blah': // Do something useful. break; // other conditions... default: }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL - Transferring data I have a date column (Date, INDEX) in my MySQL database but because I have some advanced date queries to make, I have to transfer the day and month in to a new column, 'shortDate'. The advanced queries include seasonal searches, so I can search for all photos from summer/winter/autumn/spring/christmas/new year/easter but from any year. This allows me to run queries like this, for summer: ...WHERE shortDate BETWEEN 0621 AND 0921...;" So the new column (shortDate) should look like this: Date shortDate 2011-01-28 0128 2011-06-17 0617 2011-12-22 1222 I have created the new column but I would like to know the fastest solution to transfer/convert the date column and write the conversion to the new column? Is this all possible in SQL or do I need to include another server language? I have 150,000 rows and could take a while if I don't do it the right way. Because my SQL skills are very rusty, I probably would have written some ASP to read, covert and insert the new data but I'm hoping there is a quicker way... A: All you need is this: Update YourTable set shortDate = date_format(`Date`, '%m%d') This will take care of your existing data. You have to make sure any new data entered in the table will follow the same rule. You can either do that in the application that inserts the data or by creating a trigger in the table responsible for handling the content of shortdate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a TreeView with fixed column like Blend's I am trying to implement something like this. The problem is how to have scrollbar at bottom and fixed collumn at the right ? I am using WPF 4.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: KnockoutJS - force number for specific field using ko.mapping plugin When I use ko.mapping.toJSON it converts any changes I made into strings and they need to be numbers. I tried using the custom mapping like so: var mapping = { 'y': { update: function(options) { return parseFloat(options.data); } } } ... but this only keeps them as numbers inside the contect of the page. Since I am using this to update and external JSON that gets pulled in by HighCharts.js the numbers need to stay numbers even after the toJSON. From an earlier answer here I was able to use: //override toJSON to turn it back into a single val mappedData.prototype.toJSON = function() { return parseInt(ko.utils.unwrapObservable(this.val), 10); //parseInt if you want or not }; ... which worked swimmingly. However this is just a single value type in the JSON so I am unclear on how I could use the same override for it. Do I need to create a whole new object to do this in this instance as well. Or is their something more concise? A: Whenever you edit a value in an input, the value will end up being a string. Knockout reads the new value from the element and it is always a string. If you want to keep it numeric, look at the answer on this question: Knockout.js: time input format and value restriction for a couple of ways to do it. If you use the custom binding (numericValue) in the answer, then you do not need to do anything else with the mapping options. If you use the numericObservable idea, then you would need to use the mapping options to ensure that it was creating these special observable rather than just a normal observable. Otherwise, you can continue to use the toJSON override as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MediaWiki - four garbage characters before HTML content for 404 So I've just installed MediaWiki for the first time and am having a weird problem which I can't find a solution to. I have been crawling the help docs, searching Google and reading articles for the last couple of hours and can't find an answer. Everything is working fine, except on a 404 page, four garbage characters are output before the HTML. All other pages appear to be fine, just the 404s. They are different on each one and look to me to be in hex, I've seen numbers and no letter higher than an f. Examples * *http://wiki.oneltd.co.uk/wiki/Onekipedia:Community_portal *http://wiki.oneltd.co.uk/wiki/Onekipedia:General_disclaimer *http://wiki.oneltd.co.uk/wiki/Onekipedia:Privacy_policy I have reinstalled it twice with the same problem each time. System setup * *Centos 5.6 *Apache 2.2.3 running with an nginx (0.8.55) reverse proxy *PHP 5.3.2 *MySQL 5.0.77 Server configs Apache <VirtualHost 127.0.0.1:8080> DocumentRoot /home/sites/oneltd.co.uk/wiki ServerName wiki.oneltd.co.uk Alias /wiki /home/sites/oneltd.co.uk/wiki/index.php <Directory "/home/sites/oneltd.co.uk/wiki"> Allowoverride all </Directory> CustomLog /home/sites/oneltd.co.uk/_logs/access_log "combined" ErrorLog /home/sites/oneltd.co.uk/_logs/error_log </VirtualHost> nginx server { listen 205.186.146.37:80; server_name wiki.oneltd.co.uk; server_name_in_redirect off; access_log /home/sites/oneltd.co.uk/_logs/nginx.access_log; location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~ \.(jpg|jpeg|png|gif|swf|flv|mp4|mov|avi|wmv|m4v|mkv|ico|js|css|txt|html|htm)$ { root /home/sites/oneltd.co.uk/wiki; gzip on; gzip_comp_level 2; gzip_vary on; gzip_proxied any; gzip_types text/plain text/xml text/css application/x-javascript; expires max; } } Any help or ideas of where to look will be greatly appreciated :) EDIT - PROBLEM FIXED! Thanks to Greg Hewgill's response about the chunked encoding, I managed to find the problem. It turns out that nginx can't talk HTTP/1.1 when working as a reverse proxy, but you can force Apache to downgrade to 1.0. I found the answer after reading about a similar problem with Drupal Updated Apache config: <VirtualHost 127.0.0.1:8080> DocumentRoot /home/sites/oneltd.co.uk/wiki ServerName wiki.oneltd.co.uk Alias /wiki /home/sites/oneltd.co.uk/wiki/index.php <Directory "/home/sites/oneltd.co.uk/wiki"> Allowoverride all </Directory> CustomLog /home/sites/oneltd.co.uk/_logs/access_log "combined" ErrorLog /home/sites/oneltd.co.uk/_logs/error_log # nginx can't deal with HTTP/1.1 at the moment, force downgrade to 1.0 SetEnv force-response-1.0 1 SetEnv downgrade-1.0 1 </VirtualHost> A: This sounds like it might be somehow related to HTTP chunked transfer encoding. With chunked transfer, the length of each chunk is sent in hex before the actual content. I don't know why this would be a problem in your install, or how to fix it, but it might be useful information when searching for a solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Templated function can't be found, despite being declared I have a code example here: http://codepad.org/9JhV7Fuu With this code: #include <iostream> #include <vector> #include <map> #include <list> #include <set> namespace Json { template <typename ValueType> struct Value { Value() {} Value(int) {} Value(float) {} Value(unsigned int) {} Value(std::string) {} }; } template <typename T> Json::Value<T> toJson(T x) { return Json::Value<T>(x); } template <typename T, typename U> Json::Value< std::pair<T, U> > toJson(std::pair<T, U> const& rh) { Json::Value< std::pair<T, U> > return_value; toJson(rh.first); toJson(rh.second); return return_value; } template <typename T> Json::Value<T> toJsonContainer(T const& rh) { Json::Value<T> return_value; for (typename T::const_iterator it = rh.begin(); it != rh.end(); ++it) { toJson(*it); } return return_value; } template <typename T, typename U> Json::Value< std::map<T, U> > toJson(std::map<T, U> const& rh) { return toJsonContainer(rh); } template <typename T> Json::Value< std::vector<T> > toJson(std::vector<T> const& rh) { return toJsonContainer(rh); } int main(int argc, char **argv) { std::map<std::string, std::vector<unsigned int>> x; toJson(x); return 0; } I'm getting this error: main.cpp: In function ‘Json::Value<T> toJson(T) [with T = std::vector<unsigned int>]’: main.cpp:27:2: instantiated from ‘Json::Value<std::pair<_T1, _T2> > toJson(const std::pair<_T1, _T2>&) [with T = const std::basic_string<char>, U = std::vector<unsigned int>]’ main.cpp:36:3: instantiated from ‘Json::Value<T> toJsonContainer(const T&) [with T = std::map<std::basic_string<char>, std::vector<unsigned int> >]’ main.cpp:44:27: instantiated from ‘Json::Value<std::map<T, U> > toJson(const std::map<T, U>&) [with T = std::basic_string<char>, U = std::vector<unsigned int>]’ main.cpp:54:10: instantiated from here main.cpp:20:25: error: no matching function for call to ‘Json::Value<std::vector<unsigned int> >::Value(std::vector<unsigned int>&)’ Please note that the question is why the compiler picks template <typename T> Json::Value<T> toJson(T x); over template <typename T> Json::Value< std::vector<T> > toJson(std::vector<T> const& rh); Afaik it should pick the latter since it's more specialised. Thanks! A: Well, as we know, you must declare the function before using it in C++, you declared template <typename T> Json::Value<T> toJson(T x) { return Json::Value<T>(x); } which matches with pretty much anything and then you started using it in the template <typename T, typename U> Json::Value< std::pair<T, U> > toJson(std::pair<T, U> const& rh) function. What you missed here is that you declared the std::vector version after the version using std::pair, so it's not finding the correct function template to use. To fix this, move the std::vector version to before the std::pair version or forward declare it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What are these symbols next to "merge mode by recursive" in git merge? When I use git pull [project name] master to update my core files, I get a bunch of green plus and red minus signals under "merge made by recursive." What are these symbols and what do they mean? Here's a screenshot: Thank you for your help. A: That is an approximation of how many lines have changed. Pluses are for new content and minuses are for what was taken out. Modifications end up with equal amount of both. Deletions are only minuses and new files are all pluses. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7616742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Really simple PHP array key-value issue Let's say I have the following table in my database: Name | Description | Image App | Some description | somefile.png Another App | Another descript | anotherfile.png What I want to do is create a JSON array like this: { "App": { "name": "App", "description": "Some description", "Image": "somefile.png" }, "Another App": { "name": "Another App", "description": "Another descript", "Image": "anotherfile.png" } } What I'm struggling with is pushing the key>value pair on. I can push just the value, with a non-keyed array, but I cannot push the key>value pair onto my array. What I've tried: $res = mysql_query('SELECT * FROM `apps`;'); if ($res) { $temp = array(); while ($row = mysql_fetch_array($res)) { $name = $row['name']; $descript = $row['description']; $img = $row['image']; $new = array('name'=>$name,'description'=>$descript,'img'=>$img); array_push($temp,$new); // how do I make this push with a key? } } echo json_encode($temp); My problem is with the array_push() function - I want it to push with the name as the key but I can't get it to. A: Try this: while ($row = mysql_fetch_array($res)) { $name = $row['name']; $descript = $row['description']; $img = $row['image']; $temp[$name] = array('name'=>$name,'description'=>$descript,'img'=>$img); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Override 'border:none' to Overcome Safari Select Bug? We've just discovered a pretty random bug in Safari (at least on Mac). It seems that Safari doesn't like a border style applied to a <select> tag. It will do different things depending on the version of Safari, from kind of working to no drop-down to refreshing the page. But we've applied border: none; to our select fields to match our styling better. It appears to work OK in other browsers though (including Chrome). So I need to know how to 'override' this style just for Safari. We created a style sheet just for Safari, but I don't think this is going to help since there is no border: auto; value. Tried border: inherit, but this didn't work either. Options? Ideas? THANKS! A: If you mean the little yellow/blue border around text boxes and other inputs, you need to add the property outline:none; to your style. A: I know that Safari doesn't like you to style their select tags even if you add it in as !important. I'm still looking for ways around this. I have custom made select tags made out of div tags, but the sizing is a bit screwed up on Safari because it won't allow me to overwrite it's padding. You can see this if you inspect element, click on "Computed Styles", & check "Show Inherited". A: This post is a bit old but in case it would help anyone, here is my solution even if it's not the best way to do this, but at least it worked for me. I had an issue where the width of my div tag was defined at "600px" by Safari (I never chose this size anywhere), so I added the style directly to my html tag : <div id="container" style="width: auto"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7616747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ how to store data as a 32 bit unsigned int I am looking to store a piece of data as a 32 bit unsigned int in c++. Any ideas of how to do this? I was thinking about using a char somehow but im not sure how it would work A: To use cross platform standards, you can use uint32_t variable; Be sure to include "stdint.h" if you are working on a windows platform. For more information, visit the Wikipedia page for standard integers: http://en.wikipedia.org/wiki/Stdint.h A: #include <cstdint> and then use uint32_t
{ "language": "en", "url": "https://stackoverflow.com/questions/7616748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }
Q: How to implement command line coloration? Possible Duplicate: color text in terminal aplications in unix I am working on a small Unix shell (written completely in C), and am wondering how to copy bash's prompt coloring technique. Are there libraries to do that? Has anyone ever tried them? A: You can use simple shell escape commands like \033[31mRed\033[0m or use the ncurses library. Googling ncurses will give you all you need to get started. A: The easiest way to do colorization in the unix shell is to use a library like curses / ncurses. It provides a portable way to implement items like corolization in the unix shell. Here's a link to a nice tutorial on it * *http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/color.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7616749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery - Delayed HTML function I have an issue with doing two .html()'s in the same function cause the first one is getting overrun by the second. Any thoughts? This function is getting called when another action is taken, it is working fine, but when I put in the delay and the 2nd html() it doesn't work. Thanks. function confirmNote() { $('#noteConfirm').html('Note Sent').delay(1000).html('Leave a Note'); } A: .delay() only works with functions that go through the animation queue which does not include .html(). You can use a setTimeout() to do what you want. function confirmNote() { $('#noteConfirm').html('Note Sent'); setTimeout(function() {$('#noteConfirm').html('Leave a Note')}, 1000); } A: function confirmNote() { $('#noteConfirm').html('Note Sent') setTimeout(function() { $('#noteConfirm').html('Leave a Note'); }, 1000); } Should do the trick. delay only delays animation so is not appropriate in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: One-to-Many relationship on Core Data I am having trouble with Core Data, on a one to many relationship. I have two entities, say Class and Pupils. A class can have many pupils, but a pupil belongs to only one class. I can list the Class items and put them in a UITableView object. I can also list the Pupils items and put them in a UITableView object. My problem is : for a given class say classX, how can I get the corresponding pupils. This is the first time I use "relationship" with Core Data. I tried to find some sample code on the net but with no success. Thanks for any useful tip. A: If your relationship is named "pupils" and you have a managed object for the class called "myClass", then: NSSet *pupilsForClass = [myClass valueForKey:@"pupils"]; for (NSManagedObject *pupil in pupilsForClass) { // Do something for each pupil } If you have NSManagedObject subclasses for Pupil and Class entities, then you can also access properties more directly using setter/getter methods that are generated dynamically by core data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert an NSDictionary to a JSON object? I'm still learning JSON, and using SBJSON. How would I go about taking an NSDictionary and converting it into a JSON object similar to this: {"id":"123","list":"456","done":1,"done_date":1305016383} A: Use the category that SBJSON adds to NSDictionary: NSString *jsonString = [dictionary JSONRepresentation]; Just name the keys and values appropriately in the dictionary and SBJSON will do the work for you A: There is a JSON-API (since iOS5 and OS X 10.7) in the official iOS-SDK it's called: + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error See Guillaume's post for more information how to use it: https://stackoverflow.com/a/9020923/261588 Works like a charm. A: For those that are using JSONKit instead of SBJSON: JSONKit also provides a category for NSDictionary NSString *jsonString = [dictionary JSONStringWithOptions:JKSerializeOptionNone error:nil]
{ "language": "en", "url": "https://stackoverflow.com/questions/7616760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: even when emacsclient is started in a terminal, window-system is non-nil I want to call some functions when I run emacsclient in a terminal emulator. The code I have works when Emacs is started in a text-only terminal. When I start Emacs in graphical mode and run emacsclient -t in a terminal, the functions do not run so I cannot use the mouse in the terminal emulator. Here is the code in question: (defun my-terminal-config (&optional frame) "Establish settings for the current terminal." (message (format "%s" window-system)) ;; "ns" (Mac OS X) when Emacs is started graphically (message (format "%s" (display-graphic-p))) ;; nil when Emacs is started graphically (unless (display-graphic-p) ;; enable mouse reporting for terminal emulators (xterm-mouse-mode 1) (global-set-key [mouse-4] '(lambda () (interactive) (scroll-down 1))) (global-set-key [mouse-5] '(lambda () (interactive) (scroll-up 1))))) (add-hook 'after-make-frame-functions 'my-terminal-config) This is a weird situation. Emacsclient connects to the server and creates a new frame, but because the server is running in a graphical environment, it reports window-system to be "ns" whereas in a terminal environment it would be nil. Therefore when I run emacsclient -t in a terminal, the mouse reporting enabling functions do not run. Once emacsclient is running, if I create a new frame with C-x 5 2, then the mouse reporting enabling functions will run because window-system will be nil in that frame. It seems that when mixing frames between terminals and window systems, the value of window-system will always be that of the Emacs server. Is there a way that I can run Emacs graphically and emacsclient in text mode and have the mouse functions run there? In other words, is it possible to detect that a frame being created will end up in a graphical or text environment? Maybe I should simply always run those functions when a frame is created regardless of the value of window-system? A: the trick is that window-system and display-graphic-p are now frame specific. you need to be in that frame inside your hook function (seems like it should already be the case, but i don't think it is). i had to add this at the beginning of my after-make-frame-functions hook (to make window-system and display-graphic-p behave correctly): (select-frame frame)
{ "language": "en", "url": "https://stackoverflow.com/questions/7616761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to process uploaded photos in Django web app? I am building a web app using Django. I want users to be able to upload photos using an upload form, and then on submission, the server side code takes the photo, make thumbnails for it and also resize the photo to different sizes, each saved as a separate file. These files will be used for display at a later time. Is going with PIL the best way to do this? Also, if I want to upload these photos to S3, what libraries would you recommend? Thanks in advance! A: Take a look at this: http://djangothumbnails.com/ If your asking specifically about how to handle file uploads in Django without a third party module look at my answer on this post: Simple Django Image Upload - Image file not saving and use PIL to do everything yourself. As @John Keyes said, use http://code.google.com/p/boto/ for S3. A: For your S3 (and other AWS needs) boto is great. And for thumbnailing etc. PIL will do the job for you. A: For uploading your images to s3 you can also checkout something like Django queued storage https://github.com/jezdez/django-queued-storage it allows you to upload the file to your local server, and then in the background it uploads it to s3 for you. I'm not sure if it will work for the flow that you are describing out of the box so you might need to play with it a little in order to get the cropping of the images finished before you upload to s3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UINavigationController, rootViewController with UITabBarController I have a UITabBarController. One tab is a UINavigationController where it's rootViewController is a subclass of UIViewController. In my rootViewController, in my viewDidLoad, I push the first of three ViewControllers. Based on which UISegmentedControl is pressed, I pop the old view, and I push the viewController that corresponds to the UISegmentedControl. This works for the most part. The problem is if I'm currently in the Navigation hierarchy, if I hit the same tab again (the tab I am already looking at), it pops the current ViewController off the stack and returns to the rootViewController. I'm not sure why this is happening. I only have one place where I popViewController and I set a break point there, and it never gets called. So my assumption is that when I select the tab of the UITabBarController when I'm already on that tab, it returns to the rootViewController. Is that correct? Is there anything I can do to fix this issue? Thanks. A: Yes, that's the standard behaviour, but you can prevent it by implementing the tab bar delegate method shouldSelectViewController An example of how to do this is here Prevent automatic popToRootViewController on double-tap of UITabBarController A: The functionality you describe is standard of the tabbarcontroller. Some users are used to using it and may be frustrated if you disable it. However, it is possible using the tabBarController: shouldSelectViewController delegate function. In that function you can check if the view controller wanting selection matches the one already displayed. If so, don't allow it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert array of enum values to bit-flag combination How to create a bit-flag combination from an array of enum values in the simplest most optimal way in C# 2.0. I have actually figured out a solution but I am just not satisfied with the complexity here. enum MyEnum { Apple = 0, Apricot = 1, Breadfruit = 2, Banana = 4 } private int ConvertToBitFlags(MyEnum[] flags) { string strFlags = string.Empty; foreach (MyEnum f in flags) { strFlags += strFlags == string.Empty ? Enum.GetName(typeof(MyEnum), f) : "," + Enum.GetName(typeof(MyEnum), f); } return (int)Enum.Parse(typeof(MyEnum), strFlags); } A: Here's a shorter generic extension version: public static T ConvertToFlag<T>(this IEnumerable<T> flags) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new NotSupportedException($"{typeof(T).ToString()} must be an enumerated type"); return (T)(object)flags.Cast<int>().Aggregate(0, (c, n) => c |= n); } And using: [Flags] public enum TestEnum { None = 0, Test1 = 1, Test2 = 2, Test4 = 4 } [Test] public void ConvertToFlagTest() { var testEnumArray = new List<TestEnum> { TestEnum.Test2, TestEnum.Test4 }; var res = testEnumArray.ConvertToFlag(); Assert.AreEqual(TestEnum.Test2 | TestEnum.Test4, res); } A: int result = 0; foreach (MyEnum f in flags) { result |= f; // You might need to cast — (int)f. } return result; OTOH, you should use the FlagsAttribute for improved type safety: [Flags] enum MyEnum { ... } private MyEnum ConvertToBitFlags(MyEnum[] flags) { MyEnum result = 0; foreach (MyEnum f in flags) { result |= f; } return result; } Better still, by using FlagsAttribute you may be able to avoid using a MyEnum[] entirely, thus making this method redundant.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: sending a file using DataOutputStream in java I am trying to build a client that sends the file size and contents to server. I am trying to use DataOutputStream. I am assuming that I need to open the file and and get size of file and read the contents and send it. But I am not sure how to implement those because I am really new to java... Can anyone help me about this? Thank you! A: It's quite simple, but the code is a bit long to write it all and sounds like homework. I can give you some indications. Just open the file, use the long length() method of the class File to get the size, and the writeLong(long) method of DataOutputStream to send the length to the server. Then just read the file a block at a time and use the write(byte[]) method of DataOutputStream to send each block. To read a file a block at a time, you will just create a FileInputStream and use its int read(byte[]) method. Be careful not to assume that this metod will fill up the whole buffer, because it is not guaranteed to do. Read the docs!
{ "language": "en", "url": "https://stackoverflow.com/questions/7616776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android client socket closed randomly ONLY if using 3G connection, NOT wifi connection I have a Java network server running online on a dedicated server, and I have an Android network client written with Android SDK and java. It's working fine if the android device is connected with WIFI, but if I connect the device using 3G, the socket is closed when I call: readInt() from the client. It's not happening at the first call, but later. It looks very random, and it's hard to explain, but it may happen when there is no data too read any more (or not). The exception is SocketException connection reset by peer. I would like to explain more specifically, but it is very hard to debug, and to my point of view, it looks like an Android bug (not sure about that). And that's why i'm asking this question. Because for sure someone has encountered the same problem. What could be the difference between a WIFI connection and a 3G connection for an android device, that would produce such a disconnection ? What could possibly be a fix for this ? Thanks if anyone can help. Edit: My 3G connection is NOT breaking. It's the socket that is beaking, and only the socket. And it only happens if I connect in 3G. Not in WIFI. A: Your connection might be breaking in between, in that case the socket you created before is corrupted/closed. I would suggest you to listen for Network change intent "android.net.conn.CONNECTIVITY_CHANGE" and reset your socket everytime there is a change in network.This should fix your issue A: I found the answer: Several 3G network providers close their customers' sockets in order to make more profit. The only solution is to artificially slow down the traffic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android call log reading Hello guys I am facing a problem when I read the CallLog the values of the number are 0 and when I read for example the cached name its 2 here is my code and I put the permission String[] fields = { android.provider.CallLog.Calls.NUMBER, android.provider.CallLog.Calls.TYPE, android.provider.CallLog.Calls.CACHED_NAME, android.provider.CallLog.Calls.CACHED_NUMBER_TYPE }; String order = android.provider.CallLog.Calls.DATE + " DESC"; Cursor c = getContentResolver().query( android.provider.CallLog.Calls.CONTENT_URI, fields, null, null, order ); if(c.moveToFirst()){ do{ //the problem was here //System.out.println(c.getColumnIndex(android.provider.CallLog.Calls.NUMBER)+" - - "); //the solution is :$ System.out.println(c.getString(c.getColumnIndex(android.provider.CallLog.Calls.NUMBER))+" - - "); } while (c.moveToNext()); } and I have read all the related questions on stackoverflow I figured it out so I will keep the question if any one faced it I was dump :S A: Depends on phone, also not all/any columns are required to be filled in. Up to carrier/manufacturer/whomever else wants to write to the table. But yes the question fix would do it
{ "language": "en", "url": "https://stackoverflow.com/questions/7616788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }