text
stringlengths
8
267k
meta
dict
Q: how to add activity indicator when address book name is selected in my application? i have a task to develop application with address book. i have to develop the app to select name,photo,email,hompage,address from address book.when i select the record it take long time to add record.i want to add activity indicator when user select the record in address book table. Please provide me some source for it.and help me please as fast as possible. A: Try this - [[[UIApplication sharedApplication] keyWindow] addSubview:self.activityIndicator]; and then [self.activityIndicator startAnimating]; where activityIndicator is declared in .h file like - @property(nonatomic,retain) UIActivityIndicatorView *activityIndicator; and synthesized in .m file - @synthesize activityIndicator; A: This will do // declare and synthesize the object UIActivityIndicatorView *activityIndicator; @property (nonatomic, retain) IBOutlet UIActivityIndicatorView *activityIndicator; // on event function write this code [activityIndicator startAnimating];
{ "language": "en", "url": "https://stackoverflow.com/questions/7501535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento - multiple classes extending same core class I'm sure we've all run into a situation where you have multiple extensions with a block or model that rewrites the same core block/model. The problem I've run into is this: How do you control the order in which Magento sees these classes? For example, let's say we have 2 extensions with the following 2 classes: Class A config.xml <catalog> <rewrite> <product_view>My_ClassA_Block_Catalog_Product_View</product_view> </rewrite> </catalog> My/ClassA/Block/Catalog/Product/View.php class My_ClassA_Block_Catalog_Product_View extends Mage_Catalog_Block_Product_View {} Class B <catalog> <rewrite> <product_view>My_ClassB_Block_Catalog_Product_View</product_view> </rewrite> </catalog> My/ClassB/Block/Catalog/Product/View.php class My_ClassB_Block_Catalog_Product_View extends Mage_Catalog_Block_Product_View {} -- The recommended solution is to change one of them so they extend the other and chain them together (class A extends B {}, class B extends C {}, etc): My/ClassA/Block/Catalog/Product/View.php class My_ClassA_Block_Catalog_Product_View extends My_ClassB_Block_Catalog_Product_View {} My/ClassB/Block/Catalog/Product/View.php class My_ClassB_Block_Catalog_Product_View extends Mage_Catalog_Block_Product_View {} -- The problem I've run into is that Magento doesn't necessarily see it that way. I don't know if it's alphabetical or somewhat random, but sometimes this works and sometimes it doesn't. In some cases, Magento gives priority to ClassB and all calls to createBlock('catalog/product_view') create an instance of ClassB, completely bypassing any code in ClassA. So my question is this: How do I control which class gets instantiated by createBlock('catalog/product_view') when 2 different extensions both rewrite the core catalog_product_view class? A: When Magento fetches the class to use for a particular block, it looks inside the merged config.xml tree for a single node at catalog/rewrite/product_view The problem with multiple rewrites is, only one node can be there due to the way Magento loads a module's XML, merges it with the config tree, and then loads another model. This means you can only ever have one class alias resolve to one class name. That's where the files in app/etc/modules/*.xml come into play. These files tell Magento which modules to use. They also have support for a <depends> tag. This tag allows you to say certain modules depend on another module, which means their config.xml will be loaded after another module's config.xml. In this way, you can control which order the modules are loaded in, and therefore control which merged rewrite node "wins", which in turn will allow you to know which class needs to be the final in your inheritance chain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: knowing if the left button of mouse is released on the same list box I have two list boxes, one for Avaiable Items and one for Selected items, so the user can move items between these two by either drag-drop or double-click. It is not a perfect code and most of the logic is written in MouseMove event where I can have X and Y of the mouse location also...I am looking for this scenario to Prevent it: user holds left mouse button on the left list box and select an item BUT he releases the mouse button again on the same list box, so I need a way to know if it is still on the same list box then do not do the drag drop...so is there some method can tell me the boundaries of the list box that I can use? or any other better thoughts that you have? private void lstAvailable_MouseMove(Object eventSender, MouseEventArgs eventArgs) { //*************** FUNCTION DETAILS *************** //User moves mouse in the Available list //***************** INSTRUCTIONS ***************** MouseButtons Button = eventArgs.Button; int Shift = (int)Control.ModifierKeys / 0x10000; float X = (float)VB6.PixelsToTwipsX(eventArgs.X); float Y = (float)VB6.PixelsToTwipsY(eventArgs.Y); moDualListBox.List1_MouseMove(Button, Shift, X, Y); if (eventArgs.Button == MouseButtons.Left ) { if (!mbClickProcessed) // it is a DragDrop { this.lstAvailable.DoDragDrop(this.lstAvailable.SelectedItems, DragDropEffects.Move); mbClickProcessed = true; } if (mbClickProcessed) // it is a DoubleClick { MoveClick(); MoveLostFocus(); mbClickProcessed = true; } } } A: Sample for drag-drop (no error checking): private ListBox _DraggingListBox = null; private void listBox1_DragDrop(object sender, DragEventArgs e) { if (_DraggingListBox != listBox1) MoveItem(listBox2, listBox1, (int)e.Data.GetData(typeof(int))); } private void listBox1_MouseDown(object sender, MouseEventArgs e) { _DraggingListBox = listBox1; listBox1.DoDragDrop(listBox1.IndexFromPoint(e.X,e.Y), DragDropEffects.Move); } private void listBox1_DragOver(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void listBox2_DragDrop(object sender, DragEventArgs e) { if (_DraggingListBox != listBox2) MoveItem(listBox1, listBox2, (int)e.Data.GetData(typeof(int))); } private void listBox2_DragOver(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void listBox2_MouseDown(object sender, MouseEventArgs e) { _DraggingListBox = listBox2; listBox2.DoDragDrop(listBox2.IndexFromPoint(e.X,e.Y), DragDropEffects.Move); } private void MoveItem(ListBox fromLB, ListBox toLB, int index) { toLB.Items.Add(fromLB.Items[index]); fromLB.Items.RemoveAt(index); } A: If you catch DragDrop event you have th sender of drag-drop operation. So you can easily discard the operation (or do nothing) if sender is same as destination control... If you want to know if mouse is leaving a control (and set a variable according to this) you can catch MouseLeave event, while MouseEnter event is handy to know when mouse enters a control from another one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CruiseControl.NET notification when someone stops a build Is there a setting in CruiseControl.NET that can be configured to send out notifications if someone stops a build? We've had cases where a user stopped the build, and forgot about it, and didn't start it up again. Ideally, others on the team would have been notified that the build was stopped manually. Thanks. A: I'm not sure of a setting that will send an email notification. The docs don't seem to indicate so at any rate. The email notificationTypes include the following (and cancel is absent). * *Always *Change *Failed *Success *Fixed *Exception But if you use the cctray.exe program, which comes with CruiseControl.NET, it will tell you when a build is cancelled. You should be able to download and install cctray right from your CCNet dashboard (Screenshot below)
{ "language": "en", "url": "https://stackoverflow.com/questions/7501541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When should I use retain Possible Duplicate: Understanding when to call retain on an object? I have a hard time to understand when I have to retain an object? Is there a general rule? For example: - (IBAction)buttonPressed:(UIButton *)button{ // some code NSString *buttonText = button.titleLabel.text; //retain needed or not ? [buttonText retain]; double result = [someObject someMethod:buttonText]; // some more code } A: - (IBAction)buttonPressed:(UIButton *)button{ // some code NSString *buttonText = [button.titleLabel.text retain]; //retain needed or not ? // if you think your code can release the button object at this point, so you have to retain it. // like : //[button release]; // its safer to retain your object so there wont be any problem. And dont forget to release //[buttonText retain]; double result = [someObject someMethod:buttonText]; // release when you done with it. [buttonText release]; // some more code } A: In that case you don't have to retain buttonText unless you're going to release the button and you need to keep the string. Retain increments the retain count of the object, and there are some rules and conventions to use it. I recommend you to read this Also take a look in Apple's Documentation, there's a lot of literature on this topic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to auto click div over flash object with delay I hope to be clear :) I'm looking for a way to click automatic a flash object on page load after about 5 seconds. I have try to put a blank div over the flash, when i click on the div it click also the flash object this is good but I want this do automatic with no user interaction just done by JavaScript on page load this is my code => <!DOCTYPE html PUBLIC "-//W3C//DTD html 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> Newbie at work </title> <script> $("#pipo").trigger("click"); </script> </head> <body> <div id="pipo"> <object width="280" height="280"> <param name="movie" value="http://www.newbies.com/media/swf/player/bobo.swf"></param> <param name="allowFullScreen" value="true"></param> <param name="wmode" value="opaque"></param> <param name="allowscriptaccess" value="always"> <embed src="http://www.newbies.com/media/swf/player/bobo.swf" width="280" height="280" type="application/x-shockwave-flash" wmode="opaque" allowscriptaccess="always" allowfullscreen="true" movie="http://www.newbies.com/media/swf/player/bobo.swf" > </embed></object> </div> </body> </html> A: If i correctly understand your question you need a time out $(function(){ setTimeout( function(){ $("#pipo").trigger("click"); //optional $("#pipo").click(); } ,5000); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7501551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to manage asynchronous / push communication with web clients on a Spring based Java server I need to push events to web clients in a cross-browser manner (iPhone, iPad, Android, IE/FF/Chrome/etc.) from a Spring based Java server. I am using backbone.js on the client side. To my best knowledge, I can either go with a Web socket only approach, or I can use something like socket.io. What is the best practice for this issue, and which platform/frameworks should I use? Thanks A: Looks like you're interested in an AJAX Push engine. ICEPush (same group that makes ICEFaces) provides these capabilities, and works with a variety of server- and client-side frameworks. There is also APE. A: You can have a look at Lightstreamer. My company is currently using it to push real time financial data from a web server. A: I suppose Grizzly or Netty may fit your needs. Don't have a real experience in that scope, unfortunately. A: I'd recommend socket.io as you mentioned in your question, if you're doing browser based eventing from a remote host. Socket.io handles all the connection keep-alives and reconnections directly from javascript and has facilities for channeling messages to specific sessions (users). The real advantage comes from the two-way communication of WebSockets without all the boilerplate code of maintaining the connection. You will need to do some digging for a java implementation thoughConsider running the server directly from V8.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Mojarra: Serve non minified Javascript files I have to debug part of the mojarra 2.1.3 javascript sources. Unfortunately, they are right now delivered in a minified version (jsf.js). I found jsf_uncompresses.js in the sources, how can I tell mojarra to use this? Do I have to replace jsf.js? A: There is one better solution, add this snippet to your web.xml: <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> A: It turned out, that the easiest way was to just dezip jsf-impl.jar provided by Glassfish 3.1, change jsf.js to jsf-uncompressed.js and then zip it again and rename it to .tar. Hope this could help somebody A: You can simply copy uncompressed version of the .js file in your project and then include it in your page. This will override version insluded by JSF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert property to django model field Is there any way to create virtual model field in django? For example I have class A(models.Model): field_1 = models.CharField(max_length=100) field_2 = models.CharField(max_length=100) @apply def virtual_field(): def fget(self): return self.field1 + '/' + self.field2 def fset(self, value): self.field_1, self_field_2 = value.split('/') return True return property(**locals()) Now, if I will run: a = A() a.virtual_field = '5/5' a.save() it will work fine. But I have a dump, where I have model A with virtual_field value - on serialization I've got an error "A object has no virtual_field"... How I can cheat serializer and tell it, that virtual_field exists? A: If you want to load from legacy fixture, you could build some intermediate model/table, convert file or customize dumpdata command. Fool dumpdata is possible, as following, but hmm... class VirtualField(object): rel = None def contribute_to_class(self, cls, name): self.attname = self.name = name # cls._meta.add_virtual_field(self) get_field = cls._meta.get_field cls._meta.get_field = lambda name, many_to_many=True: self if name == self.name else get_field(name, many_to_many) models.signals.pre_init.connect(self.pre_init, sender=cls) #, weak=False) models.signals.post_init.connect(self.post_init, sender=cls) #, weak=False) setattr(cls, name, self) def pre_init(self, signal, sender, args, kwargs, **_kwargs): sender._meta._field_name_cache.append(self) def post_init(self, signal, sender, **kwargs): sender._meta._field_name_cache[:] = sender._meta._field_name_cache[:-1] def __get__(self, instance, instance_type=None): if instance is None: return self return instance.field1 + '/' + instance.field2 def __set__(self, instance, value): if instance is None: raise AttributeError(u"%s must be accessed via instance" % self.related.opts.object_name) instance.field1, instance.field2 = value.split('/') def to_python(self, value): return value class A(models.Model): field1 = models.TextField() field2 = models.TextField() virtual_field = VirtualField() # legacy.json [{"pk": 1, "model": "so.a", "fields": {"virtual_field": "A/B"}}, {"pk": 2, "model": "so.a", "fields": {"virtual_field": "199/200"}}] $ ./manage.py loaddump legacy.json Installed 2 object(s) from 1 fixture(s) Or you could add customized serializer to public serializers and mainly override its Deserializer function to work w/ properties that you have. Mainly override to tweak two lines in Deserializer inside django/core/serializers/python.py field = Model._meta.get_field(field_name) # and yield base.DeserializedObject(Model(**data), m2m_data)
{ "language": "en", "url": "https://stackoverflow.com/questions/7501557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Open source wiki on rails/ couchDB Is there any good implementation of open source wiki using Rails and couchdb? If not then which is the best option on rails platform, of course open source. Thanks A: The only one I know of is Instiki (please note that the maintained home is NOT instiki.org, use the page I linked to). However it uses SQLite or MySQL. A: take a look at github's gollum. it's a git based wiki system. absolutely awesome.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get row view data in the listview this example: http://saigeethamn.blogspot.com/2010/04/custom-listview-android-developer.html .There are 3 textview ids at custom_row_view.xml. There are 3 row data inside one position listitem when using onListItemClick. how to extract these data? how to use the id? Anyway to get row view data in the list view when the list item is clicked [protected void onListItemClick(ListView l, View v, int position, long id]? A: The parameter View v itself is the row view. You can get the attached data by calling v.getTag(). Should set it earlier in getView of adapter using v.setTag(Object) A: Depends on the kind of data. For example id does contain the _id from a database table row that was set with one of the CursorAdapters. Usually this is the PK of that database table row. A: listView.getAdapter().getItemAt(position) gets you the object bound to the view V A: I would like to recommend you not to get data from the view, instead use the ArrayList you have used to set data to the Adapter of the ListView. In the example which you have pointed out, you are using an ArrayList of HashMap. So for an example.. listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // arrayList is the variable which you have used as a list in your SimpleAdapter hashMap = arrayList.get((int)id); // you need to typecast 'id' from long to int value = hashMap.get(KEY); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7501562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the mainThread to run again? Hi, I have a winform application that is hosting a WCF Service(NamedPipes). When reciving a call a event will be triggered and then a form will be created and opened. The problem is that I get the followin exception ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment. When creating a System.Windows.Forms.WebBrowser in the winforms InitializeComponent method? I Supose that another thread is running the even(working thread), how can I get the main thread to run the event? I do not have any winform open at the time so I can´t use InvokeRequired. BestRegards Edit1 : Pleas not that I am using [STAThread] public static void Main(string[] args) { Application.Run(_instance); } A: These kind of calls are made on thread pool threads. They are not suitable to display any UI. You'll need to create your own thread of the right flavor: var t = new Thread(() => { Application.Run(new Form1()); }); t.SetApartmentState(ApartmentState.STA); t.Start(); There are other practical problems you'll be battling with this, you can't just pop up a window without the user participating. Typical mishaps are the user accidentally closing it without even seeing it or the window disappearing behind the window that the user is working with. If you already have a user interface then be sure to use Control.BeginInvoke() to let the main thread display the window. Consider the soft touch with a NotifyIcon, displaying a balloon in the tray notification area to alert the user. A: That WCF call is most likely coming in on a thread other than the main UI thread. All UI controls including ActiveX ones must be created and accessed from the UI thread and only the UI thread. The error you are getting is indicating that the creating thread is not even in a Single Thread Apartment (STA) which is also a requirement. To get the code executing on the main UI thread use the Control.Invoke method. It will marshal the execution of a delegate onto the thread hosting the target Control or Form. If you do not have a reference to a Control or Form immediately available then you will need to create one. You may have to create a thread that runs a message loop as well. This can be done with Application.Run. It is simple enough to create a hidden Form that could be used to call Invoke. Here is what it might look like. void SomeMethodExecutingOnThreadPool() { var form = null; var mre = new ManualResetEvent(false); // Create the UI thread. new Thread( () => { form = new Form(); form.Load += (sender, args) => { mre.Set(); } Application.Run(form); }).Start(); // Wait for the UI thread to initialize. mre.WaitOne(); // You can now call Invoke. form.Invoke(/* ... */); } A: My solution is to create a dummy winform on startup and when I need the main UI thread I will use invoke on this dummyform. It will use some more resourse but I dont see a simpler way of doing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery: bind within some action causes mutliple executions Okay, i just asked for unbinding particular keypress events. I solved this now with namespaced events. But I got another problem...the function below binds a keypress event after a div is shown by animate() . It works well but the keypress event seems to count the times, the function is executed...in my case the myFnc() executes when a link is clicked...so when i click the link the keypress.f event is fired one time...but when the link is clicked more than one time before i press the key, the keypress event also executed more then one time although i pressed the key only one time....so the fadeToggle() will execute 5 times with one keypress, when the function is executed 5 times before through five clicks ...does anyone understand what i mean and can help me with this? function myFnc() { $('#somediv').animate({ height: 'toggle' }, 600, function() { $(document).bind('keypress.f', function(event) { if($('#secret').is(':visible')) { if ( event.which == 102 ) { $('.content-2').fadeToggle(); $('.content-284').fadeToggle(); } } else { $(document).unbind('keypress.f'); } }); }); } A: Use .is() method and the :animated selector to only apply the animation if it is currently not in progress.. (if the issue is multiple clicks while the animation is in progress) function myFnc() { var $somediv = $('#somediv'); if (!$somediv.is(':animated')) { $somediv.animate({ height: 'toggle' }, 600, function() { $(document).bind('keypress.f', function(event) { if ($('#secret').is(':visible')) { if (event.which == 102) { $('.content-2').fadeToggle(); $('.content-284').fadeToggle(); } } else { $(document).unbind('keypress.f'); } }); }); } } another solution would be to always unbind the keypress before binding a new one.. $(document).unbind('keypress.f'); $(document).bind('keypress.f', function(event) {...}); This way it will always be just one.. A: You could solve this with something like var bound_keypress_f = false; function myFnc() { $('#somediv').animate({ height: 'toggle' }, 600, function() { if (!bound_keypress_f) { $(document).bind('keypress.f', function(event) { if($('#secret').is(':visible')) { if ( event.which == 102 ) { $('.content-2').fadeToggle(); $('.content-284').fadeToggle(); } bound_keypress_f = true; } else { $(document).unbind('keypress.f'); bound_keypress_f = false; } }); } }); } A: You are binding 5 keypress.f events (one is bound each time you click the link). You can get around this in a couple different ways: 1) Unbind all keypress.f events before binding the keypress.f event. 2) Bind the keypress.f event when the page loads, and add an if(flag) to the beginning of the function. Whenever the link is clicked, set the flag to true. Set the flag to false when you don't want keypress.f to fire the function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: posts containing html tags displayed unformatted I am writing a simple cms-like solution to keep track of my silly ideas. Everything is going great, but I am now having some difficulties implementing the Xinha RTE plugin into my application. I have followed their on-site tutorial, and it seems to be working but... When making formatting to a text, headings paragraphs etc. Though the tags are saved correctly in the mysql database: <h1>heading</h1> <p>text example</p> they are displayed as: <h1>heading</h1><p>text example</p> (concatenated and NOT formatted , displaying tags in stead) or &lt;p&gt;tesy&lt;/p&gt; &lt;h4&gt;fgfg&lt;br /&gt;&lt;/h4&gt; &lt;h2&gt; &lt;/h2&gt; the last example output is because I made this change: //$postCon = mysql_real_escape_string($postCon); $postCon = htmlspecialchars($postCon); That was only because someone at their forum said that it would be "dumb" to escape html special chars - since html tags are made up of them. I have a really hard time specifying the actual problem. hence my question is a little sloppy. I hope that some out there have been where I am now, and can provide some explanation or guidance in the right direction. I will go drink coffee and ponder on this for now, and bring updates if I got anything new. For now I will just leave you with the actual script which does the post handling. thanks, <?php include_once 'bin/configDb.php'; include_once 'bin/connectDb.php'; include_once 'header.php'; //get stuff from post $topicSub = $_POST['topic_subject']; //$topicSub = mysql_real_escape_string($topicSub); $topicSub = htmlspecialchars($topicSub); $topicCat = $_POST['topicCat']; // $topicCat = mysql_real_escape_string($topicCat); $sesId = $_GET['username']; //the form has been posted, so save it //insert the topic into the topics table first, then we'll save the post into the posts table $postCon = $_POST['post_content']; //$postCon = mysql_real_escape_string($postCon); $postCon = htmlspecialchars($postCon); $sql = "INSERT INTO topics(topic_subject, topic_date, topic_cat, topic_by) VALUES('$topicSub', NOW(), '$topicCat', '$sesId' )"; $result = mysql_query($sql); if(!$result) { //something went wrong, display the error echo 'An error occured while inserting your data. Please try again later.' . mysql_error(); $sql = "ROLLBACK;"; $result = mysql_query($sql); } else { //the first query worked, now start the second, posts query //retrieve the id of the freshly created topic for usage in the posts query $topicId = mysql_insert_id(); $sql = "INSERT INTO posts(post_content, post_date, post_topic, post_by) VALUES ('$postCon', NOW(), '$topicId', '$sesId' )"; $result = mysql_query($sql); if(!$result) { //something went wrong, display the error echo 'An error occured while inserting your post. Please try again later.' . mysql_error(); $sql = "ROLLBACK;"; $result = mysql_query($sql); } else { $sql = "COMMIT;"; $result = mysql_query($sql); //after a lot of work, the query succeeded! echo 'You have successfully created <a href="topic.php?id='. $topicid . '">your new topic</a>.'; header("location:admin.php"); } } include_once 'footer.php'; ?> A: You've missed the purpose of mysql_real_escape_string. It's there to make arbitrary string data SAFE to use in an SQL query. It's an SQL injection attack prevention method. htmlspecialchars will not help at all to prevent SQL injection attacks. You're using a screwdriver to drive in a nail. It may work in some cases, but won't ever cover all the cases. And it's those "uncovered" cases that will allow someone to attack your site by waltzing in through the front door. A: I found the issue to be in a completely different area of the code. It was in the code that displayed the content, silly me. It was a htmlentities(stripslashes()) doing the funny business. Thanks for letting me put it out there. Marc B, thanks for once again dealing with my sql injection issues. Feel free to pitch more recommendations my way. I did take your last advice into use :) personal thanks to you
{ "language": "en", "url": "https://stackoverflow.com/questions/7501569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cPickle - different results pickling the same object Is anyone able to explain the comment under testLookups() in this code snippet? I've run the code and indeed what the comment sais is true. However I'd like to understand why it's true, i.e. why is cPickle outputting different values for the same object depending on how it is referenced. Does it have anything to do with reference count? If so, isn't that some kind of a bug - i.e. the pickled and deserialized object would have an abnormally high reference count and in effect would never get garbage collected? A: There is no guarantee that seemingly identical objects will produce identical pickle strings. The pickle protocol is a virtual machine, and a pickle string is a program for that virtual machine. For a given object there exist multiple pickle strings (=programs) that will reconstruct that object exactly. To take one of your examples: >>> from cPickle import dumps >>> t = ({1: 1, 2: 4, 3: 6, 4: 8, 5: 10}, 'Hello World', (1, 2, 3, 4, 5), [1, 2, 3, 4, 5]) >>> dumps(({1: 1, 2: 4, 3: 6, 4: 8, 5: 10}, 'Hello World', (1, 2, 3, 4, 5), [1, 2, 3, 4, 5])) "((dp1\nI1\nI1\nsI2\nI4\nsI3\nI6\nsI4\nI8\nsI5\nI10\nsS'Hello World'\np2\n(I1\nI2\nI3\nI4\nI5\ntp3\n(lp4\nI1\naI2\naI3\naI4\naI5\nat." >>> dumps(t) "((dp1\nI1\nI1\nsI2\nI4\nsI3\nI6\nsI4\nI8\nsI5\nI10\nsS'Hello World'\n(I1\nI2\nI3\nI4\nI5\nt(lp2\nI1\naI2\naI3\naI4\naI5\natp3\n." The two pickle strings differ in their use of the p opcode. The opcode takes one integer argument and its function is as follows: name='PUT' code='p' arg=decimalnl_short Store the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the newline- terminated decimal string following. BINPUT and LONG_BINPUT are space-optimized versions. To cut a long story short, the two pickle strings are basically equivalent. I haven't tried to nail down the exact cause of the differences in generated opcodes. This could well have to do with reference counts of the objects being serialized. What is clear, however, that discrepancies like this will have no effect on the reconstructed object. A: It is looking at the reference counts, from the cPickle source: if (Py_REFCNT(args) > 1) { if (!( py_ob_id = PyLong_FromVoidPtr(args))) goto finally; if (PyDict_GetItem(self->memo, py_ob_id)) { if (get(self, py_ob_id) < 0) goto finally; res = 0; goto finally; } } The pickle protocol has to deal with pickling multiple references to the same object. In order to prevent duplicating the object when depickled it uses a memo. The memo basically maps indexes to the various objects. The PUT (p) opcode in the pickle stores the current object in this memo dictionary. However, if there is only a single reference to an object, there is no reason to store it it the memo because it is impossible to need to reference it again because it only has one reference. Thus the cPickle code checks the reference count for a little optimization at this point. So yes, its the reference counts. But not that's not a problem. The objects unpickled will have the correct reference counts, it just produces a slightly shorter pickle when the reference counts are at 1. Now, I don't know what you are you doing that you care about this. But you really shouldn't assume that pickling the same object will always give you the same result. If nothing else, I'd expect dictionaries to give you problems because the order of the keys is undefined. Unless you have python documentation that guarantees the pickle is the same each time I highly recommend you don't depend on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Website structure / Newbie I created a website using php, passing values from page to page either with POST or GET. Though there is some cons, I dont know how to track specifically what data has been viewed in GoogleAnalytics as it just shows the name of the page (xxxx.php) On the other side, I see websites structured differently with a bunch of subdirectories created : www.xxx.com/xxxxxx/xxxxx/xxx This looks like pretty manual for me , compared to the .php?xxxx=xxxx way of structuring. Do you know how this subdirectory style structuring can be automatically obtained? A: This is done with Apache rewrite rules. To make it so that whenever a user goes to /posts/visiting_new_york, it actually goes to to /viewpost.php?id=visiting_new_york, you create a file in your site called .htaccess like this: RewriteEngine On RewriteRule '^posts/([^/]+)$' viewpost.php?id=$1 [L] A: Use an MVC framework like rails, or simply configure your webserver's virtual directory structure to be identical to the local servers file system and adhere to that scheme when saving your php files. A: Yes, you can do this with "mod_rewrite" in apache. It involves creating a .htaccess file with URL re-writing rules inside. So you can transform /index.php?page=contact&lang=en into /en/contact/ Here's a good rewrite cheat sheet: http://www.addedbytes.com/cheat-sheets/mod_rewrite-cheat-sheet/ Wadih A: You need to read about url rewriting http://httpd.apache.org/docs/2.0/misc/rewriteguide.html If you just want to track your dynamic pages , there is another solution in Google analytic http://www.google.com/support/googleanalytics/bin/answer.py?answer=55504
{ "language": "en", "url": "https://stackoverflow.com/questions/7501578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does one use SQLite in Perl 6? I want to start dabbling in Perl 6. A large percentage of my programming involves SQLite databases. It looks like work has been put into using SQLite in Perl 6, but most of the info I can find is old and vague. I see a "perl6-sqlite" module here, but it's marked as [old] and has very little to it. I've also seen references to a new DBI based on something to do with Java, but most of that talk is from last year and it's unclear whether there's something that works. So is there currently an accepted way to use SQLite within Perl 6? A: (Updated 2015-01): DBIish from https://github.com/perl6/DBIish/ has decent support for SQLite and PostgreSQL, and limited support for mysql. The README shows how to use it with an SQLite backend.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using regex to find items encapsulated in [] and then replace them So i have some strings which I want to replace some occurrences of brackets in. Now this is what I've done so far. And it works string answerText = "This is an [example] string"; Match match = Regex.Match(answerText, @"\[(.*?)\]"); if(match.Success) { if(match.Value.Equals("[example]")) { answerText = answerText.Replace(match.Value, "awsome"); } } What I'm trying to figure out is how to make this happen if the answer text looks something like this string answerText = "This is an [example1] [example2] [example3] string"; A: Is there any reason why you're not doing this instead of using regexes? string answerText = "This is an [example] string"; answerText.Replace("[example]", "awsome"); A: What about this string answerText = "This is an [example1] [example2] [example3] string"; string pattern = @"\[(.*?)\]"; answerText = Regex.Replace(answerText, pattern, "awesome"); A: You can use Replace method of Regex something like below. Regex.Replace(inputString, "\\[" + matchValue + "\\]", "ReplaceText", RegexOptions.IgnoreCase); Hope this helps!! A: Solved this by using the solution I suggested in my original post looping through the string several times until I got no match.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CKEditor Padding Adding the following style to my page removes the rounded corners from FireFox and Chrome. (IE didn't have rounded corners to start with). In FireFox and Chrome it also removes the padding between the editor and the border but in IE it does not. I am totally stomped as to why the padding is not being removed in IE span.cke_skin_kama { -moz-border-radius: 0px; -webkit-border-radius: 0px; -o-border-radius: 0px; border: 1px solid #D3D3D3; padding: 0px; } A: This solved the problem span.cke_skin_kama { -moz-border-radius: 0px; -webkit-border-radius: 0px; -o-border-radius: 0px; border: 1px solid #D3D3D3; padding: 0px !important; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handle stopping of VB.NET Windows service I have created a Windows Service in VB.NET (VS2010) that executes a certain task every minute. When the service is being stopped, either manually by the user, or when the system is rebooted, what can I do to make sure the task is being finished properly before the service is actually terminated? A: You should override the Service's OnStop event. ' when stopping release the resources Protected Overrides Sub OnStop() ReleaseYourObjects() End Sub Here you should finish your task and release all resources that need to be released. The constructor of the service will not be called again when it's restarted. Because of this, you should not use the constructor to perform startup processing, rather use the OnStart() method to handle all initialization of your service, and OnStop() to release any resources. Reduced to your needs, it might be sufficient to stop the timer so that it could simply be restarted in OnStart: Me.ServiceTimer.Change(Timeout.Infinite, Timeout.Infinite) If your task is started from it's own thread, you can ensure that it will be finished properly. When it's instead running in the main-thread and... ... when the Windows Service Control Manager (SCM) calls the OnStart(), OnStop(), OnPause(), or OnContinue() method, you only have ~60 sec before you must return. If you do not return within this time, then the SCM will mark that service as not responding. After a while, it can out right kill the process you are running in. If you need more time to process things during these methods, you can call the RequestAdditionalTime() method and tell the SCM that things are talking a bit longer that it expects. (See the OnStop() method in the example above.) Read more: http://www.codeproject.com/KB/system/LexnnWinService.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7501588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Click event won't register in iPad Ok, so I'm creating a gallery site for iPad. It needs to be able to swipe and when you click on the thumbnails, it loads the gallery images with AJAX. The html looks something like this: <section id="col1"> <nav> <div class="appGallery"> <div class="imageHandler"></div> <ul> <li><a href="1.html"><img src="1.jpg" alt="" /></a></li> <li><a href="2.html"><img src="2.jpg" alt="" /></a></li> <li><a href="3.html"><img src="3.jpg" alt="" /></a></li> <li><a href="4.html"><img src="4.jpg" alt="" /></a></li> </ul> </div> </nav> </section> I am using a swipe plugin and basically what the imageHandler does is to track the movement (touch/mouse events). It has a higher z-index that overrides the unordered list so this basically means the 'a' link won't work. I've written a whole new algorithm to detect which thumbnails is being clicked on $('#col1 nav') based on height and event.pageY. My algorithm works perfectly on desktop but not iPad. The click event just won't register. Here's how the JavaScript looks like: var dragging = false; imageHandler.bind('touchmove', function(event) { dragging = true; }); imageHandler.bind('touchend', function(event) { var touch = event.originalEvent.touches[0] || event.originalEvent.changedTouches[0]; if (dragging) { //swipe column dragging = false; } else { //I've done some testing myself by including an alert() here, it pops out. $('#col1 nav').click(function(event) { //but when I insert and alert() here, nothing happens var touch = event.originalEvent.touches[0] || event.originalEvent.changedTouches[0]; //my algorithm to select the thumbnails using touch.pageY //ajax using .load }); dragging = false; } return false; }); Anyone has any idea what is wrong? A: Looks like you're binding it inside the "touchend" event. So click is only registered once you stop dragging. Have you tried binding it outside the function using a live event? Like so: $('#col1 nav').live("click", function(event) {
{ "language": "en", "url": "https://stackoverflow.com/questions/7501590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validation with OpenRasta We're starting a new project, on the client side, we'll use a asp.net mvc3 application, accessing resources exposed by OpenRasta. asp.net mvc has built in validation with Data Annotations, how usually people do validation with OpenRasta? A: It depends the kind of validation you want. We don't currently support anything out of the box because the scenarios of what people wanted has always been very nebulous. People usually apply validation on the constructed model themselves rather than get OW to do it. Happy to discuss your requirements and implement them as needed in 2.1, there's still a small open window for certain new features.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to give an argument when a condition has been met in PHP? When i want to mail my users to notify them of some event, i will call the mail() function in PHP. I want to give the mail function a fifth argument, but since this is disabled when in safe_mode, the mail() function will return false when giving this argument. My question is basically: How can i write this piece of code: if (!$bSafeMode) { mail($sTo, $sSubject, $sBody, $sHeader, $sFifthArgument); } else { mail($sTo, $sSubject, $sBody, $sHeader); } But in a way like this: mail($sTo, $sSubject, $sBody, $sHeader, (!$bSafeMode? $sFifthArgument : '')); Obviously this code i showed you doesn't work, but i want to know if there is something similar to this, so that i can keep my code tidier. And please don't argue with me as to why i want it this way and why i want to check for safe_mode and stuff. I just do, i only want to know if what i want is possible and how i would go about doing it. Thanks in advance! A: of course, you can do something like $args = array('foo', 'bar'); if($blah) $args[] = 'baz'; call_user_func_array('mail', $args); but I don't think this is anyhow better than your first snippet A: You'd have to pass null to the function (in the case of mail that's the default value too for the fifth argument as far as I know). So it'd be like: mail($sTo, $sSubject, $sBody, $sHeader, (!$bSafeMode ? $sFifthArgument : null)); That should be allowed. See also as example: http://codepad.org/HerLr9O4 :) As Phil mentioned in the comment below; it will probably check for the passed amount of parameters (I can't test this here; but I would expect that). That basically means you're stuck with the if-else; which is perfectly readable (and maybe even better documentable too!) :).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xml Convert.ToDouble works wrong I have a project that reads some data from xml file Convert.ToDouble metod works wrong. it converts 0.05 as 5. is there any idea to solve this problem? this is my ReadDataFromXml method: public static List<double> XmldenTabanDegerleriniOku(string ID) { string ayarDir = System.Environment.CurrentDirectory + "\\Ayarlar"; string Dosya = ayarDir + "\\YuzeyBoyutlari.xml"; XmlDocument doc = new XmlDocument(); doc.Load(Dosya); XmlNodeList holList = doc.GetElementsByTagName("HOL"); List<double> tabanDegerleri = new List<double>(); foreach (XmlNode node in holList) { XmlElement holElement = (XmlElement)node; if (node.Attributes["ID"].Value == ID) { double uzunluk =Convert.ToDouble(holElement.GetElementsByTagName("uzunluk")[0].InnerText.Replace('.',',')); double genislik =Convert.ToDouble(holElement.GetElementsByTagName("genislik")[0].InnerText.Replace('.',',')); double cizgilerArasiMesafe = Convert.ToDouble(holElement.GetElementsByTagName("cizgilerArasiMesafe")[0].InnerText.Replace('.', ',')); tabanDegerleri.Add(uzunluk); tabanDegerleri.Add(genislik); tabanDegerleri.Add(cizgilerArasiMesafe); break; } } return tabanDegerleri; } A: Don't use Convert.ToDouble then: use XmlConvert.ToDouble. I believe that effectively uses the invariant culture (as XML documents conveying data shouldn't be culture-specific in that sense). EDIT: I hadn't noticed that you were manually replacing '.' with ',' - so when you say that "it is converting 0.05 as 5" you really mean "it is converting 0,05 as 5". You should use XmlConvert and stop messing with the data yourself. A: The problem Your are replacing . by , before converting. That means when you get 0.05 you convert it to 0,05. That conversion will behave according to your locale. In US, for instance, that is 5. The Solution Take a look at @JonSkeet's answer and use XmlConvert.ToDouble which is culture invariant (it uses XML standarts for data formatting). And, of course, drop the string replacements. A: You should use the correct CultureInfo instead of replacing the dots with comas. You can do this using this signature of the Convert.ToDouble method. Something like: double uzunluk =Convert.ToDouble(holElement.GetElementsByTagName("uzunluk")[0].InnerText, CultureInfo.CurrentCulture); If you still have a problem with dots and comas, it means that the culture of your Xml file is not coherent with the current culture (which is the culture of the machine executing the line of code), for example your Windows installation is set to have comas as decimal separators (in this case it seems CurrentCulture is the Turkish culture, and your xml has a different one, like US Culture). In this case, you have to call Convert using the actual culture of your xml, understanding where it has been generated. If it has dots as decimal separators, then you can try getting the common invariant culture (CultureInfo.InvariantCulture), which indeed uses dots, or maybe be more specific. (see GetCultureInfo). A: I notice you're doing some text replacement of . to ,. Does this mean you are in a culture where there's a decimal comma rather than decimal point? In this case "0.05" is 5. If you wanted the fraction the string would have to be "0,05". A: Does the double conversion work if you convert the value before changing the decimal point to a comma? I think you have a locale issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python re.split() vs split() In my quests of optimization, I discovered that that built-in split() method is about 40% faster that the re.split() equivalent. A dummy benchmark (easily copy-pasteable): import re, time, random def random_string(_len): letters = "ABC" return "".join([letters[random.randint(0,len(letters)-1)] for i in range(_len) ]) r = random_string(2000000) pattern = re.compile(r"A") start = time.time() pattern.split(r) print "with re.split : ", time.time() - start start = time.time() r.split("A") print "with built-in split : ", time.time() - start Why this difference? A: Running a regular expression means that you are running a state machine for each character. Doing a split with a constant string means that you are just searching for the string. The second is a much less complicated procedure. A: re.split is expected to be slower, as the usage of regular expressions incurs some overhead. Of course if you are splitting on a constant string, there is no point in using re.split(). A: When in doubt, check the source code. You can see that Python s.split() is optimized for whitespace and inlined. But s.split() is for fixed delimiters only. For the speed tradeoff, a re.split regular expression based split is far more flexible. >>> re.split(':+',"One:two::t h r e e:::fourth field") ['One', 'two', 't h r e e', 'fourth field'] >>> "One:two::t h r e e:::fourth field".split(':') ['One', 'two', '', 't h r e e', '', '', 'fourth field'] # would require an addition step to find the empty fields... >>> re.split('[:\d]+',"One:two:2:t h r e e:3::fourth field") ['One', 'two', 't h r e e', 'fourth field'] # try that without a regex split in an understandable way... That re.split() is only 29% slower (or that s.split() is only 40% faster) is what should be amazing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Create color variations in cpp I have a given color and want to create variations of it in terms of hue, saturation and lightness. I found a webpage which creates variations the way I would like it (See http://coloreminder.com/). However, I do not entirely understand how these variations are created for an arbitrary color. From what I can tell from considering created variations at this home page, it seems not to be enough to simply change the HSL values separately to create variations. Hence, I wanted to ask if anybody knows an approach for creating these variations, or ideally knows where to get a piece of code to adopt this kind of color variations creation in my own program? I am using C++ and QT. EDIT: Thank you for your replies! Actually the variations of the given homepage really only varies the HSL values separately in 10% steps. I got confused since I compared the values with HSV values in color picker of my program. A: From what I can tell from considering created variations at this home page, it seems not to be enough to simply change the HSL values seperately to create variations. Really? The interface seems to be clear enough about what modifications it makes. You can select "hue", "saturation" or "luminance" and it shows 9 variations on that channel. The following MATLAB script will plot the different variations in a similar way (although in the HSV color space, not HSL). % display n variations of HTML-style color code. function [] = colorwheel ( hex, n ) % parse color code. rgb = hex2rgb(hex); % render all variations. h = figure(); for j = 1 : 3, % build n variations on current channel. colors = variantsof(rgb, j, n); % display variations. for i = 1 : n, % generate patch of specified color. I = zeros(128, 128, 3); I(:,:,1) = colors(i, 1); I(:,:,2) = colors(i, 2); I(:,:,3) = colors(i, 3); % render patches side-by-side to show progression. imshow(I, 'parent', ... subplot(3, n, (j-1)*n+i, 'parent', h)); end end end % parse HTML-style color code. function [ rgb ] = hex2rgb ( hex ) r = double(hex2dec(hex(1:2))) / 255; g = double(hex2dec(hex(3:4))) / 255; b = double(hex2dec(hex(5:6))) / 255; rgb = [r g b]; end % generate n variants of color on j-th channel. function [ colors ] = variantsof ( rgb, j, n ) colors = zeros(n, 3); for i = 1 : n, % convert to HSV. color = rgb2hsv(rgb); % apply variation to selected channel. color(j) = color(j) + ((i-1) / n); if color(j) > 1.0, color(j) = color(j) - 1.0; end % convert to RGB. colors(i,:) = hsv2rgb(color); end % order colors with respect to channel. if j > 1, colors = sortrows(colors, j); end end Using the "goldenrod" sample color, as: colorwheel('daa520', 9); I get: The first row is a variation on hue, the second on saturation and the third on value. The outputs don't correspond exactly to the ones on the coloreminder.com, but this is explained by the difference in color space and exact value used in permutations. A: Have you read through the documentation for QColor? The QColor class itself provides plenty of useful functions for manipulating colors in pretty much any way you can think of, and the documentation itself explains some basic color theory as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: erlang gen_tcp:connect/3 not working with rpc:call/4, anyone knows why? Could not solve this by myself * *launched a new node A with ssh command *started a new node B *gen_tcp:connect/3 works on B, but rpc:call(B,gen_tcp,connect,Params) not works. Both nodes are running on local laptop and one node returns ok and the other node returns error. I don't understand. Anyone knows why? ~ $ssh allen@127.0.0.1 'erl -name loadtest@127.0.0.1 -detached -setcookie loadtest' ~ $erl -name allen@127.0.0.1 -setcookie loadtest Erlang R14B03 (erts-5.8.4) [source] [64-bit] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.8.4 (abort with ^G) (allen@127.0.0.1)1> gen_tcp:connect("www.google.com",80,[]). {ok,#Port<0.630>} (allen@127.0.0.1)2> rpc:call('loadtest@127.0.0.1',gen_tcp,connect,["www.google.com",80,[]]). {error,nxdomain}
{ "language": "en", "url": "https://stackoverflow.com/questions/7501624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS Reachability: Problem with host Method I have create a method to check if the host is reachable. I had download the Reachability class (both .h & .m) from apple developer websites and import to my project. I have pass the NSString Name as the URL (host Name). The hostName is http://www.google.com. However, no matter what host name I pass to this method and its always return NO (connectToHost). The code as below: - (BOOL) checkHostAvailability:(NSString *)Name{ BOOL connectToHost; hostReach = [[Reachability reachabilityWithHostName:Name] retain]; [hostReach startNotifier]; NetworkStatus hostStatus = [hostReach currentReachabilityStatus]; NSLog(@"Name: %@", Name); NSLog(@"hostStatus is %@", hostStatus); if(hostStatus == NotReachable){ NSLog(@"Here is the checkHostAvailability Method and host NOT reachable"); connectToHost = NO; }else{ NSLog(@"Here is the checkHostAvailability Method and host is reachable"); connectToHost = YES; } return connectToHost; } After a few hours of investigation, I have found out that the NetworkStatus hostStatus always equal to null. I assume this is why this method is not working. And I have spend 8 hours to find out the problem with this code and search out this website, however I still couldn't find the problem and solution. Please help and much appreciated. A: Remove the 'http://' from the host name. A: If you wanted to use http://www.google.com as your host, you would pass 'google.com' as the hostname. Do not include http://, the ending slash or anything that could follow an ending slash. www. is fine to include. [Reachability reachabilityWithHostName:@"google.com"]; A: This is the code I use for all the connection checks (see here: iOS Developer Library -Reachability) and it is working fine for me : -(BOOL) hasConnection{ //check network status _ iphone settings Reachability *internetReachability = [Reachability reachabilityForInternetConnection]; [internetReachability startNotifier]; NetworkStatus status=[internetReachability currentReachabilityStatus]; if (status == NotReachable) { NSLog(@"No internet"); //[internetReachability stopNotifier]; return NO; }else { NSLog(@"Internet is ON"); // [internetReachability stopNotifier]; //check internet connection _reachable path Reachability *hostReachable=[Reachability reachabilityWithHostName:@"www.apple.com"]; BOOL connectionRequired =[hostReachable connectionRequired]; NSLog(@"%hhd",connectionRequired); [hostReachable startNotifier]; Reachability *wifiReachability=[Reachability reachabilityForLocalWiFi]; [wifiReachability startNotifier]; NetworkStatus hostStatus=[hostReachable currentReachabilityStatus]; if(hostStatus == NotReachable){ NSLog(@"No internet connection"); [hostReachable stopNotifier]; return NO; }else{ NSLog(@"Connection is ok"); [hostReachable stopNotifier]; return YES; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Highlight the text using jquery I have one textbox, button and and list box with some text. When I click on button what ever the text I enter in text if it matches the text in the list box I am trying to highlight that text using jquery I used this code. Jquery Code $("#btnhighlight").click(function () { alert("yes"); var htext = $("#txthighlighttext").val(); alert(htext); $("#lstCodelist").highlight('MD'); }); Style sheet I used to hightlight and i downloaded the highlight plug in added to the project <style type="text/css"> .highlight { background-color: yellow } </style> Please can any one help me out how to do this. or if I am doing wrong? Can an A: Maybe your problem is that your script is executed before DOM ready. try with this: $(function (){ $("#btnhighlight").click(function () { var htext = $("#txthighlighttext").text(); $('#lstCodelist').highlight(htext); }); }); or put your script at the body end. ps. I supposed you used this plugin (jquery.highlight) edit: http://jsfiddle.net/yJmBu/ here a full example A: This plugin is generating spans around the text it finds. Option tags can not contain any html tags so the following (Generated by your plugin) <select> <option><span class="highlight">Te</span>st</option> </select> is illegal syntax and will be ignored by the browser. However if I understand your intent, there are some plugins out there that will accomplish something similar for you out of the box. http://code.drewwilson.com/entry/autosuggest-jquery-plugin Some proof that a nested span inside an option is not allowed. * *html tags in the option tags *It is bad to put <span /> tags inside <option /> tags, only for string manipulation not styling?
{ "language": "en", "url": "https://stackoverflow.com/questions/7501642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JGit: Retrieve tag associated with a git commit I want to use JGit API to retrieve the tags associated with a specific commit hash (if there is any)? Please provide code snippet for the same. A: If you know that there is exactly one tag for your commit, you could use describe, in more recent versions of JGit (~ November 2013). Git.wrap(repository).describe().setTarget(ObjectId.fromString("hash")).call() You could parse the result, to see if a tag exists, but if there can be multiple tags, you should go with Marcins solution. A: Git object model describes tag as an object containing information about specific object ie. commit (among other things) thus it's impossible in pure git to get information you want (commit object don't have information about related tags). This should be done "backwards", take tag object and then refer to specific commit. So if you want get information about tags specified for particular commit you should iterate over them (tags) and choose appropriate. List<RevTag> list = git.tagList().call(); ObjectId commitId = ObjectId.fromString("hash"); Collection<ObjectId> commits = new LinkedList<ObjectId>(); for (RevTag tag : list) { RevObject object = tag.getObject(); if (object.getId().equals(commitId)) {; commits.add(object.getId()); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Comunication with object android-wfc I need to comunicate information between a webservice wfc soad with an android device. I get to comunicate strings, but now I want to send objects that the web service will work with. I followed this tutorial. However, it doesn't work for me. I get the error below: SoapFault - faultcode: 'a:DeserializationFailed' faultstring: 'The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:user. The InnerException message was 'Element user from namespace http://tempuri.org/ cannot have child contents to be deserialized as an object. Please use XmlNode[] to deserialize this pattern of XML.'. Please see InnerException for more details.' faultactor: 'null' detail: null Seems that my webservice can deserialize my object... but why? Also I saw that the "user" object I sent is in another namespace of the webservice, so I don't know if it could influence, if this do something, how can I correct it? And at last, is there any method to see what xml(soad) are using in the comunications? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7501650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting Cookie to Remember Drop Down Menu State - JQuery here is my code: $(document).ready(function() { $("#root ul").each(function() {$(this).css("display", "none");}); $("#root .category").click(function() { var childid = "#" + $(this).attr("childid"); if ($(childid).css("display") == "none") { $(childid).css("display", "block"); } else { $(childid).css("display", "none"); } if ($(this).hasClass("cat_close")) { $(this).removeClass("cat_close").addClass("cat_open");} else { $(this).removeClass("cat_open").addClass("cat_close"); } }); }); Can you help me out in creating/setting a cookie that will remember the menu box that was opened after leaving the page or clicking a link? BTW, I would like to use Jquery cookie plugin. Thank you!! A: Use jquery-cookie plugin Your code will looks like (if I correctly understand what is here): <script type="text/javascript"> jQuery(document).ready(function () { var selectedId = jQuery.cookie('selected-sub-menu-id'); // get selected submenu id jQuery("#root ul").each(function () { if (jQuery(this).attr('id') != selectedId) { jQuery(this).css("display", "none"); } }); jQuery("#root .category").click(function () { var childid = "#" + jQuery(this).attr("childid"); jQuery(childid).toggle(); if (jQuery(this).hasClass("cat_close")) { jQuery(this).removeClass("cat_close").addClass("cat_open"); } else { jQuery(this).removeClass("cat_open").addClass("cat_close"); } jQuery.cookie('selected-sub-menu-id', childid.substring(1)); // set selected submenu id }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7501663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: request data in django forms class SomeForm(forms.Form): type = forms.CharField( widget = forms.HiddenInput( attrs = {'value': 'how_to_get_value_from_request'} ) ) I want when user opens www.site.com/order/type/t1 hidden value = "t1" www.site.com/order/type/t2 hidden value = "t2" www.site.com/order/type/t3 hidden value = "t3" etc. How to do this ? A: That's not how you pass values to a form. You do it when you instantiate the form, in your view: def my_view(request): form = SomeForm(initial={'type': 'the_value_I_want'})
{ "language": "en", "url": "https://stackoverflow.com/questions/7501665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does 'git mergetool' (meld) show conflict markers? Why does 'git mergetool' (meld) show me the ancestor view WITH conclict markers? This is totally wrong and I've never understood why it does this. How can I fix it? A 3 way merge should show [ Your Changes ] [ Common Base ] [ Upstream Changes ] What I get is: [ My Changes ] [ File with Conflict markers ] [ Upstream changes ] See: A: looks like you don't have the parameter names done correctly in the config. You should see things like $BASE, $REMOTE, etc. Make sure these are as specified in the documentation for 'meld' OR you have committed, by accident, an unresolved file. To check for this do a git log -S'<<<<<<' and see if anything comes back. If it does, then this is the case. hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7501666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Adding new PHP modules I am having problems with my IMAP PHP module installation and want to try either installing this module again without recompiling PHP (is this possible?) or at least look at the configuration of all of the PHP modules. After doing some Googling, I am still at a loss as to how to: * *Install new PHP modules without recompiling PHP, if possible. *Configure the installed PHP modules. I notice that the IMAP module appears on a webpage with <?php php_info(); ?> but does NOT appear with php -i on the command line. Any help would be appreciated. Thank you! A: Check the ini file(s) referenced in the output of php -i. The CLI uses a different php.ini file, and you may need to enable the module in that php.ini.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Efficient way to compute number of visits in an IP range and time range Assume there is a popular web server, the number of visits to this web server can be tens of thousands in an hour, in order to analyse the statistical property of these visits, we want to know the number of requests in a specific time range and IP range. For example, we have 1012 requests in the following format: (IP address , visiting time) Suppose we want to know how many visits came from the IP range [10.12.72.0 , 10.12.72.255] during 2p.m and 4p.m. The only candidate ideas i can think of are: (1)use B-TREE to index this large data set using one dimension, for instance build a B-TREE on the parameter IP. Using this B-TREE we can quickly get the number of request coming from any specific IP range, but how can we know how many of these visits are between 2p.m and 4p.m? (2)use BITMAP, but similar to B-TREE, due to space requirement the BITMAP can only be built on one dimension, for instance IP address, we don't know how many of these request are issued between 2p.m and 4p.m. Is there any efficient algorithm, thx? The number of queries can be quite large A: You want a data structure that supports orthogonal range counting. A: Your first step is figure out the precision you need... TIME: * *Do you need, to the millisecond, time stamps or is, to the hour, good enough? * * *Number of hours since 1970 can fit in under a million, 3 bytes ~integer * * *Number of milliseconds and you need 8 bytes ~long IP: * *Are all your IPs v4 (4 bytes) or v6 (16 bytes)? *Will you ever search by specific IP or will you only use IP ranges? * * *If the latter you could just use the class C for each IP 123.123.123.X (3 bytes) Assuming: * *1 hour time precision is good enough *3 byte IP class C is good enough Re-Organizing your data (2 possible structures pick one): Database: * *You can use a relational database * * *Table: Hits * * * * *IPClassC INT NON-CLUSTERED INDEX * * * * *TimeHrsUnix INT NON-CLUSTERED INDEX * * * * *Count BIGINT DEFAULT VALUE (1) Flat Files: * *You can use more flat files * * *Have 1 flat file for each class C IP that appears in your logs (max 2^24) * * * * *Each file is 8B (big int) * 1MB (Hrs Since 1970 to 2070) = 8MB in size How to load your new data structure: Database: * *Parse your logs (read in memory one line at a time) *Convert record to 3 byte IP and 3 byte Time *Convert your IP class C to an integer and your Time hrs to an integer *IF EXISTS(SELECT * FROM Hits WHERE IPClassC = @IP AND TimeHrsUnix = @Time) * * *UPDATE Hits SET Count = Count + 1 WHERE IPClassC = @IP AND TimeHrsUnix = @Time *Else * * *INSERT INTO Hits VALUES(@IP, @Time) Flat Files: * *Parse your logs (read in memory one line at a time) *Convert record to 3 byte IP and 3 byte Time *Convert your IP to a string and your time to an integer *if File.Exist(IP) = False * * *File.Create(IP) * * *File.SetSize(IP, 8 * 1000000) *CountBytes = File.Read(IP, 8 * Time, 8) *NewCount = Convert.ToLong(CountBytes) + 1 *CountBytes = Convert.ToBytes(NewCount) *File.Write(IP, CountBytes, 8 * Time, 8) Querying your new data structures: Database: * *SELECT SUM(Count) FROM Hits WHERE IPClassC BETWEEN @IPFrom AND @IPTo AND TimeHrsUnix BETWEEN @TimeFrom AND @TimeTo Flat File: * *Total = 0 *Offset = 8 * TimeFrom *Len = (8 * TimeTo) - Offset *For IP = IPFrom To IPTo * * *If File.Exist(IP.ToString()) * * * * *CountBytes = File.Read(IP.ToString(), Offset, Len) * * * * *LongArray = Convert.ToLongArray(CountBytes) * * * * *Total = Total + Math.Sum(LongArray) *Next IP Some extra tips: * *If you go the database route your likely going to have to use multiple partitions for the database file *If you go the flat file route you may want to break your query into threads (assuming your SAS will handle the bandwidth). Each thread would handle a sub set of the IP/Files in the range. Once all threads completed the totals from each would be summed. A: 10^12 is a large number (TERA) - certainly too large for in-memory processing. I would store this in a relational database with a star schema, use a time dimension, and pre-aggregate by time of day (e.g. hour bands), IP subnets, and other criteria that you are interested in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VS 2010 and TFS 2005 compatibility We are currently in a position to move up from Visual Studio 2008 to Visual Studio 2010. Unfortunately, we don't have a server allocated for a TFS upgrade yet (should happen in about 6 months), so we are stuck with TFS 2005 for now. Will VS2010 be compatible with TFS 2005? If so, any potential issues we need to consider? A: Visual Studio and Team Explorer 2010 do not officially support TFS 2005 servers (see http://msdn.microsoft.com/en-us/library/dd997788.aspx for the compat matrix). I don't think it is actively blocked, though, and it may work just fine for the mainstream scenarios. I don't have TFS 2005 server to try it. A: Currently using VS2010 and TFS2005 here and they work well together.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax Help Involving Webgrids I'm unexperienced with Ajax. I'm using a webgrid that executes: javascript:__doPostBack('GridView1','Select$1') when a row is selected. How can I call some action when this is posted? ____UPDATE_______ protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.DataItemIndex == -1) return; e.Row.Attributes.Add("onMouseOver", "this.style.cursor='hand';"); e.Row.Attributes.Add("onclick", GetPostBackClientEvent(GridView1, "Select$" + e.Row.RowIndex.ToString()) ); } A: The code you wrote is not Ajax (unless the grid is enclosed in an update panel or something like that). The way you trigger an event on the server side would be like this: if (Request.Form["__EVENTTARGET"] == "GridView1") { //fire event string argument = Request.Form["__EVENTARGUEMENT"]; //do something. } UPDATE The important thing is going to be the "argument" piece in my code since it will have the row that the person clicked on in the form of Select$<RowNumber> I guess you need to do something with that information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set environment variables on Mac OS X Lion When someone says "edit your .plist file" or "your .profile" or ".bash_profile" etc, this just confuses me. I have no idea where these files are, how to create them if I have to do that, etc, and also why there seem to be so many different ones (why? Do they do different things?) So could someone please explain very patiently to a previous Windows user (wanting desperately to become more familiar with the pleasant if initially somewhat confusing OS X world) how to do this step by step? I need the variables to be set both for GUI applications and command line applications, and at the moment it's for an ant script that needs the variables, but there will most likely be other needs as well. Please note that I have Lion too, since many of the answers you get Googling seem to be outdated for Lion... Also note that I have practically zero experience using the Terminal. I'm willing to learn, but please explain for a novice... A: Open Terminal: vi ~/.bash_profile Apply changing to system (no need restart computer): source ~/.bash_profile (Also work with macOS Sierra 10.12.1) A: Here's a bit more information specifically regarding the PATH variable in Lion OS 10.7.x: If you need to set the PATH globally, the PATH is built by the system in the following order: * *Parsing the contents of the file /private/etc/paths, one path per line *Parsing the contents of the folder /private/etc/paths.d. Each file in that folder can contain multiple paths, one path per line. Load order is determined by the file name first, and then the order of the lines in the file. *A setenv PATH statement in /private/etc/launchd.conf, which will append that path to the path already built in #1 and #2 (you must not use $PATH to reference the PATH variable that has been built so far). But, setting the PATH here is completely unnecessary given the other two options, although this is the place where other global environment variables can be set for all users. These paths and variables are inherited by all users and applications, so they are truly global -- logging out and in will not reset these paths -- they're built for the system and are created before any user is given the opportunity to login, so changes to these require a system restart to take effect. BTW, a clean install of OS 10.7.x Lion doesn't have an environment.plist that I can find, so it may work but may also be deprecated. A: echo $PATH it prints current path value Then do vim ~/.bash_profile and write export PATH=$PATH:/new/path/to/be/added here you are appending to the old path, so preserves the old path and adds your new path to it then do source ~/.bash_profile this will execute it and add the path then again check with echo $PATH A: I had problem with Eclipse (started as GUI, not from script) on Maverics that it did not take custom PATH. I tried all the methods mentioned above to no avail. Finally I found the simplest working answer based on hints from here: * *Go to /Applications/eclipse/Eclipse.app/Contents folder *Edit Info.plist file with text editor (or XCode), add LSEnvironment dictionary for environment variable with full path. Note that it includes also /usr/bin etc: <dict> <key>LSEnvironment</key> <dict> <key>PATH</key> <string>/usr/bin:/bin:/usr/sbin:/sbin:/dev/android-ndk-r9b</string> </dict> <key>CFBundleDisplayName</key> <string>Eclipse</string> ... *Reload parameters for app with /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.fra‌​mework/Support/lsregister -v -f /Applications/eclipse/Eclipse.app *Restart Eclipse A: Let me illustrate you from my personal example in a very redundant way. * *First after installing JDK, make sure it's installed. *Sometimes macOS or Linux automatically sets up environment variable for you unlike Windows. But that's not the case always. So let's check it. The line immediately after echo $JAVA_HOME would be empty if the environment variable is not set. It must be empty in your case. *Now we need to check if we have bash_profile file. You saw that in my case we already have bash_profile. If not we have to create a bash_profile file. *Create a bash_profile file. *Check again to make sure bash_profile file is there. *Now let's open bash_profile file. macOS opens it using it's default TextEdit program. *This is the file where environment variables are kept. If you have opened a new bash_profile file, it must be empty. In my case, it was already set for python programming language and Anaconda distribution. Now, i need to add environment variable for Java which is just adding the first line. YOU MUST TYPE the first line VERBATIM. JUST the first line. Save and close the TextEdit. Then close the terminal. *Open the terminal again. Let's check if the environment variable is set up. A: First, one thing to recognize about OS X is that it is built on Unix. This is where the .bash_profile comes in. When you start the Terminal app in OS X you get a bash shell by default. The bash shell comes from Unix and when it loads it runs the .bash_profile script. You can modify this script for your user to change your settings. This file is located at: ~/.bash_profile Update for Mavericks OS X Mavericks does not use the environment.plist - at least not for OS X windows applications. You can use the launchd configuration for windowed applications. The .bash_profile is still supported since that is part of the bash shell used in Terminal. Lion and Mountain Lion Only OS X windowed applications receive environment variables from the your environment.plist file. This is likely what you mean by the ".plist" file. This file is located at: ~/.MacOSX/environment.plist If you make a change to your environment.plist file then OS X windows applications, including the Terminal app, will have those environment variables set. Any environment variable you set in your .bash_profile will only affect your bash shells. Generally I only set variables in my .bash_profile file and don't change the .plist file (or launchd file on Mavericks). Most OS X windowed applications don't need any custom environment. Only when an application actually needs a specific environment variable do I change the environment.plist (or launchd file on Mavericks). It sounds like what you want is to change the environment.plist file, rather than the .bash_profile. One last thing, if you look for those files, I think you will not find them. If I recall correctly, they were not on my initial install of Lion. Edit: Here are some instructions for creating a plist file. * *Open Xcode *Select File -> New -> New File... *Under Mac OS X select Resources *Choose a plist file *Follow the rest of the prompts To edit the file, you can Control-click to get a menu and select Add Row. You then can add a key value pair. For environment variables, the key is the environment variable name and the value is the actual value for that environment variable. Once the plist file is created you can open it with Xcode to modify it anytime you wish. A: I took the idiot route. Added these to the end of /etc/profile for environment in `find /etc/environments.d -type f` do . $environment done created a folder /etc/environments create a file in it called "oracle" or "whatever" and added the stuff I needed set globally to it. /etc$ cat /etc/environments.d/Oracle export PATH=$PATH:/Library/Oracle/instantclient_11_2 export DYLD_LIBRARY_PATH=/Library/Oracle/instantclient_11_2 export SQLPATH=/Library/Oracle/instantclient_11_2 export PATH=$PATH:/Library/Oracle/instantclient_11_2 export TNS_ADMIN=/Library/Oracle/instantclient_11_2/network/admin A: Unfortunately none of these answers solved the specific problem I had. Here's a simple solution without having to mess with bash. In my case, it was getting gradle to work (for Android Studio). Btw, These steps relate to OSX (Mountain Lion 10.8.5) * *Open up Terminal. *Run the following command: sudo nano /etc/paths (or sudo vim /etc/paths for vim) *Go to the bottom of the file, and enter the path you wish to add. *Hit control-x to quit. *Enter 'Y' to save the modified buffer. *Open a new terminal window then type: echo $PATH You should see the new path appended to the end of the PATH I got these details from this post: http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.UkED3rxPp3Q I hope that can help someone else A: Simplified Explanation This post/question is kind of old, so I will answer a simplified version for OS X Lion users. By default, OSX Lion does not have any of the following files: * *~/.bashrc *~/.bash_profile *~/.profile At most, if you've done anything in the terminal you might see ~/.bash_history What It Means You must create the file to set your default bash commands (commonly in ~/.bashrc). To do this, use any sort of editor, though it's more simple to do it within the terminal: * *%> emacs .profile *[from w/in emacs type:] source ~/.bashrc *[from w/in emacs type:] Ctrl + x Ctrl + s (to save the file) *[from w/in emacs type:] Ctrl + x Ctrl + c (to close emacs) *%> emacs .bashrc *[from w/in emacs type/paste all your bash commands, save, and exit] The next time you quit and reload the terminal, it should load all your bash preferences. For good measure, it's usually a good idea to separate your commands into useful file names. For instance, from within ~/.bashrc, you should have a source ~/.bash_aliases and put all your alias commands in ~/.bash_aliases. A: Your .profile or .bash_profile are simply files that are present in your "home" folder. If you open a Finder window and click your account name in the Favorites pane, you won't see them. If you open a Terminal window and type ls to list files you still won't see them. However, you can find them by using ls -a in the terminal. Or if you open your favorite text editor (say TextEdit since it comes with OS X) and do File->Open and then press Command+Shift+. and click on your account name (home folder) you will see them as well. If you do not see them, then you can create one in your favorite text editor. Now, adding environment variables is relatively straightforward and remarkably similar to windows conceptually. In your .profile just add, one per line, the variable name and its value as follows: export JAVA_HOME=/Library/Java/Home export JRE_HOME=/Library/Java/Home etc. If you are modifying your "PATH" variable, be sure to include the system's default PATH that was already set for you: export PATH=$PATH:/path/to/my/stuff Now here is the quirky part, you can either open a new Terminal window to have the new variables take effect, or you will need to type .profile or .bash_profile to reload the file and have the contents be applied to your current Terminal's environment. You can check that your changes took effect using the "set" command in your Terminal. Just type set (or set | more if you prefer a paginated list) and be sure what you added to the file is there. As for adding environment variables to GUI apps, that is normally not necessary and I'd like to hear more about what you are specifically trying to do to better give you an answer for it. A: It is recommended to check default terminal shell before setting any environment variables, via following commands: $ echo $SHELL /bin/zsh If your default terminal is /bin/zsh (Z Shell) like in my case (Personally prefer Z Shell), then you should set these environment variable in ~/.zshenv file with following contents (In this example, setting JAVA_HOME environment variable, but same applies to others): export JAVA_HOME="$(/usr/libexec/java_home)" Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file. A: What worked for me is to create a .launchd.conf with the variables I needed: setenv FOO barbaz This file is read by launchd at login. You can add a variable 'on the fly' to the running launchd using: launchctl setenv FOO barbaz` In fact, .launchd.cond simply contains launchctl commands. Variables set this way seem to be present in GUI applications properly. If you happen to be trying to set your LANG or LC_ variables in this way, and you happen to be using iTerm2, make sure you disable the 'Set locale variables automatically' setting under the Terminal tab of the Profile you're using. That seems to override launchd's environment variables, and in my case was setting a broken LC_CTYPE causing issues on remote servers (which got passed the variable). (The environment.plist still seems to work on my Lion though. You can use the RCenvironment preference pane to maintain the file instead of manually editing it or required Xcode. Still seems to work on Lion, though it's last update is from the Snow Leopard era. Makes it my personally preferred method.) A: Setup your PATH environment variable on Mac OS Open the Terminal program (this is in your Applications/Utilites folder by default). Run the following command touch ~/.bash_profile; open ~/.bash_profile This will open the file in the your default text editor. For ANDROID SDK as example : You need to add the path to your Android SDK platform-tools and tools directory. In my example I will use "/Development/android-sdk-macosx" as the directory the SDK is installed in. Add the following line: export PATH=${PATH}:/Development/android-sdk-macosx/platform-tools:/Development/android-sdk-macosx/tools Save the file and quit the text editor. Execute your .bash_profile to update your PATH. source ~/.bash_profile Now everytime you open the Terminal program you PATH will included the Android SDK. A: Adding Path Variables to OS X Lion This was pretty straight forward and worked for me, in terminal: $echo "export PATH=$PATH:/path/to/whatever" >> .bash_profile #replace "/path/to/whatever" with the location of what you want to add to your bash profile, i.e: $ echo "export PATH=$PATH:/usr/local/Cellar/nginx/1.0.12/sbin" >> .bash_profile $. .bash_profile #restart your bash shell A similar response was here: http://www.mac-forums.com/forums/os-x-operating-system/255324-problems-setting-path-variable-lion.html#post1317516 A: More detail, which may perhaps be helpful to someone: Due to my own explorations, I now know how to set environment variables in 7 of 8 different ways. I was trying to get an envar through to an application I'm developing under Xcode. I set "tracer" envars using these different methods to tell me which ones get it into the scope of my application. From the below, you can see that editing the "scheme" in Xcode to add arguments works, as does "putenv". What didn't set it in that scope: ~/.MACOS/environment.plist, app-specific plist, .profile, and adding a build phase to run a custom script (I found another way in Xcode [at least] to set one but forgot what I called the tracer and can't find it now; maybe it's on another machine....) GPU_DUMP_DEVICE_KERNEL is 3 GPU_DUMP_TRK_ENVPLIST is (null) GPU_DUMP_TRK_APPPLIST is (null) GPU_DUMP_TRK_DOTPROFILE is (null) GPU_DUMP_TRK_RUNSCRIPT is (null) GPU_DUMP_TRK_SCHARGS is 1 GPU_DUMP_TRK_PUTENV is 1 ... on the other hand, if I go into Terminal and say "set", it seems the only one it gets is the one from .profile (I would have thought it would pick up environment.plist also, and I'm sure once I did see a second tracer envar in Terminal, so something's probably gone wonky since then. Long day....) A: Step1: open ~/.bash_profile Now a text editor opens: Step2: variable name should be in capitals. in this example variable is NODE_ENV Step3: export NODE_ENV=development Save it and close. Restart your system. Done. To check env variable: open terminal and type echo $NODE_ENV
{ "language": "en", "url": "https://stackoverflow.com/questions/7501678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "544" }
Q: How to know route from the URL or $request Object? PLOT: After implementing ACL on my website, if a user tries to access unauthorised page he will be denied and shown a page to login. After he loggs in, I wanted to redirect the user to the previous page to which he was denied to earlier. To do this, I store the request parameters using $request -> getParams(), onto a session variable, which will be used to generate the url again. This is where the problem occurs, to generate the url back, I need the name of the route and that i dont know how to read. I need to know the route name, so that I will be able to regenerate the url, from the array stored in session, or if there is a better way to solve this, please suggest. A: Why not just store $request->getRequestUri()? This will give you the URL as it appears in the browser. A: Dont try to think of complex solutions for simple problem. You can do this, with just using $_SERVER['REQUEST_URI'], this gives the same result as @Phil's answer (Correct me, If i am missing something). and is more than enough to do what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call multiple values outside while statement $searchquery = mysql_query("SELECT * FROM regform_admin WHERE status = 'Approved' AND month LIKE '%".$checkmonth."%' AND day LIKE '%".$checkday."%' AND year LIKE '%".$checkyear."%' OR month2 LIKE '%".$checkmonth."%' AND day2 LIKE '%".$checkday."%' AND year2 LIKE '%".$checkyear."%' OR betday LIKE '%".$checkday."%'"); while($fetchres = mysql_fetch_array($searchquery)) { $vehicles = $fetchres['vehicles']; echo "<b>$vehicles</b><br>"; } include "vehicledbconnect.php"; $searchquery2 = mysql_query("SELECT * FROM vehicletbl WHERE vehicle NOT LIKE '%".$vehicles."%'"); while($fetch = mysql_fetch_array($searchquery2)) { $v = $fetch['vehicle']; $vehed = $fetch['vehed']; $vehcap = $fetch['vehcap']; $vehyr = $fetch['vehyr']; $type = $fetch['type']; echo "<tr>"; echo "<td class=light><input type = 'checkbox' name='chk[]'></td>"; echo "<td class=light>$v</td>"; echo "<td class=light>$type</td>"; echo "<td class=light>$vehyr</td>"; echo "<td class=light>$vehed</td>"; echo "<td class=light>$vehcap</td>"; echo "<td class=light>$vehcolor</td>"; echo "</tr>"; echo "$array"; } Is it possible to echo all values inside the while statement from $searchquery inside $searchquery2? For example the values of $searchquery is: vehicle1 vehicle2 vehicle3 Now I'm going to echo all of it inside $searchquery2, is it possible? I try to echo $vehicles (from $searchquery) inside $searchquery2 but it only echoes the last value (example. vehicle3) because I know it is not inside the while statement of $searchquery. Is it possible? Thanks. A: Build a loop in loop. Try this: mysql_query("SELECT * FROM regform_admin WHERE...") while(...) { $vehicles = $fetchres['vehicles']; echo "<b>$vehicles</b><br>"; mysql_query("SELECT * FROM vehicletbl WHERE vehicle NOT LIKE '%".$vehicles."%'"); while(...) { echo ... } } A: Instead of echoing inside the while loop, try buffering the output to a variable instead: $ob = ''; while($fetchres = mysql_fetch_array($searchquery)) $ob .= '<b>' . $fetchres['vehicles'] . '</b><br>'; echo($ob); During your second while loop, $ob is still alive and you can echo it out just as easily. Here I'm storing it as a string, but you can store the values as an array also if you need more granular access to the elements. Update If you want to store them into an array, try it this way: $ob = array(); while($fetchres = mysql_fetch_array($searchquery)) $ob[] = $fetchres['vehicle']; // This pushes the current vehicle onto the end of the array After this loop, you just have the string for each vehicle in the array, and none of the formatting. You can add that in when you output the elements. Iterate over your array with foreach: foreach($ob as $k => $v) { // Inside this loop, $k is the key, or index, and $v is the value. // You can change the names of these variables by modifying the line above, e.g. // foreach($ob as $foo => $bar) <-- $foo = key/index, $bar = value }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Telerik reports subreports I'm starting with telerik reports so I have one question. In my report I need to create maser report for every chosen product and below it I need to show report for each selected product detailed. So when I chose some products in reports parameters listbox I see my summary report but don't know how to add as many detailed reports below it as user has chosen in listbox. Thanks for any hint! A: Telerik supports subreports like you need. Here are the basic steps: * *Build a new report to display the detail information. It should have a parameter that is the 'current' product (it sounds like you might already have this report) *On your main product report (the master), place a SubReport control in the detail section. Set the Report property of the SubReport to the report you created above. *Set the Parameters property on the SubReport to pass the product from the current detail row to the subreport. For more information, you can reference Telerik's documentation, a live demo, or the API reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MonoTouch does not support OpenAsync method for opening a web service connection when running on the device (works on the simulator) I am using MonoTouch 4.0.7 with MonoDevelop 2.8 Beta 2 and XCode 4 (by the way someone know how to get MonoTouch 4.2 version?). We are trying to call a .Net web service method through classes generated by the slsvcutil proxy generator. When testing the app on the iPhone simulator, the code is working and we succeed to connect to the server and send web services requests. However, when testing the app on a device (iPhone 4 with iOS 4.3.5), the app fails to connect to the server when calling OpenAsynch() method (Method called in the code generated by the proxy generator), we get a strange error: Attempting to JIT compile method '(wrapper delegate-begin-invoke) '(wrapper delegate-begin-invoke) :begin_invoke_IAsyncResult_this__TimeSpan_AsyncCallback_object (System.TimeSpan,System.AsyncCallback,object)' while running with --aot-only. My error stack: Unhandled Exception: System.ExecutionEngineException: Attempting to JIT compile method '(wrapper delegate-begin-invoke) <Module>:begin_invoke_IAsyncResult__this___TimeSpan_AsyncCallback_object (System.TimeSpan,System.AsyncCallback,object)' while running with --aot-only. at System.ServiceModel.MonoInternal.ClientRuntimeChannel.OnBeginOpen (TimeSpan timeout, System.AsyncCallback callback, System.Object state) [0x00000] in <filename unknown>:0 at System.ServiceModel.Channels.CommunicationObject.BeginOpen (TimeSpan timeout, System.AsyncCallback callback, System.Object state) [0x00000] in <filename unknown>:0 at System.ServiceModel.Channels.CommunicationObject.BeginOpen (System.AsyncCallback callback, System.Object state) [0x00000] in <filename unknown>:0 at System.ServiceModel.ClientBase`1+ChannelBase`1[ICommandMgr,ICommandMgr].System.ServiceModel.ICommunicationObject.BeginOpen (System.AsyncCallback callback, System.Object state) [0x00000] in <filename unknown>:0 at System.ServiceModel.ClientBase` 1[ICommandMgr].System.ServiceModel.ICommunicationObject.BeginOpen (System.AsyncCallback callback, System.Object state) [0x00000] in <filename unknown>:0 at CommandMgrClient.OnBeginOpen (System.Object[] inValues, System.AsyncCallback callback, System.Object asyncState) [0x00000] in CommandMgrStaticProxyClient.cs:1156 at System.ServiceModel.ClientBase`1[ICommandMgr].InvokeAsync (System.ServiceModel.BeginOperationDelegate beginOperationDelegate, System.Object[] inValues, System.ServiceModel.EndOperationDelegate endOperationDelegate, System.Threading.SendOrPostCallback operationCompletedCallback, System.Object userState) [0x00000] in <filename unknown>:0 at CommandMgrClient.OpenAsync (System.Object userState) [0x00057] in CommandMgrStaticProxyClient.cs:1193 Someone know if it is a MonoTouch bug or if there is a way to fix this crash? Thanks in advance! ---- EDIT ---- I found a workaround: replace the OpenAsync() call by Open(). Thus, I think it is a limitation/bug of MonoTouch that does not support asynchronous call to open a Web service connection. I'll enter a bug in bugzilla.xamarin.com private void DoNotificationMgrOpenAsync(string address, int port) { this.SystemUIHandler.LogInfo(">>>>>> NotificationMgr Open"); m_notificationMgrClient = new NotificationMgrClient( new System.ServiceModel.BasicHttpBinding() { Namespace = "http://schema.dartfish.com/2011/05/RemoteControl" }, new System.ServiceModel.EndpointAddress( string.Format(System.Globalization.CultureInfo.InvariantCulture, "http://{0}:{1}/Dartfish/RemoteControlServices/", address, port))); //m_notificationMgrClient.OpenCompleted += new System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(NotificationMgrClient_OpenCompleted); //m_notificationMgrClient.OpenAsync(); m_notificationMgrClient.Open(); DoGetLastMessageId(); } void NotificationMgrClient_OpenCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { this.SystemUIHandler.LogInfo("<<<<<< NotificationMgr Open"); System.Diagnostics.Debug.Assert(m_notificationMgrClient != null); if (m_notificationMgrClient != null) { m_notificationMgrClient.OpenCompleted -= NotificationMgrClient_OpenCompleted; // init messageId DoGetLastMessageId(); } } A: I believe the specific problem is the same as in this post from the Unity 3D forum: AOT issue with += event handler syntax As in this post, the generated async proxy code uses the += event syntax, which requires JIT compilation. I have confirmed that the fix in the post solves that problem. I haven't tested OpenAsyc, so you may run into additional difficulties after solving the event handler issue. A: UPDATE MonoTouch (itself) is hitting one of the full-AOT limitation of MonoTouch. The immediate workaround is to use the synchronous Open method (instead of OpenAsync method). A bug report was opened to track this issue. You can add yourselves on its c.c. list to be updated on its progress.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: subject displays in encoding format while sending long subject I am sending mail to outlook using System.Net.Mail Here code i used, msg.From = new MailAddress("stagingsupport@syncfusion.com"); msg.IsBodyHtml = true; msg.Body = "Some text"; msg.To.Add("karthike@syncfusion.com"); msg.Subject = "[Enterprise Priority] - Customer Incident 85172 for Karthik (108269) velusamys@syncfusion.com : Custom function called from within an AND function results in error - Syncfusion Website Team Test I – Created"; I am getting the subject like =?utf-8?B?W0VudGVycHJpc2UgU... I dint give any non ascii character in subject but i comes in encoded form.I refered the following link,i cant get the solution that much, System.Net.Mail and =?utf-8?B?XXXXX.... Headers What i have to follow to get the subject come correct decoded form? A: You have to set UTF8 encoding. msg.SubjectEncoding= System.Text.Encoding.UTF8;
{ "language": "en", "url": "https://stackoverflow.com/questions/7501691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find min width required to display item in full with jQuery? Is it possible to find the number of pixels that is required to display a div completely? Right now, my div is at 100%, but I would really like it to be as small as the content... (can't use floats or other css tricks). A: This question may be dependent upon the content so without seeing your HTML, we can only guess, but the only way that a div sizes itself to it's content is when it's position: absolute. So, you can use a function like this to get a div to temporarily wrap to it's content so you can measure the content width. You would then use that width to set it's size if you wanted: function measureWidth(selector) { var item = $(selector).eq(0); // just first item var pos = item.css("position"); // save original value item.css("position", "absolute"); var width = item.width(); item.css("position", pos); return(width); } var width = measureWidth("#header"); You can see it work here: http://jsfiddle.net/jfriend00/L2J5w/ FYI, I learned this technique from jQuery. It uses it internally to measure the width of some things. It even has an internal (non-documented) function called .swap() that is used for saving the values of a set of CSS properties, setting those CSS properties to something else, taking a measurement, then restoring the CSS properties to their original values. A: If you do not set the div width to 100% and set the display: inline, then it should only take as much space as the content as long as it does not overflow. If the contents do overflow then, this will tell you the width of the div for its contents when a scrollbar is present $("#mydivid")[0].scrollWidth
{ "language": "en", "url": "https://stackoverflow.com/questions/7501692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Internet explorer 8 refuses to download a file from a popup I'm crafting a website. In one place there is a button which performs an Ajax callback, and then tries to download a file via window.open(). The expected behaviour is for the new window to flash briefly and then a file download to appear. This works fine on IE9, but IE8 seems to have a problem with that, even with popup blocker disabled. After further experimenting I found another peculiar behavior. If I enter the URL of the download manually into the addressbar of a freshly opened tab, I get an error message. Something generic about not being able to download. If I now try to refresh the page (or just hit ENTER in the address bar, thereby repeating the same request), the download proceeds nicely. I expected that it might have something to do with content-disposition or cache-control headers, but removing those didn't help. Nor did adding the URL to the "trusted sites" zone. I'm going to try and remake it with window.location instead anyway, because I don't like the popup (that wasn't made by me), but I'm puzzled about this behavior. What causes it? A: I ran across a similar issue. It turns out that IE has trouble opening files when you use AJAX to get them. The solution I used is to not use ajax. Instead I used a little jQuery and a iframe: jquery - on click (dont need ajax/get) var dynamicUrl = 'SomeFileService.aspx?someQueryParam=' + input; $('#iframePopup').attr('src', dynamicUrl); window.frames["#iframePopup"].location.reload(); HTML <iframe id="iframePopup" style="visibility:hidden;height:0px;width:0px;"></iframe>
{ "language": "en", "url": "https://stackoverflow.com/questions/7501695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find all files with a filename that ends with tilde I use Emacs and it sometimes makes backup for edited files. After a few days, I would have a lot of backup files whose name ends with a tilde. Is there a way to find these files and delete them at once? I tried this: find "*" -type f -iname *~ But it doesn't work. I want the command to work recursively – something like ls -alR. A: You can do something like that : find . -type f -name '*~' -delete If you want to delete also #*# file : find . -type f -name '*~' -o -name '#*#' -delete You can print all deleted files with "-print": find . -type f -name '*~' -delete -print A: You need to escape from the shell. And you need to specify search path, not * find . -type f -name '*~' To delete the files: find . -type f -name '*~' -exec rm -f '{}' \; A: Another way is by using grep. lnydex99uhc:javastuff user$ ls Permutation.java VigenereCipher.java VigenereCipher.java~ lnydex99uhc:javastuff user $ find . | grep .~$ ./VigenereCipher.java~ You can also pass any command you want like this : lnydex99uhc:javastuff zatef$ rm $(find . | grep .~$)
{ "language": "en", "url": "https://stackoverflow.com/questions/7501697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: How do I pass variables between class instances or get the caller? class foo(): def __init__(self) self.var1 = 1 class bar(): def __init__(self): print "foo var1" f = foo() b = bar() In foo, I am doing something that produces "var1" being set to 1 In bar, I would like to access the contents of var1 How can I access var1 in the class instance f of foo from within the instance b of bar Basically these classes are different wxframes. So for example in one window the user may be putting in input data, in the second window, it uses that input data to produce an output. In C++, I would have a pointer to the caller but I dont know how to access the caller in python. A: Same as in any language. class Foo(object): def __init__(self): self.x = 42 class Bar(object): def __init__(self, foo): print foo.x a = Foo() b = Bar(a) A: As a general way for different pages in wxPython to access and edit the same information consider creating an instance of info class in your MainFrame (or whatever you've called it) class and then passing that instance onto any other pages it creates. For example: class info(): def __init__(self): self.info1 = 1 self.info2 = 'time' print 'initialised' class MainFrame(): def __init__(self): a=info() print a.info1 b=page1(a) c=page2(a) print a.info1 class page1(): def __init__(self, information): self.info=information self.info.info1=3 class page2(): def __init__(self, information): self.info=information print self.info.info1 t=MainFrame() Output is: initialised 1 3 3 info is only initialised once proving there is only one instance but page1 has changed the info1 varible to 3 and page2 has registered that change. A: No one has provided a code example showing a way to do this without changing the init arguments. You could simply use a variable in the outer scope that defines the two classes. This won't work if one class is defined in a separate source file from the other however. var1 = None class foo(): def __init__(self) self.var1 = var1 = 1 class bar(): def __init__(self): print var1 f = foo() b = bar() A: Alternatively you could have a common base class from which both derived classes inherit the class variable var1. This way all instances of derived classes can have access to the variable. A: Something like: class foo(): def __init__(self) self.var1 = 1 class bar(): def __init__(self, foo): print foo.var1 f = foo() b = bar(foo) You should be able to pass around objects in Python just like you pass around pointers in c++. A: Perhaps this was added to the language since this question was asked... The global keyword will help. x = 5 class Foo(): def foo_func(self): global x # try commenting this out. that would mean foo_func() # is creating its own x variable and assigning it a # value of 3 instead of changing the value of global x x = 3 class Bar(): def bar_func(self): print(x) def run(): bar = Bar() # create instance of Bar and call its bar.bar_func() # function that will print the current value of x foo = Foo() # init Foo class and call its function foo.foo_func() # which will add 3 to the global x variable bar.bar_func() # call Bar's function again confirming the global # x variable was changed if __name__ == '__main__': run()
{ "language": "en", "url": "https://stackoverflow.com/questions/7501706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: scaffold all guid's in asp.net dynamic data by default is there an option to scaffold all guid columns in asp.net dynamic data by default? I know there's the possibility to set the ScaffoldColumn attribute to true in this way: [MetadataType(typeof(MyEntityMetadata))] public partial class MyEntity {} public partial class MyEntityMetadata { [ScaffoldColumn(true)] public Nullable<global::System.Guid> DataValueG { get; set; } } but I don't want to specify always two additional classes for every guid column... Thanks. A: From MSDN, "You can set scaffold to true for the entire data model to expose all data columns in the database ... by setting scaffold to true in the Global.asax file or expose individual data columns in a data table to CRUD operations by setting scaffold to true in the partial class." DefaultModel.RegisterContext(typeof(MyDataContext), new ContextConfiguration() { ScaffoldAllTables = true });
{ "language": "en", "url": "https://stackoverflow.com/questions/7501707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to receive action by BroadcastReceiver inside Service I have problem with receiving an intent sended by widget as PendingIntent: intent = new Intent(MyService.MY_ACTION); pendingIntent = PendingIntent.getService(this, 0, intent, 0); views.setOnClickPendingIntent(R.id.button, pendingIntent); I added a broadcast receiver to MyService: private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Intent command received"); String action = intent.getAction(); if( MY_ACTION.equals(action)) { doSomeAction(); } } }; and finally I registered this receiver i onCreate method of the service: IntentFilter filter = new IntentFilter(); filter.addAction(MY_ACTION); registerReceiver(mIntentReceiver, filter); And now when th MyService is running and I click the button, I get : 09-21 14:21:18.723: WARN/ActivityManager(59): Unable to start service Intent { act=com.myapp.MyService.MY_ACTION flg=0x10000000 bnds=[31,280][71,317] }: not found I also tried to add an intent-filter (with MY_ACTION action) to manifest file to MyService but it causes calling onStartCommand method of MyService. And that is not what I want. I need to call the onReceive method of mIntentReceiver. A: What do you want to do? If you register a broadcast receiver in your Service onCreate method then: * *You should raise a broadcast intent, not a service intent. Change this: pendingIntent = PendingIntent.getService(this, 0, intent, 0); To this: pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); * *You service should be running to listen for this broadcast event, this will not run your service, since you are registering the receiver when the service is created. A: For such purposes you should extend your service from IntentService. You will receive the broadcast in onHandleIntent() method of your service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: n-gram counting in MySQL I am building a MySQL database that will have roughly 10,000 records. Each record will contain a textual document (a few pages of text in most cases). I want to do all sorts of n-gram counting across the entire database. I have algorithms already written in Python that will what I want against a directory containing a large number of text files, but to do that I will need to extract 10,000 text files from the database - this will have performance issues. I'm a rookie with MySQL, so I'm not sure if it has any built-in features that do n-gram analysis, or whether there are good plugins out there that would do it. Please note that I need to go up to at least 4-grams (preferably 5-grams) in my analysis, so the simple 2-gram plugins I've seen won't work here. I also need to have the ability to remove the stopwords from the textual documents before doing the n-gram counting. Any ideas from the community? Thanks, Ron A: My suggestion would be to use a dedicated full-text search index program like lucene/solr, which has much richer and extensible support for this sort of thing. It will require you to learn a bit to get it set up, but it sounds as if you want to mess around at a level that will be difficult to customize in MySQL. A: If you really want to prematurely optimize ;) you could translate your python into C and then wrap it with thin mysql UDF wrapper code. But I'd highly recommend just loading your documents one at a time and running your python scripts on them to populate a mysql table of n-grams. My hammer for every nail at the moment is Django. It's ORM makes interacting with mysql tables and optimizing those interactions a cinch. I'm using it to do statistics in python on multimillion record databases for production sites that have to return gobs of data in less than a second. And any python ORM will make it easier to switch out your database if you find something better than mysql, like postgre. The best part is that there are lots of python and django tools to monitor all aspects of your app's performance (python execution, mysql load/save, memory/swap). That way you can attack the right problem. It may be that sequential bulk mysql reads aren't what's slowing you down...
{ "language": "en", "url": "https://stackoverflow.com/questions/7501713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: PLPGSQL array indexing start at 1? I have found that, by default, the first index of an array in PLPGSQL starts at 1, and not 0 like most programming languages. I was just curious as to why this is, and what other programming language follow this? Thanks! A: What languages follow the default array indexing at 1? ALGOL 68, COBOL, Fortran (if not specified otherwise), FoxPro, Lua, MATLAB, ... anyway, the list is here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: calculator multiple values I am done with my calculator, thanks to the people here who helped me. Here what I have done: import java.awt.*; import java.awt.event.*; public class SimpleCalculator implements ActionListener { double value1=0,value2=0,result=0; static String command=null; int counter=0; // containers private Frame f; private Panel p1, p2, p3, p4,p5,p6; // components private Label l1, l2, l3; static private TextField tf1; private Button bAdd, bSub, bMul, bDiv, bClear,b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bEqual; private static void value(String num) { if((tf1.getText()).equals("0")) tf1.setText(num); else tf1.setText(tf1.getText()+num); } public SimpleCalculator() { f = new Frame("My First GUI App"); p1 = new Panel(); p2 = new Panel(); p3 = new Panel(); p4 = new Panel(); p5 = new Panel(); p6 = new Panel(); tf1 = new TextField(15); b1 = new Button("1"); b2 = new Button("2"); b3 = new Button("3"); b4 = new Button("4"); b5 = new Button("5"); b6 = new Button("6"); b7 = new Button("7"); b8 = new Button("8"); b9 = new Button("9"); b0 = new Button("0"); bAdd = new Button("+"); bSub = new Button("-"); bMul = new Button("*"); bDiv = new Button("/"); bClear = new Button("C"); bEqual = new Button("="); } public void launchFrame() { // use default layout manager of the Panel (FlowLayout) p1.add(tf1); p2.add(b1); p2.add(b2); p2.add(b3); p3.add(b4); p3.add(b5); p3.add(b6); p4.add(b7); p4.add(b8); p4.add(b9); p5.add(b0); p6.add(bAdd); p6.add(bSub); p6.add(bMul); p6.add(bDiv); p6.add(bClear); p6.add(bEqual); // change the layout manager of the Frame, // use GridLayout(4, 1) f.setLayout(new GridLayout(6, 1)); f.add(p1); f.add(p2); f.add(p3); f.add(p4); f.add(p5); f.add(p6); f.pack(); f.setVisible(true); // register event handlers b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); b0.addActionListener(this); bEqual.addActionListener(this); bAdd.addActionListener(this); bSub.addActionListener(this); bMul.addActionListener(this); bDiv.addActionListener(this); bClear.addActionListener(this); f.addWindowListener(new MyCloseButtonHandler()); } // override the actionPerformed method public void actionPerformed(ActionEvent ae) { Object source = ae.getSource(); if (source == b1) value("1"); else if (source == b2) value("2"); else if (source == b3) value("3"); else if (source == b4) value("4"); else if (source == b5) value("5"); else if (source == b6) value("6"); else if (source == b7) value("7"); else if (source == b8) value("8"); else if (source == b9) value("9"); else if (source == b0) value("0"); else if(source== bAdd){ value1=Double.parseDouble(tf1.getText()); command="+"; tf1.setText(""); } else if(source==bSub){ value1=Double.parseDouble(tf1.getText()); command="-"; tf1.setText(""); } else if(source==bDiv){ value1=Double.parseDouble(tf1.getText()); command="/"; tf1.setText(""); } else if(source == bMul){ value1=Double.parseDouble(tf1.getText()); command="*"; tf1.setText(""); } else if(source ==bClear) tf1.setText("0"); else if(source==bEqual){ value2=Double.parseDouble(tf1.getText()); if(command.equals("+")) result=value1+value2; else if(command.equals("-")) result=value1-value2; else if(command.equals("*")) result=value1*value2; else if(command.equals("/")) result=value1/value2; command="="; tf1.setText(""+result); } } private class MyCloseButtonHandler extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } public static void main(String args[]) { double value1=0; SimpleCalculator sc = new SimpleCalculator(); sc.launchFrame(); } } The problem is that they can't perform operations continuously, like 1+2+3, I have tried adding the values each time I press an operation, but it gives me a wrong output. A: I would use Java's built-in Javascript parser for your calculator. A: You are only storing two values (value1 and value2), thus you can only do math with the two. Think of ways how you could store more values. A: why not use a tool like jep to parse the expression, unless this is something you have to hand code (like a school/college project).. either ways it doesn't hurt to see the solution which exists. A: How about you display the result of the first 2 numbers (i.e. result, which works), and then when they hit another operand, you put value1 = result and value2 be the next number. Then, once they hit equals again, you get 1+2+3. You can then implement a clear button to set result = 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Model, View, Controller confusion Possible Duplicate: Understanding Model-View-Controller I have a general programming question about how to divide up my code, usually (and I'm trying to get away from this) I just write it all in the viewController, lots and lots of code in the view controller. But now i've reviewed some information on the MVC but I have some questions. My Question Mainly, if I a view controller (holding a model and a view), and in the model I run a method figures out a number display for the view, so just a simple int which the view would take and display on the screen. In order for my model to tell my view to do this should I go straight from model ----> view. Or should I return the data back to the controller and then send it to the view? Lastly, if I need to send the data back to the controller, how might I do so, because I thought that the model should'nt know about the controller, only vice-versa. Sorry for the lengthy question. Thanks for all your help. A: There's a lot of info about this in the net. From Wikipedia: Though MVC comes in different flavors, control flow is generally as follows: * *The user interacts with the user interface in some way (for example, by pressing a mouse button). *The controller notifies the model of the user action, possibly resulting in a change in the model's state. (For example, the controller updates the user's shopping cart.) *A view queries the model in order to generate an appropriate user interface (for example the view lists the shopping cart's contents). The view gets its own data from the model. In some implementations, the controller may issue a general instruction to the view to render itself. In others, the view is automatically notified by the model of changes in state (Observer) that require a screen update. *The user interface waits for further user interactions, which restarts the control flow cycle. The goal of MVC is, by decoupling models and views, to reduce the complexity in architectural design and to increase flexibility and maintainability of code. MVC has also been used to simplify the design of Autonomic and Self-Managed systems A: As long as you don't use bindings, you can simply have model-classes for your db-operations, views for your interfaceobjects and a controller, that retrieves data from the earlier and puts it in the latter and you're fairly structured. As for the way back: everything you app does, is triggered by one kind of event or another. According to those, you have to fetch the appropriate values from your interface (->outlets). For everything else, you'll actually have to do some further studying controllers and bindings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Navigation in JSF Good morning! I am novice. I have a simple JSF application. But it does not work as expected. This is my login.xhtml: <h:body> <h:outputText value="Please enter your login and password"/> <h:form id="loginForm"> <h:panelGrid columns="2"> <h:outputText value="User name"/> <h:inputText value="#{textBean.login}" required="true"/> <h:outputText value="Password"/> <h:inputSecret value="#{textBean.password}" required="true"/> <h:commandButton value="Submit" action="#{textBean.doLogin}"/> </h:panelGrid> </h:form> </h:body> This is my error.xhtml: <h:body> <h:outputText value="You have entered incorrect data"/> <h:form id="errorForm"> <h:commandLink value="Back to login page" action="#{TextBean.backToLogin}"/> </h:form> </h:body> This is my bean class TextBean.java: public class TextBean implements Serializable { private static final long serialVersionUID = 1L; private String login; private String password; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String doLogin() { if ("admin".equals(login) && "mypass".equals(password)) { return "welcome"; } else { return "error"; } } public String backToLogin() { return "login"; } } Why the error page does not go back to the login page? When you click on the link "Back to login page" I get the exception. What am I doing wrong? This is my exception: The server encountered an internal error () that prevented it from fulfilling this request. javax.servlet.ServletException: javax.el.PropertyNotFoundException: /error.xhtml @14,80 action="#{TextBean.doMyLogin}": Target Unreachable, identifier 'TextBean' resolved to null javax.faces.webapp.FacesServlet.service(FacesServlet.java:521) javax.faces.el.EvaluationException: javax.el.PropertyNotFoundException: /error.xhtml @14,80 action="#{TextBean.doMyLogin}": Target Unreachable, identifier 'TextBean' resolved to null javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:95) com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) javax.faces.component.UICommand.broadcast(UICommand.java:315) javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787) javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252) com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) javax.faces.webapp.FacesServlet.service(FacesServlet.java:508) javax.el.PropertyNotFoundException: /error.xhtml @14,80 action="#{TextBean.doMyLogin}": Target Unreachable, identifier 'TextBean' resolved to null com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:107) javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) javax.faces.component.UICommand.broadcast(UICommand.java:315) javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787) javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252) com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81) com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) javax.faces.webapp.FacesServlet.service(FacesServlet.java:508) Help me please, dear friends! Any help would be greatly appreciated. A: The name of your bean is textBean not TextBean. That is why JSF can't resolve it: identifier 'TextBean' resolved to null
{ "language": "en", "url": "https://stackoverflow.com/questions/7501719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ordering in JPA not working i'm using JPA with Hibernate implementation. I've a named query like in an entity MyTable : @NamedQuery(name = "myQuery", query = "select val from MyTable val") The myTable entity is containing a foriegn key relation with another entity. @OneToMany(mappedBy = "myTable ", cascade = { CascadeType.ALL }, fetch = FetchType.LAZY) private Set<ReferenceTable> tbl; There is a field in the ReferenceTable entity, that i need to get in sorted order when JPA runs the named query shown above. I tried @OrderBy but that didnt work. Any help would be much appreciated. Thanks, nks A: Apparently @OrderBy doesn't work well with Hibernate's JPA implementation: http://docs.jboss.org/ejb3/app-server/HibernateAnnotations/reference/en/html_single/index.html#entity-mapping-association-collections Is that what you're using? At any rate, try adding the "order by" in your JPQL query, something like select ... order by tbl DESC Also, if you want complete flexibility, make a native sql query, where you select your stuff and order it per your liking. You can even tell your native query to what class's it should marshall the results, so you get pretty much the same thing that a JPQL query would get you, but with more precision on the actual query: @NamedNativeQuery( name="myQuery", query="SELECT .... order by ... asc" resultClass=MyJPAEntity.class ) You can but the above as a class level annotation on your entity bean class. And yes, i do get the irony of using an orm framework but still being forced to rever to basic sql. A: Set<..> impl will be undordered even if DB/JPA returns an ordered collection. you can use SortedSet as shown in this example from hibernate documentation @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinColumn(name="CUST_ID") @Sort(type = SortType.COMPARATOR, comparator = TicketComparator.class) public SortedSet<Ticket> getTickets() { return tickets; } source : http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html#collections-sorted A: Unless you use org.hibernate.annotations.Sort which sorts in Java using a comparator, you are better off without java.util.Set. Using set won't help you with ordering (the best thing Hibernate could pick here would be a LinkedHashSet). I also doubt you use it to make sure an element is unique. I think you'd better use java.util.Collection which is the most generic. Hibernate uses ArrayList as default, which will keep the result set's order. However, Hibernate's implementation of @OrderBy is bad, it doesn't seem to fully implement JPA 2.0, not in 4.1.9 either. This might also be why you have troubles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does `setTimeout` not recur in Node.js? var arrayProcessTimeout; arrayProcessTimeout = setTimeout(function() { console.log('hard'); return null; }, 50); That's my code in Node.js and one would expect it to output hard constantly.. but it doesn't. It outputs it once and that's it. A: Maybe you want to use setInterval instead of setTimeout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Action Script problems with adobe Flash builder I have been given a repository full of Mxml and .AS files. The task is to edit a wack a mole game. I have loaded the repository into the flash builder by using new -> Flex Project then i set the project location to the root repository. It has now been loaded into flash builder but when i click run maingame on the maingame file, it doesn't run, i get an error message saying File not found: file:/C:/Users/Tom/Desktop/DubitPlatform-Co/bin-debug/MainGameView.html any ideas where i am going wrong? Thanks here is the code for the maingameview.mxml file <?xml version="1.0" encoding="utf-8"?> <views:MainGameViewBase xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:views="uk.co.dubit.whackamole.views.*" xmlns:components="uk.co.dubit.whackamole.views.components.*" styleName="stretchToContainer"> <fx:Declarations> <s:Sequence id="startAnimation" effectEnd="startAnimationEnd()"> <s:Sequence id="readyAnimation" target="{readyLabel}" > <s:Parallel duration="400"> <s:Fade alphaFrom="0" alphaTo="1" /> <s:Scale scaleXFrom="0" scaleYFrom="0" scaleXTo="1" scaleYTo="1" /> </s:Parallel> <s:Pause duration="1000" /> <s:Fade alphaFrom="1" alphaTo="0" duration="100" /> </s:Sequence> <s:Sequence id="goAnimation" target="{goLabel}" > <s:Parallel duration="400"> <s:Fade alphaFrom="0" alphaTo="1" /> <s:Scale scaleXFrom="0" scaleYFrom="0" scaleXTo="1" scaleYTo="1" /> </s:Parallel> <s:Pause duration="1000" /> <s:Fade alphaFrom="1" alphaTo="0" duration="100" /> </s:Sequence> </s:Sequence> </fx:Declarations> <s:VGroup width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10" gap="10"> <s:HGroup width="100%" height="100%" gap="10"> <s:BorderContainer styleName="roundedBorder" minHeight="0" minWidth="0" width="66%" height="100%" > <s:Label id="readyLabel" text="Ready?" fontSize="72" color="0xffffff" verticalCenter="0" horizontalCenter="0" alpha="0"> <s:filters> <s:GlowFilter color="0x000000" strength="10" /> </s:filters> </s:Label> <s:Label id="goLabel" text="Go!" fontSize="72" color="0xffffff" verticalCenter="0" horizontalCenter="0" alpha="0"> <s:filters> <s:GlowFilter color="0x000000" strength="10" /> </s:filters> </s:Label> <s:DataGroup id="moleHolesDataGroup" dataProvider="{ moleHoles }" itemRenderer="uk.co.dubit.whackamole.views.MoleHoleItemRenderer" verticalCenter="0" horizontalCenter="0"> <s:layout> <s:TileLayout requestedRowCount="3" requestedColumnCount="3" horizontalGap="10" verticalGap="10" /> </s:layout> </s:DataGroup> </s:BorderContainer> <s:VGroup width="33%" height="100%" gap="10"> <s:BorderContainer styleName="roundedBorder" minHeight="0" minWidth="0" width="100%" height="30" > <s:Label text="Achievements" verticalCenter="0" horizontalCenter="0" /> </s:BorderContainer> <s:BorderContainer styleName="roundedBorder" minHeight="0" minWidth="0" width="100%" height="100%" > </s:BorderContainer> </s:VGroup> </s:HGroup> <s:BorderContainer styleName="roundedBorder" minHeight="0" minWidth="0" width="100%" height="30" bottom="10" > <s:Label text="Score: { mainGame.score }" left="10" verticalCenter="0"/> </s:BorderContainer> </s:VGroup> </views:MainGameViewBase> Im not 100% sure that this is the file that i should run to be able to play the game. Which would the file be that makes the game executable? A: Your HTML is not getting generated. Following are some try which i can say... Does your bin-debug has MainGameView.html * *Can you post down your MainGameView.mxml file, there should be some error which is not generating your html output. *Delete the contents of maingame.mxml file and just include the Application tag alone, see whether you are able to generate MainGameView.html in bin-debug
{ "language": "en", "url": "https://stackoverflow.com/questions/7501733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programmatically determine human readable color (e.g. Red, Green, etc..) of an image I'm trying to come up with a script that will programmatically run through an image and tell me it's primary color(s). Currently the script gets the RGB value of each pixel. Compares them against predefined rules and attempts to count up the number of pixels of each colour. My problem is the script is a little hit and miss. Does anyone know of a better way of doing this (maybe using a different colour coding system that's easier to translate to english) or an existing set of rules defining colours via their RGB? <?php $file = "8629.jpg"; $colors = array("Red" => array("rel" => true, "r" => 0.65, "g" => 0.09, "b" => 0.25, "var" => 0.3), "Blue" => array("rel" => true, "r" => 0.21, "g" => 0.32, "b" => 0.46, "var" => 0.3), "Green" => array("rel" => true, "r" => 0, "g" => 0.67,"b" => 0.33, "var" => 0.3), "Black" => array("rel" => false, "r" => 0, "g" => 0,"b" => 0, "var" => 30), "White" => array("rel" => false, "r" => 255, "g" => 255,"b" => 255, "var" => 30)); $total = 0; $im = imagecreatefromjpeg($file); $size = getimagesize($file); if (!$im) { exit("No image found."); } for ($x = 1; $x <= $size[0]; $x++) { for($y = 1; $y <= $size[1]; $y++) { $rgb = imagecolorat($im, $x, $y); $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $colorTotal = $r + $g + $b; $rRatio = $r > 0 ? $r / $colorTotal : 0; $gRatio = $g > 0 ? $g / $colorTotal : 0; $bRatio = $b > 0 ? $b / $colorTotal : 0; foreach($colors as $key => $color) { if ($color["rel"]) { if ((($color["r"] - $color["var"]) <= $rRatio && $rRatio <= ($color["r"] + $color["var"])) && (($color["g"] - $color["var"]) <= $gRatio && $gRatio <= ($color["g"] + $color["var"])) && (($color["b"] - $color["var"]) <= $bRatio && $bRatio <= ($color["b"] + $color["var"]))) { $colourCount[$key]++; $total++; } } else { if ((($color["r"] - $color["var"]) <= $r && $r <= ($color["r"] + $color["var"])) && (($color["g"] - $color["var"]) <= $g && $g <= ($color["g"] + $color["var"])) && (($color["b"] - $color["var"]) <= $b && $b <= ($color["b"] + $color["var"]))) { $colourCount[$key]++; $total++; } } } } } var_dump($colourCount); foreach($colourCount as $key => $color) { $colourPrecent[$key] = $color / $total; } arsort($colourPrecent); var_dump($colourPrecent); foreach($colourPrecent as $key => $color) { if ($prevVal) { if ($color < ($prevVal - 0.1)) { break; } } $primary[] = $key; $prevVal = $color; } echo("The primary colours in this image are " . implode(" and ", $primary)); ?> A: Solution was to convert the RGB to HSL as suggested by Herbert. Function for converting to human still needs a little tweaking / finishing off but here it is: function hslToHuman($h, $s, $l) { $colors = array(); // Gray if ($s <= 10 && (9 <= $l && $l <= 90)) { $colors[] = "gray"; } $l_var = $s / 16; // White $white_limit = 93; if (($white_limit + $l_var) <= $l && $l <= 100) { $colors[] = "white"; } // Black $black_limit = 9; if (0 <= $l && $l <= ($black_limit - $l_var)) { $colors[] = "black"; } // If we have colorless colors stop here if (sizeof($colors) > 0) { return $colors; } // Red if (($h <= 8 || $h >= 346)) { $colors[] = "red"; } // Orange && Brown // TODO // Yellow if (40 <= $h && $h <= 65) { $colors[] = "yellow"; } // Green if (65 <= $h && $h <= 170) { $colors[] = "green"; } // Blue if (165 <= $h && $h <= 260) { $colors[] = "blue"; } // Pink && Purple // TODO return $colors; } A: Alright so you've got a graphics library, there must be an average thingy in there, you average your picture, take any pixel and tadaam you're done ? And the simplest solution found on here is : resize to 1x1px, get colorat : Get image color After that it's pretty easy, find somewhere a detailed list of rgb to human readable (for example html colors), encode that as an array and use it in your script -> round() your r,g,b, vals to the precision of your data and retrieve the color. You should determine what color granularity you want and go from there -> find your set of named colors (I think all 8bit colors have a name somewhere) and then reduce your rgb information to that - either by reducing color information of the image before reading it (faster) or by reducing color information at read time (more flexible in terms of color list. Basic example of some rgb-human readable resources : http://www.w3schools.com/html/html_colornames.asp Others : http://chir.ag/projects/name-that-color/#2B7C97 http://r0k.us/graphics/SIHwheel.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7501737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Url rewritting multiple domains and subfolders asp.mvc I have got some site on on http://mydomain.com/mysite, with few dynamic subsites http://mydomain.com/mysite/category1, http://mydomain.com/mysite/othercategory2 I would like to access mysite/{dynamiccategoryname} from other address http://otherdomain.com. It should work with mysite and mysite/category1 ... http://otherdomain.com should show http://mydomain.com/mysite http://otherdomain.com/category1 should show http://mydomain.com/mysite/category1 but not with redirecting client. A: This can be done with URL rewriting. You basically need to rewrite all requests with hostname otherdomain.com to /mysite/*. This can be done with the following rewrite rule: <configuration> <system.webServer> <rewrite> <rules> <rule name="Rewrite all request for otherdomain.com to /mysite"> <match url="(.*)" /> <conditions> <add input="{HTTP_HOST}" pattern="^otherdomain\.com$" /> </conditions> <action type="Rewrite" url="/mysite/{R:0}" /> </rule> </rules> </rewrite> </system.webServer> </configuration> Another solution is to set up a secondary site in IIS, with hostname otherdomain.com on the same IP but let the path of that site point to the physical path of the /mysite folder. But if you need the ASP.NET MVC application of mydomain.com on otherdomain.com as well that will not work of course. But it can be a solution if otherdomain.com is e.g. just for serving static content (images, css, script).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does this pattern take a long time to match in java? The following regex pattern, when applied to very long strings (60KB), causes java to seem to "hang". .*\Q|\E.*\Q|\E.*\Q|\E.*bundle.* I don't understand why. A: You have 5 eager/greedy quantifiers in that regex, so you could well be doing a huge amount of backtracking. This article explains this behaviour at length and has suggestions for making your regex performance better. In this case, the answer may be to replace the greedy quantifiers with non-greedy ones, or better still to use non-backtracking subpatterns. A: First, I think you could simplify your regex as follows: .*\Q|\E.*\Q|\E.*\Q|\E.*bundle.* could become .*\|.*\|.*\|.*bundle.* Second, to sorta answer your question, the fact that you have so many ".*"s in your regex means that there are a TON of possibilities that the regex solution must work through. The following might work faster if this would work for your situation. (?:[^\|]*\|){3}[^|]*bundle.* by changing "." to "[^|]" you narrow the focus of the engine since the first ".*" will not eagerly grab the first "|". A: Basically, the ".*" (match any number of anything) means try to match the entire string, if it doesn't match, then go back and try again, etc. using one of these is not too much of a problem, but the time necessary to use more than one increases exponentially. This is a fairly in-depth (and much-more accurate) discussion of this sort of thing: http://discovery.bmc.com/confluence/display/Configipedia/Writing+Efficient+Regex EDIT: (I hope you really wanted to know WHY) Example Source String: aaffg, ";;p[p09978|ksjfsadfas|2936827634876|2345.4564a bundle of sticks ONE WAY OF LOOKING AT IT: The process takes so long because the .* matches the entire source string (aaffg, ";;p[p09978|ksjfsadfas|2936827634876|2345.4564a bundle of sticks), only to find that it does not end in a | symbol, then backtracks to the last case of a | symbol (...4876|2345...), then tries to match the next .* all the way to the end of the string. It starts looking for the next | symbol specified in your expression, and not finding it, it then backtracks to the first | symbol that was matched (the one in ...4876|2345...), discards that match and finds the closest | before it (...dfas|2936...), so that it will be able to match the second | symbol in your match expression. It will then proceed to match the .* to 2936827634876 and the second | to the one in ...4876|2345... and the next .* to the remaining text, only to find that you wanted yet another |. It will then continue to backtrack again and again, until it matches all of the symbols you specified. ANOTHER WAY OF LOOKING AT IT: (Original expression): .*\Q|\E.*\Q|\E.*\Q|\E.*bundle.* this roughly translates to match: any number of anything, followed by a single '|', followed by any number of anything, followed by a single '|', followed by any number of anything, followed by a single '|', followed by any number of anything, followed by the literal string 'bundle', followed by any number of anything the problem is that any number of anything includes | symbols, requiring parsing of the entire string over and over again where what you really mean is any number of anything that is not a '|' To fix or improve the expression, I would recommend three things: First (and most significant), replace the majority of the "match anything"s (.*) with negated character classes ([^|]) like so: [^|]*\Q|\E[^|]*\Q|\E[^|]*\Q|\E.*bundle.* ...this will prevent it from matching to the end of the string over and over again, but instead matching all the non-| symbols up to the first character that is not a "not a | symbol" (that double negative means up to the first | symbol), then matching the | symbol, then going to the next, etc... The second change (somewhat significant, depending upon your source string) should be making the second-to-last "match any number of anything" (.*) into a "lazy" or "reluctant" type of "any number of" (.*?). This will make it try to match anything with the idea of looking out for bundle instead of skipping over bundle and matching the rest of the string, only to realize that there is more to match once it gets there, having to backtrack. This would result in: [^|]*\Q|\E[^|]*\Q|\E[^|]*\Q|\E.*?bundle.* The third change I would recommend is for readability - replace the \Q\E blocks with a single escape, as in \|, like so: [^|]*\|[^|]*\|[^|]*\|[^|].*?bundle.* This is how the expression is internally processed anyways - there is literally a function that converts the expression to "escape all the special characters in between \Q and \E" - \Q\E is a shorthand only, and if it does not make your expression shorter or easier to read, it should not be used. Period. The negated character classes have an un-escaped | because | is not a special character within the context of character classes - but let's not digress too much. You can escape them if you'd like, but you don't have to. The final expression translates roughly to: match: any number of anything that is not a '|', followed by a single '|', followed by any number of anything that is not a '|', followed by a single '|', followed by any number of anything that is not a '|', followed by a single '|', followed by any number of anything, up until the next expression can be matched, followed by the literal string 'bundle', followed by any number of anything A good tool that I use (but costs some money) is called RegexBuddy - a companion/free website for understanding regex's is http://www.regular-expressions.info, and the particular page that explains repetition is http://www.regular-expressions.info/repeat.html RegexBuddy emulates other regex engines and says that your original regex would take 544 'steps' to match as opposed to 35 'steps' for the version I provided. SLIGHTLY LONGER Example Source String A: aaffg, ";;p[p09978|ksjfsadfas|12936827634876|2345.4564a bundle of sticks SLIGHTLY LONGER Example Source String B: aaffg, ";;p[p09978|ksjfsadfas|2936827634876|2345.4564a bundle of sticks4me Longer source string 'A' (added 1 before 2936827634876) did not affect my suggested replacement, but increased the original by 6 steps Longer source string 'B' (added '4me' at the end of the expression) again did not affect my suggested replacement, but added 48 steps to the original Thus, depending on how a string is different from the examples above, a 60K string could only take 544 steps, or it could take more than a million steps
{ "language": "en", "url": "https://stackoverflow.com/questions/7501745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I create an image tooltip hover over form labels with jQuery? How can I put an image tooltip on the label of all radio buttons within a form? I am using simple_form to generate the form markup, so each label has a for attribute (e.g. for="reward_id_79") that I could use to link the label with its corresponding image img src='blah.jpg' id='reward_id_79'. Each radio input will have an associated image that I'd like to display in a tooltip popup with the user hovers over the label text. I'd like not to alter the simple_form output, but instead have a series of hidden images elsewhere in the page. A: Take a look at the poshytips jquery plugin. http://vadikom.com/demos/poshytip/ It does pretty much what you need and is really easy to use. A: There's a jQuery tooltip plugin you could try, which looks like quite full-featured.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Selecting UISegmentedControl controls result in SIGABRT The objective is to have a MKMapView which switches from mapType by making use of a UISegmentedControl. When pressing one of the segmented controls however, I get this in my output: 2011-09-21 18:36:39.127 ShutterBug[2022:ec03] -[__NSCFData indexOfObject:]: unrecognized selector sent to instance 0x5c90700 2011-09-21 18:36:39.130 ShutterBug[2022:ec03] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData indexOfObject:]: unrecognized selector sent to instance 0x5c90700' Here is the relevant part of my code, getting SIGABRT on first line of changeMapType: static NSArray *mapTypeChoices = nil; #define MAP_STREET @"Street" #define MAP_SATELLITE @"Satellite" #define MAP_HYBRID @"Hybrid" - (UISegmentedControl *)mapTypeSegmentedControl { if (!mapTypeChoices) mapTypeChoices = [NSArray arrayWithObjects:MAP_STREET, MAP_SATELLITE, MAP_HYBRID, nil]; UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:mapTypeChoices]; segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; [segmentedControl addTarget:self action:@selector(changeMapType:) forControlEvents:UIControlEventValueChanged]; switch (self.mapView.mapType) { case MKMapTypeStandard: segmentedControl.selectedSegmentIndex = [mapTypeChoices indexOfObject:MAP_STREET]; break; case MKMapTypeSatellite: segmentedControl.selectedSegmentIndex = [mapTypeChoices indexOfObject:MAP_SATELLITE]; break; case MKMapTypeHybrid: segmentedControl.selectedSegmentIndex = [mapTypeChoices indexOfObject:MAP_HYBRID]; break; } return [segmentedControl autorelease]; } - (void)changeMapType:(UISegmentedControl *)segmentedControl { if (segmentedControl.selectedSegmentIndex == [mapTypeChoices indexOfObject:MAP_STREET]) { self.mapView.mapType = MKMapTypeStandard; } else if (segmentedControl.selectedSegmentIndex == [mapTypeChoices indexOfObject:MAP_SATELLITE]) { self.mapView.mapType = MKMapTypeSatellite; } else if (segmentedControl.selectedSegmentIndex == [mapTypeChoices indexOfObject:MAP_HYBRID]) { self.mapView.mapType = MKMapTypeHybrid; } } EDIT: debugger is showing me that changeMapType: is called twice when pressed UISegmentedController only once.. A: mapTypeChoices is autoreleased when you create it in mapTypeSegmentedControl. The memory has been reallocated to something else (NSData by the look of it) in the meantime, so it crashes when you try to ask for indexOfObject. Assuming mapTypeChoices is a class instance variable, just retain it after you create it and you're all set. (Remember to release on dealloc, though! A: Your static array, mapTypeChoices, is being autoreleased. This isn't a class property, so it will not be retained automatically (assuming you would have defined the retain property attribute). Don't use the autoreleased initializer for NSArray. Use -initWithObject: instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Twitter4j 401 Authentication This is the code that is causing the problem. And below is the Logcat. I have printed the exception. I have checked the consumer and secret keys multiple times. Could anyone shed anymore light or how to get more details on this issue? I should also mention that I have run this script on the emulator and a real phone, both bring back the same logcat 09-21 15:27:25.504: ERROR/HelloWorld(17680): 401:Authentication credentials (https://dev.twitter.com/docs/auth) were missing or incorrect. Ensure that you have set valid conumer key/secret, access token/secret, and the system clock in in sync. 09-21 15:27:25.504: ERROR/HelloWorld(17680): Failed to validate oauth signature and token 09-21 15:27:25.504: ERROR/HelloWorld(17680): Relevant discussions can be on the Internet at: 09-21 15:27:25.504: ERROR/HelloWorld(17680): http://www.google.co.jp/search?q=10f5ada3 or 09-21 15:27:25.504: ERROR/HelloWorld(17680): http://www.google.co.jp/search?q=dceba039 09-21 15:27:25.504: ERROR/HelloWorld(17680): TwitterException{exceptionCode=[10f5ada3-dceba039], statusCode=401, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.4} 09-21 15:27:25.504: ERROR/HelloWorld(17680): at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:185) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at com.blundell.tut.ttt.TweetToTwitterActivity.loginNewUser(TweetToTwitterActivity.java:109) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at com.blundell.tut.ttt.TweetToTwitterActivity.buttonLogin(TweetToTwitterActivity.java:83) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at java.lang.reflect.Method.invokeNative(Native Method) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at java.lang.reflect.Method.invoke(Method.java:521) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at android.view.View$1.onClick(View.java:2077) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at android.view.View.performClick(View.java:2461) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at android.view.View$PerformClick.run(View.java:8890) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at android.os.Handler.handleCallback(Handler.java:587) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at android.os.Handler.dispatchMessage(Handler.java:92) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at android.os.Looper.loop(Looper.java:123) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at java.lang.reflect.Method.invokeNative(Native Method) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at java.lang.reflect.Method.invoke(Method.java:521) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629) 09-21 15:27:25.504: ERROR/HelloWorld(17680): at dalvik.system.NativeStart.main(Native Method) A: Maybe, you`ve created a desktop application. Change type of your app on browser app. This is good tutorial http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/ A: 09-21 15:27:25.504: ERROR/HelloWorld(17680): 401:Authentication credentials (https://dev.twitter.com/docs/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret You have entered wrong Consumer Key or Secret Key from your Created Application in Twitter. Ensure that you gave the two keys also ensure that it is correct. For Further Reference Check this Integrating Twitter with Android A: look at My application setting and Application type Access: * *Read only *Read and Write *Read, Write and Access direct messages What type of access does your application need? Note: @Anywhere applications require read & write access. Find out more about our Application Permission Model. Default is read only please select read and write and again. A: Well my device's date was incorrect. Seemed strange but, it did work. When the date was set correct it worked fine. You may show an alert asking the user to check the device current date and/or time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clone a generic type I want to clone a generic object and preserve its type. run.Append(style.Clone(BlackFont)); //run object accepts only RunProperties objects public T Clone(T what) { if (what is RunProperties) return (T) what.Clone(); } It doesn't work since T type does not have a Clone method, how can I overcome this without casting in the first statement. run.Append((RunProperties) style.Clone(BlackFont)); //I do not want this //not that this will work since you can't convert T to RunProperties Thanks for any help. ---EDIT--- It seems that it would be better for my not to use generics in this case. I'll split up the data. A: Here is a function I wrote that clones a record of type T, using reflection. This is a very simple implementation, I did not handle complex types etc. public static T Clone<T>(T original) { T newObject = (T)Activator.CreateInstance(original.GetType()); foreach (var originalProp in original.GetType().GetProperties()) { originalProp.SetValue(newObject, originalProp.GetValue(original)); } return newObject; } I hope this can help someone. A: You could always constrain the method to only accept types that implement the ICloneable interface: public T Clone(T what) where T : ICloneable { if (what is RunProperties) return (T) what.Clone(); } But since your method really only works with one type, you could change it slightly and use the as operator also: public T Clone(T what) { var castWhat = what as RunProperties; if(castWhat != null) return castWhat.Clone(); } A: You can use a generic constraint to constrain the type of T to a type which implements ICloneable. A: you're almost giving the answer yourself: T type does not have a Clone method Also, what is the point of a generic method if you only do something for one type? The Clone method comes from the ICloneable interface, so you can implement your generic Clone method, making it work for all types that implement ICloneable like this: public T Clone<T>(T what) where T: ICloneable { return (T) what.Clone(); } A: You could use a generic constraint: public T Clone<T>(T what) where T: ICloneable { if (what is RunProperties) return (T)what.Clone(); ... } or if the T generic parameter is defined on the containing class: public class Foo<T> where T: ICloneable { public T Clone(T what) { if (what is RunProperties) return (T)what.Clone(); ... } } A: I would suggest defining an interface ISelf<out T>, with a single read-only property called "Self", of type T (which, in any implementation, should return "this"). Them define ICloneable<out T> which inherits ISelf<T> and implements a method, Clone(), of type T. Then, if you have a method which needs something which derives from type Foo and is cloneable, simply pass that method an ICloneable<Foo>. To use the passed-in object as a "Foo", access its "Self" property. I would suggest that classes with public clone methods should often be sealed, but extend unsealed types simply by adding a public "Clone" wrapper. That will allow for the existence of derived types which do or do not allow cloning. Consider the class family Foo, CloneableFoo, DerivedFoo, and CloneableDerivedFoo, and OtherDerivedFoo. * *Foo does not provide a public Clone method; it could be cloned without difficulty, and has a protected MakeClone method. *CloneableFoo derives from Foo, and exposes a public Clone method which wraps MakeClone and implements ICloneable<CloneableFoo>. *DerivedFoo is derived from Foo; like Foo, it but does not have a public Clone method, but offers a protected MakeClone method. *CloneableDerivedFoo derives from DerivedFoo, and exposes a public Clone method which wraps MakeClone and implements ICloneable<CloneableDerivedFoo>. *OtherDerivedFoo derives from DerivedFoo, but has class invariants which would be broken if cloned; it shadows MakeClone with a void function that is tagged obsolete-error. Given those relationships, it would be useful for one method to accept any cloneable derivative of Foo, while another method will accept any derivative--cloneable or not--of DerivedFoo. The first method should use a parameter of type ICloneable<Foo>, while the latter takes a parameter of type DerivedFoo. Note that if DerivedFoo were derived from CloneableFoo rather than Foo, it would not be possible to have anything derive from DerivedFoo without promising a public Clone method. A: Use FastDeepcloner i developed https://www.nuget.org/packages/FastDeepCloner/ /// <summary> /// Clone Object, se FastDeepCloner for more information /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items"></param> /// <param name="fieldType"></param> /// <returns></returns> public static List<T> Clone<T>(this List<T> items, FieldType fieldType = FieldType.PropertyInfo) { return DeepCloner.Clone(items, new FastDeepClonerSettings() { FieldType = fieldType, OnCreateInstance = new Extensions.CreateInstance(FormatterServices.GetUninitializedObject) }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: div scrollbar width Is there an easy way to get the width of a scrollbar using javascript / jquery ? I need to get the width of a div that overflows + whatever width the scroll bar is. Thank you A: try this $("#myDiv")[0].scrollWidth A: Setting a div's overflow to "scroll" automatically adds scrollbars (even if there's nothing inside, the scrollbars will be there, but grey). So just make a div, find the width, set overflow to scroll, and find the new width, and return the difference: function getScrollBarWidth() { var helper = document.createElement('div'); helper.style = "width: 100px; height: 100px; overflow:hidden;" document.body.appendChild(helper); var bigger = helper.clientWidth; helper.style.overflow = "scroll"; var smaller = helper.clientWidth; document.body.removeChild(helper); return(bigger - smaller); } A: if you're using jquery, try this: function getScrollbarWidth() { var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div></div>'); $('body').append(div); var w1 = $('div', div).innerWidth(); div.css('overflow-y', 'auto'); var w2 = $('div', div).innerWidth(); $(div).remove(); return (w1 - w2); } i'm using this in the project i'm working on and it works like a charm. it gets the scrollbar-width by: * *appending a div with overflowing content to the body (in a non-visible area, -200px to top/left) *set overflow to hidden *get the width *set overflow to auto (to get scrollbars) *get the width *substract both widths to get width of the scrollbar so what you'll have to do is getting the width of your div ($('#mydiv').width()) and add the scrollbar-width: var completewidth = $('#mydiv').width() + getScrollbarWidth(); A: Here is a plain javascript version that is way faster. function getScrollbarWidth() { var div, body, W = window.browserScrollbarWidth; if (W === undefined) { body = document.body, div = document.createElement('div'); div.innerHTML = '<div style="width: 50px; height: 50px; position: absolute; left: -100px; top: -100px; overflow: auto;"><div style="width: 1px; height: 100px;"></div></div>'; div = div.firstChild; body.appendChild(div); W = window.browserScrollbarWidth = div.offsetWidth - div.clientWidth; body.removeChild(div); } return W; };
{ "language": "en", "url": "https://stackoverflow.com/questions/7501761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Does QProcess::close() raise the unix SIGTERM signal on the process? In Linux/Qt I have a GUI application. The GUI starts up additional child processes using QProcess. To close the child processes I use QProcess::close(). Does QProcess::close() raise the unix SIGTERM signal for the child process? (I have linked to the Qt documentation for QProcess and close() because I can not tell from the documentation if a unix signal is raised...) UPDATE: changed question to ask about a specific unix signal: SIGTERM. A: Today I found out that QProcess::close() does not raise the SIGTERM signal. To debug this issue I am capturing the stderr and stdout of the child process. Spoiler: QProcess::terminate() does raise the SIGTERM signal. Child process code to handle unix SIGTERM signal: static void unixSignalHandler(int signum) { qDebug("DBG: main.cpp::unixSignalHandler(). signal = %s\n", strsignal(signum)); /* * Make sure your Qt application gracefully quits. * NOTE - purpose for calling qApp->exit(0): * 1. Forces the Qt framework's "main event loop `qApp->exec()`" to quit looping. * 2. Also emits the QCoreApplication::aboutToQuit() signal. This signal is used for cleanup code. */ qApp->exit(0); } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MAINOBJECT mainobject; /* * Setup UNIX signal handlers for some of the common signals. * NOTE common signals: * SIGINT: The user started the process on the command line and user ctrl-C. * SIGTERM: The user kills the process using the `kill` command. * OR * The process is started using QProcess and SIGTERM is * issued when QProcess::close() is used to close the process. */ if (signal(SIGINT, unixSignalHandler) == SIG_ERR) { qFatal("ERR - %s(%d): An error occurred while setting a signal handler.\n", __FILE__,__LINE__); } if (signal(SIGTERM, unixSignalHandler) == SIG_ERR) { qFatal("ERR - %s(%d): An error occurred while setting a signal handler.\n", __FILE__,__LINE__); } // executes mainbobject.cleanupSlot() when the Qt framework emits aboutToQuit() signal. QObject::connect(qApp, SIGNAL(aboutToQuit()), &mainobject, SLOT(cleanupSlot())); return a.exec(); } Parent process code that handles close() or terminate() of the child: if(this->childProcess1!=NULL && this->childProcess1->state()==QProcess::Running) { this->childProcess1->terminate(); // raise unix SIGTERM signal on the process (let's it execute cleanup code) if(childProcess1->waitForFinished() == false) { qDebug("DBG - MainWindow::close(): Failed to close childProcess1."); qDebug() << "DBG - childProcess1->exitCode =" << childProcess1->exitCode(); qDebug() << "DBG - childProcess1->ExitStatus =" << childProcess1->exitStatus(); qDebug() << "DBG - childProcess1->error() =" << childProcess1->error(); qDebug() << "DBG - childProcess1->errorString()=" << childProcess1->errorString(); } } if(this->childProcess2!=NULL && this->childProcess2->state()== QProcess::Running) { this->childProcess2->terminate(); // raise unix SIGTERM signal on the process (let's it execute cleanup code) if(childProcess2->waitForFinished() == false) { qDebug("DBG - MainWindow::close(): Failed to close childProcess2."); qDebug() << "DBG - childProcess2->exitCode =" << childProcess2->exitCode(); qDebug() << "DBG - childProcess2->ExitStatus =" << childProcess2->exitStatus(); qDebug() << "DBG - childProcess2->error() =" << childProcess2->error(); qDebug() << "DBG - childProcess2->errorString()=" << childProcess2->errorString(); } } When the parent uses QProcess::terminate(), the child process output is: "DBG: main.cpp::unixSignalHandler(). signal = Terminated When the parent uses `QProcess::close(), the child process output is: DBG - PARENTOBJECT::close(): Failed to close childProcess. DBG - childProcess->exitCode = 0 DBG - childProcess->ExitStatus = 1 DBG - childProcess->error() = 1 DBG - childProcess->errorString()= "Unknown error" The output from the terminate() experiment proves that the child process is getting a SIGTERM signal. The output from the close() experiment proves that the child process is not getting the SIGTERM signal. Conclusion: If you want to send the child process the SIGTERM signal, use QProcess::terminate(). A: It does, I'm looking at the source for qprocess.cpp and it goes through some motions to nicely wind the process down, then calls off to a generic handler, then passes to terminateProcess in qprocess_unix which SIGTERM's the process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing managedObjectContext - is this efficient? I have an app I am working on. There is a navigation controller, and my appDelegate is passing its managedObjectContext to the nav controllers root controller like so: RootViewController *rootViewController = (RootViewController *)[navigationController topViewController]; rootViewController.managedObjectContext = self.managedObjectContext; (Bonus question - I've read the above is the preferred way to pass the context, as opposed to some examples I see where the view controller grabs the context from the delegate - is this correct? Also, do I need to release rootViewController above, or am I correct in that it is autoreleased because it was not created using alloc or new?) Anyway, the main view of the app has a button - when clicked, it records a timestamp and saves it in core data. The app then displays a second view, which is where the user is going to work with a subset of the data. This second view allows the user to choose to see all timestamps from the current week, month, or year. My initial thought is to pass the managedObjectContext from the rootVC to the detailVC, and perform the data read and queries in the detailVC. Is this the proper way to go about this, or is it better to perform the query at the rootVC and pass the data to the detail controller as an array or something? Or does it make no difference other than organizationally (no performance difference) - 6 of one, half a dozen of the other? A: You don't really have to worry about the efficiency of this, it will perform fine whichever way you do it - you're just passing a pointer around. That's not to say this is a decent way of going about things though. Apple's Core Data templates are pretty terrible. Generally speaking, it's better to factor out your data management into a separate manager class that has responsibility for managing your data. A: I think that passing the MOC around your view controllers, as you said in your question, is a good approach. The idea behind the MVC pattern is that view controllers take care of the business logic, so in such if you pass to it the MOC (which is at the end the Model) you give your second view controller the capability to perform its own business logic independently of any other view controller. Instead if you decide to perform the query on the first view controller and then pass the result to the second view controller and finally passing back to the first view controller the changes occurred in the second, you're adding extra complexity to the first view controller, besides you add a bidirectional link between the two view controllers (so any change in one VC will required changes to the other!) and finally you reduce the second view controller basically to a view with some functionality but no model interaction. Finally you can use, as suggested in another post, a singleton that takes care of all MOC interactions. But in my opinion with this approach you're adding an extra management layer on top of an existing management layer, which is represented by the MOC. This approach makes sense when you want to get rid of all business logic stuff in your view controllers, but this is usually desired when there are many complex activities that need to be shared by several view controllers: but in such case probably it's time to think about a different organization of your app. Finally my answer to your bonus question: you don't need to release the view controller, don't do that! Until it is inside the navigation controller and you don't release the navigation controller, your view controller is protected from being dealloc'd. A: I find that passing round a managed object context (MOC) is a bit of a pain. Especially if you need to access it in many different places, which you know doubt will Usually, what I do is create a class to handle various Core Data bits and bobs for me. I make this a singleton that can be accessed anywhere with one call. I then invoke the method to get the MOC. For example: myMOC = [[MyPersistentStoreController sharedMyPersistentStoreController] managedObjectContext]]; For info on how to easily create a singleton, have a look at Matt Gallagher's blog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIControlStateHighlighted equivalent for UISegmentedControl, iphone If one is using UIbuttons, Uibuttons background image/colour can be set with property UIControlStateHighlighted. [UIButton setBackgroundImage: UIImage forState:UIControlStateHighlighted]; I want similar property for UIsegmentedControl. If any of these segmented bar is pressed I want to change colour of that bar only when it is pressed. Colour should get back to default when that bar is released. May be I am missing something obvious but is there any property of UIsegmentedControl ?. thanks for any help in advance.. A: Even i was trying to do same thing and this is not possible, i tried all the way, so i created two buttons with image and put together(so feel like segmented button). A: [segmentControl setMomentary:YES]; A: The documentation only has tintColor which applies to the whole control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Protovis map visualization: US+Canada I'm trying to make a choropleth map which includes both US states and Canadian provinces on the same map and I'm having some issues dealing with the base map. Protovis comes with a dataset called us_lowres.js but there is no good corresponding Canadian dataset... I have found this SVG map which I would like to use: http://upload.wikimedia.org/wikipedia/commons/5/55/BlankMap-USA-states-Canada-provinces%2C_HI_closer.svg but I want to color it using Protovis if at all possible. The question is: how can I use the data in this SVG to create a map that protovis can understand? Protovis has functionality for Geographic scales but this SVG is just in whatever linear coordinate system it was drawn in, not lat/lng. Any great ideas out there? :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7501769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spreadsheet multiple formulas mashup I’m trying to automate some processes for task management, but I’m having no success. I can’t use macros or similar, just formulas, and I’m not an adept at spreadsheet hacking. Anyways, here’s my workbook, with its **sheets**: **Form** TASK LI DE X Test 1 3 Test2 2 **LI** WEEK TASK COMPLETED 1 Test 2 Test 2 Test * 4 Test2 * **DE** WEEK TASK COMPLETED 1 Test * What I’ve been trying to do is: * *On Form, check which column, from LI or DE, is > 0. *For each one > 0, check for the existence of TASK on its respective sheet (LI or DE). *If it is there, check if it has an *. *If it has an *, take the WEEK number of that row, compare it to the WEEK from the other sheet, take the greater number, and load it into the X column of the TASK on Form. The order here doesn’t really matter. I just need the WEEK from the one with an *. For this example, in order for X to change, TASK must be with an * in the sheets where it is. For instance, if, on Form, Test has numbers in LI and DE, and Test has an * in LI sheet, but not in DE sheet, X must remain empty. But if both have it with *, X must be loaded with the greater WEEK between LI and DE. If I were to do it with macros, I would simply check each column with a loop, but with formulas I suppose nested IFs would suffice. I’ve tried with VLOOKUP, but it only takes the first item in the array, and though the order doesn’t matter, it is generally (I think I will make this a policy) the last value. Any doubt, just let me know! I hope I made my issue clear. Thank you very much in advance! A: I think you can do it with formula but as you will have to loop, you will need SUMPRODUCT or Array Formula. Here is a formula you can try (validate with CtrlShiftEnter): =MAX((LI!$C$2:$C$5="*")*(LI!$A$2:$A$5)*(LI!$B$2:$B$5=Form!A2),(DE!$C$2:$C$5="*")*(DE!$A$2:$A$5)*(DE!$B$2:$B$5=Form!A2)) Some explanation: * *The MAX formula will find the greatest value between the two ARRAY FORMULA of the two worsheets *The array formula works like a multiple loop test: * *(LI!$C$2:$C$5="*") checks if there is a star in the third column *(LI!$A$2:$A$5) will return the week number *(LI!$B$2:$B$5=Form!A2) will check if the tasks are the same I hope I understood well what you intended to do :) [EDIT] Another try thanks to your comment (both task should be completed to appear) =IF(AND((LI!$C$2:$C$5="*")*(LI!$A$2:$A$5)*(LI!$B$2:$B$5=Form!A2),(DE!$C$2:$C$5="*")*(DE!$A$2:$A$5)*(DE!$B$2:$B$5=Form!A2))),MAX((LI!$C$2:$C$5="*")*(LI!$A$2:$A$5)*(LI!$B$2:$B$5=Form!A2),(DE!$C$2:$C$5="*")*(DE!$A$2:$A$5)*(DE!$B$2:$B$5=Form!A2)),"")
{ "language": "en", "url": "https://stackoverflow.com/questions/7501770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fetch parent and child comment at single query? I have this table structure I want to build query through which i can fetch all the rows using tst_id (which is called parent comment) and this tst_id should be matched with (if any) parent_tst_id (these are called child comments) .BUT the condition is parent comment(parent_tst_id=0) and child comment (tst_id) should be fetch at the same time and in same query. tst_id mem_id from_id testimonial added parent_tst_id 3500 822 822 and KdevInd 1316613536 3497 3499 329 329 Reply by me 1316613489 3497 3498 821 821 a Fan comme 1316613307 3497 3497 329 399 Profile COm 1316613243 0 please help, thanks A: You can self-join the table SELECT child.*, parent.* FROM comments AS child LEFT JOIN comments AS parent ON child.parent_tst_id = parent.tst_id WHERE child.tst_id = XXX A: Assuming tst_id available with you is always that of a parent comment, you can simply use the following query: SELECT * FROM comments WHERE tst_id = XXX OR parent_tst_id = XXX
{ "language": "en", "url": "https://stackoverflow.com/questions/7501773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle database is hanging infinitly in UPDATE queries suddenly my update queries are not executing . i can make select queries but when i try to update records the database hangs infinitly. i tried even from sql plus and nothing happens. A: Most likely you have another open uncommitted transaction for the same set of records, so they are locked for that transaction. And, most likely, you locked them, running the same UPDATE in another transaction. Just Commit/rollback your transactions, you should be fine. A: This query will show you who is blocking your update. Execute the update that hangs, then in another session run this: select s1.username || '@' || s1.machine || ' ( SID=' || s1.sid || ' ) is blocking ' || s2.username || '@' || s2.machine || ' ( SID=' || s2.sid || ' ) ' AS blocking_status from v$lock l1 join v$lock l2 on (l1.id1 = l2.id1 and l2.id2 = l2.id2) JOIN v$session s1 ON (s1.sid = l1.sid) JOIN v$session s2 ON (s2.sid = l2.sid) WHERE l1.BLOCK=1 and l2.request > 0; EDIT: To properly attribute this, it looks like I cribbed this a while back from ORAFAQ.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: C# Accessing Higher-Level Method from Nested Class I want to create a library class for an external control circuit which communicates via serial port. The circuit has built in functions to get/set various settings using serial communication (e.g. sending "SR,HC,01,1,\r" turns sensor 1 ON). There are ~100 functions sorted into the following categories: Sensor Settings, Output Settings, and Environment Settings. Here is what I tried. public class CircuitController { // Fields. private SerialPort controllerSerialPort; private SensorSettings sensorSettings; private OutputSettings outputSettings; private EnvironmentSettings environmentSettings; ... // Properties. // Properties to get sensorSettings, outputSettings, and environmentSettings. // Methods. public string SendReceive(string sendCommand) // Send command and receive response. { ... } // Nested classes. public class SensorSettings { // Fields. // The various sensor settings here. // Properties. // Properties to get/set the sensor settings. Note: Get/Set is done through calling one of the following methods. // Methods. public double GetSensorUnits(int sensorNumber) { ... string commandToSend = String.Format("HE,WL,1,{0}", sensorNumber); // Setup command string. string commandResponse = SendReceive(commandToSend); // Send command and receive response. ERROR here, cannot access higher level, non-static methods. // Logic to process commandResponse. ... } // Other methods to create, send, and process the circuit's sensor settings "functions". } public class OutputSettings { // Same logic as SensorSettings class. } public class EnvironmentSettings { // Same logic as SensorSettings class. } } I figured that this way there won't be 100 methods/properties crammed under the CircuitController class. I could use a get property to obtain the sensorSettings instance, for example, and then call the desired method/property: circuitControllerInstance.GetSensorSettingsProperty.GetSensorUnits(1);. I receive a compile error that I am trying to access SendReceive() from a nested class. Is there a way to do this? Thanks! A: A nested class does not "see" whatever is declared in its host. You should pass a host reference to any nested class, for instance, in the constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to rename "Options" menu in Symbian app? My Qt application for Symbian supports several languages and I've managed to translate everything, but the only thing remains unchanged is menu bar, that is named "Options", even when I change phone locale, the name for menu bar remains the same. Additionally, when I open menu, softkeys have names "Select" and "Cancel", although these names change when I change phone locale. So, my question is - is there a way to rename menu bar, and change softkeys when menu is opened without changing phone locale? EDIT: Alternatively, Symbian-native code, that allows to rename left soft key, would be fine. A: Normally the Options and Cancel names match the phone's locale. If you want to translate them into another language, here's how to change the right softkey at runtime in native Symbian: // Change the Exit softkey to Hide HBufC* hideText(CCoeEnv::Static()->AllocReadResourceLC(R_MYAPP_HIDE)); TInt pos(Cba()->PositionById(EAknSoftkeyExit)); Cba()->RemoveCommandFromStack(pos, EAknSoftkeyExit); Cba()->SetCommandL(pos, EPodOClockCmdHide, *hideText); CleanupStack::PopAndDestroy(hideText); Try EAknSoftkeyOptions to change the left softkey.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to using amq.topic to pub/sub messages in Apache Qpid I have a C++ publisher to send messages like this: Connection connection; connection.open("127.0.0.1", 5672); Session session = connection.createSession(); Message msg; msg.setData("TestAMsg"); msg.getDeliveryProperties().setRoutingKey("test.A"); session.messageTransfer(arg::content = message, arg::destination = "amq.topic"); msg.setData("TestBMsg"); msg.getDeliveryProperties().setRoutingKey("test.B"); session.messageTransfer(arg::content = message, arg::destination = "amq.topic"); And I have a Java subscriber like this: AMQConnectionFactory connectionFactory = new AMQConnectionFactory("amqp://guest:guest@myhost/test? brokerlist='tcp://127.0.0.1:5672'"); AMQConnection connection = (AMQConnection) connectionFactory.createConnection(); org.apache.qpid.jms.Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); AMQTopic destination = (AMQTopic) AMQDestination.createDestination("topic://amq.topic//exclusive='false'? bindingkey='Test.A'"); MessageConsumer messageAConsumer = session.createConsumer(destination); Message message_ = messageConsumer_.receive(); No messages received in above code. I am very confused how this will work? What is the right form of bingding URL for consumers? What am I missing? A: Your consumer specifies a binding key that is different than the routing key used by the producer. Your producer code: msg.getDeliveryProperties().setRoutingKey("test.A"); Your consumer code: AMQTopic destination = (AMQTopic) AMQDestination.createDestination("topic://amq.topic//exclusive='false'? bindingkey='Test.A'"); Notice the difference in case for the first character of each key. Your producer uses test.A and your consumer uses Test.A, and since the keys are case-sensitive they are considered completely different. That's why your producer won't get any messages. A: your binding key should be test.# or test.* the differencees between # and *, follow this link http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_MRG/2/html/Messaging_User_Guide/chap-Messaging_User_Guide-Exchanges.html#sect-Messaging_User_Guide-Exchange_Types-Topic_Exchange
{ "language": "en", "url": "https://stackoverflow.com/questions/7501783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Question with scipy.optimize I am a newbie and I need your help!! I have installed scipy on my Ubuntu. When I ran the code from scipy import optimize, special I get the following in terminal: can't read /var/mail/scipy.optimize and if I type python, and get >>> then type in from scipy import optimize then I ran code including scipy, optimize, I get the following: name 'scipy' is not defined A: from scipy import optimize, special on the shell prompt starts the from command, which is an email program. from scipy import optimize, special in Python will put the modules optimize and special in your namespace, but not scipy. Either use them unqualified or do import scipy instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom serialization/deserialization of specific objects The JSON-objects I need to deserialize have the following form: { "typeName": { "field1": "content1", "field2": "content2" ... } } Basically it means, that every object except of an array is contained in a wrapper object, where the field name is the type of the wrapped object. The type name is needed to create an instance of a specific subclass. I cannot change anything, but need to use this interface. I tried to write a custom converter, but I don't know how to distinguish the type information from a normal field name of the the wrapped object. Is it possible to solve that problem in any way? A: Your question is not very clear but I am assuming that your "typeNames" are not fixed. If so, you can deserialize into a dictionary using Json.NET, viz: public void DeserializeSomeStuff() { const string json = @"{""typeName"":{""field1"": ""content1"",""field2"": ""content2""}}"; var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(json); foreach (var kvp in obj) { Console.WriteLine("key={0}", kvp.Key); foreach (var kv in kvp.Value) { Console.WriteLine(" key={0} value={1}", kv.Key, kv.Value); } } // key=typeName // key=field1 value=content1 // key=field2 value=content2 }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: change the default selected option in a select via jquery I have a select list where one option is selected by default when the page loads. When a different option is selected, the html I view in Firebug does not change. I have a button that makes copies of this element, and would like the copies to have the same selected value as this one, but they all have the default value selected. How can I make the copies have the same selected values as the original? A: When you clone the element you should be able to set the cloned select's value to that of the original. E.g., var $select = $('#my-select'), $clone = $select.clone().val($select.val()); // I don't know where you really want the clone, just an example... $clone.insertAfter($select);
{ "language": "en", "url": "https://stackoverflow.com/questions/7501797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entry state showing different values when read directly and when read from a variable I am using entity framework 4.1 and code first in asp.net mvc. Just to test learn i wrote below code (A controller). public ActionResult Foo() { StringBuilder sb = new StringBuilder(); using (var db = new DemoDataBase1Context()) { //get person from db var person = db.Persons.FirstOrDefault(); //get entry var entry = db.Entry(person); //now change the person object person.Name = "Some New Value"; //print entity state //this is showing unchanged sb.Append("<br>State: " + entry.State); //this is showing changed sb.Append("<br>State: " + db.Entry(person).State); } return Content(sb.ToString()); } In above code you can see, when iam doing entry.State its saying unchanged, if i do db.Entry(person).State its saying changed. Can any one explain why?? A: If you have auto change detection enabled (which is the default in EF 4.1) Entry calls DetectChanges internally. The method starts probably similar to this: if (Configuration.AutoDetectChangesEnabled) ChangeTracker.DetectChanges(); //... In your second call of db.Entry(person) the object has changed and the DetectChanges method detects this by comparing a snapshot which was made when you loaded the entity with the current values. Since there is a difference the state changes from Unchanged to Modified. Also the State of the entry object you have created before the change will go to Modified because DbEntityEntry.State is likely a property which just propagates the State value of the inner _internalEntityEntry which remains the same instance in both DbEntityEntry objects. If you really want to save the former state of an entity you need to save the State itself, not only the entry object: var state = db.Entry(person).State; This is just an enum and won't change with a later call to Entry. You can compare this behaviour with the behaviour when you disable automatic change detection: db.Configuration.AutoDetectChangesEnabled = false; Both sb.Append... lines will receive the state Unchanged in that case because EF doesn't notice now anymore that one of your POCO properties has changed because DetectChanges isn't called. A: I think the Entry method gives you the state of the object as it is when you call Entry. I don't think it has anything to do with reading it from a variable versus calling it directly. When you get your reference to the first entry, your object isn't changed. The very next line you change it and call Entry again, at which point it is changed. If you store a reference to that then compare the two I am guessing they are different references: var person = db.Persons.FirstOrDefault(); // get reference to entry - unchanged at this point var entry1 = db.Entry(person); // make a change to the object person.Name = "Changed"; // get reference to entry - changed now var entry2 = db.Entry(person); // these will not be equal: probably false var equalOrNot = entry1 == entry2;
{ "language": "en", "url": "https://stackoverflow.com/questions/7501808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .Net Mvc: How to fire a error for Application_Error() manage them? I manage all app erros in my Application_Error() in Global.asax: protected void Application_Error(object sender, EventArgs e) { Exception exception = Server.GetLastError(); Log.LogException(exception); Response.Clear(); HttpException httpException = exception as HttpException; RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Erro"); if (httpException == null) { routeData.Values.Add("action", "Index"); } else //It's an Http Exception { switch (httpException.GetHttpCode()) { case 404: //Page not found routeData.Values.Add("action", "HttpError404"); break; case 500: //Server error routeData.Values.Add("action", "HttpError500"); break; // Here you can handle Views to other error codes. // I choose a General error template default: routeData.Values.Add("action", "General"); break; } } //Pass exception details to the target error View. routeData.Values.Add("error", exception); //Clear the error on server. Server.ClearError(); //Avoid IIS7 getting in the middle Response.TrySkipIisCustomErrors = true; //Call target Controller and pass the routeData. IController errorController = new ErroController(); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); } So, I have a Custom Authorize Attribute in my app that handle Unauthorized Request and I want to redirect to Application_Error() manipulate that instead. So, I do that: protected override void HandleUnauthorizedRequest(AuthorizationContext context) { if (context.HttpContext.Request.IsAuthenticated) { throw new HttpException(403, "Forbidden Access."); } else { base.HandleUnauthorizedRequest(context); } } In that way the Application_Error() is called, but it seems ugly to me to call a exception so directly, exist another way? What you think guys? A: Because the Unauthorized is not an error by default!!! Just add this method to global.asax protected void Application_EndRequest(object sender, EventArgs e) { if (Context.Response.StatusCode == 401 || Context.Response.StatusCode == 403) { // this is important, because the 401 is not an error by default!!! throw new HttpException(401, "You are not authorised"); } } A: You should not raise an exception inside of AuthorizeAttribute because that could lead to performance problems for code that is relying on AuthorizeAttribute to do an authorization check. AuthorizeAttribute is meant for checking whether or not Authorization is valid, not for taking action based on this information. That is why the original code doesn't throw an exception directly - it delegates the task to the HttpUnauthorizedResult class. Instead, you should create a custom handler (similar to the HttpUnauthorizedResult) to raise the exception. This will cleanly separate the logic of checking authorization and taking an action based on being unauthorized into 2 different classes. public class HttpForbiddenResult : HttpStatusCodeResult { public HttpForbiddenResult() : this(null) { } // Forbidden is equivalent to HTTP status 403, the status code for forbidden // access. Other code might intercept this and perform some special logic. For // example, the FormsAuthenticationModule looks for 401 responses and instead // redirects the user to the login page. public HttpForbiddenResult(string statusDescription) : base(HttpStatusCode.Forbidden, statusDescription) { } } And then in your custom AuthorizeAttribute, you just need to set the new handler in HandleUnauthorizedRequest. protected override void HandleUnauthorizedRequest(AuthorizationContext context) { if (context.HttpContext.Request.IsAuthenticated) { // Returns HTTP 403 - see comment in HttpForbiddenResult.cs. filterContext.Result = new HttpForbiddenResult("Forbidden Access."); } else { base.HandleUnauthorizedRequest(context); } } If you need to execute a different action than throwing an HttpException, you should subclass ActionResult and implement the action in the ExecuteResult method or use one of the built-in classes that inherits ActionResult. A: Your code is fine. By default if you call the base.HandleUnauthorizedRequest it throws a 401 exception which is intercepted by the forms authentication module and you get redirected to the login page (which might not be the desired behavior). So your approach is correct. Another possibility is to directly render the corresponding error view if you don't want to go through the Application_Error: protected override void HandleUnauthorizedRequest(AuthorizationContext context) { if (context.HttpContext.Request.IsAuthenticated) { context.Result = new ViewResult { ViewName = "~/Views/Shared/Forbidden.cshtml" }; } else { base.HandleUnauthorizedRequest(context); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7501810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When using Visual Studio custom templates with parameters, how can you get the actual root namespace? I am attempting to set up a template to create a unit test class with some basic structure and default using statements. I have created a VS2010 custom template to do this and almost everything works correctly. The issue I have encountered is that I am attempting to reference my project's base namespace in my using statements, and am unable to determine whether there is a parameter that will let me do this. An example of what I want, assuming my project is called MyProduct.Test: using NUnit.Framework; using MyProduct.Test.Base; namespace MyProduct.Test.BLL.Services.MyService { [TestFixture] public class MyServiceTest : TestBase { [SetUp] public void Setup() etc... I can generate everything except for using MyProduct.Test.Base with the template below: using NUnit.Framework; using $safeprojectname$.Base; namespace $rootnamespace$ { [TestFixture] public class $safeitemname$ : TestBase { [SetUp] public void Setup() etc... Unfortunately, $safeprojectname$ is only available for Project templates, not Item templates. This template results in the following output: using NUnit.Framework; using $safeprojectname$.Base; namespace MyProduct.Test.BLL.Services.MyService { [TestFixture] public class MyServiceTest : TestBase { [SetUp] public void Setup() etc... Is there any way for me to get the actual root namespace of my project (since $rootnamespace$ actually outputs the namespace for the file being added based on its location)? Note: Obviously I can set this up to work fine for one project, but it would be much more useful to have a template that works for all projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Determine if a value pulled from a file falls within a range So I have to write a code that determines whether a value pulled from a file falls within a specific range. double averageMaximumX = query.Average(t => double.Parse(t.XMax)); double varianceMaximumX = query.Sum(t => Math.Pow(double.Parse(t.XMax) - averageMaximumX, 2)); varianceMaximumX /= query.Count(); double stdDevMaximumX = Math.Sqrt(varianceMaximumX); double averageMinimumX = query.Average(t => double.Parse(t.XMin)); double varianceMinimumX = query.Sum(t => Math.Pow(double.Parse(t.XMin) - averageMinimumX, 2)); varianceMinimumX /= query.Count(); double stdDevMinimumX = Math.Sqrt(varianceMinimumX); double averageMaximumY = query.Average(t => double.Parse(t.YMax)); double varianceMaximumY = query.Sum(t => Math.Pow(double.Parse(t.YMax) - averageMaximumY, 2)); varianceMaximumY /= query.Count(); double stdDevMaximumY = Math.Sqrt(varianceMaximumY); double averageMinimumY = query.Average(t => double.Parse(t.YMin)); double varianceMinimumY = query.Sum(t => Math.Pow(double.Parse(t.YMin) - averageMinimumY, 2)); varianceMinimumY /= query.Count(); double stdDevMinimumY = Math.Sqrt(varianceMinimumY); double averageMaximumZ = query.Average(t => double.Parse(t.ZMax)); double varianceMaximumZ = query.Sum(t => Math.Pow(double.Parse(t.ZMax) - averageMaximumZ, 2)); varianceMaximumZ /= query.Count(); double stdDevMaximumZ = Math.Sqrt(varianceMaximumZ); double averageMinimumZ = query.Average(t => double.Parse(t.ZMin)); double varianceMinimumZ = query.Sum(t => Math.Pow(double.Parse(t.ZMin) - averageMinimumZ, 2)); varianceMinimumZ /= query.Count(); double stdDevMinimumZ = Math.Sqrt(varianceMinimumZ); var results = from item in query select new { XMaxResult = TryParseWithDefault(item.XMax, double.NaN) <= averageMaxX ? "pass" : "FAIL", XMinResult = TryParseWithDefault(item.XMin, double.NaN) >= averageMinX ? "pass" : "FAIL", YMaxResult = TryParseWithDefault(item.YMax, double.NaN) <= averageMaxY ? "pass" : "FAIL", YMinResult = TryParseWithDefault(item.YMin, double.NaN) >= averageMinY ? "pass" : "FAIL", ZMaxResult = TryParseWithDefault(item.ZMax, double.NaN) <= averageMaxZ ? "pass" : "FAIL", ZMinResult = TryParseWithDefault(item.ZMin, double.NaN) >= averageMinZ ? "pass" : "FAIL" }; A: Add and subtract the standard deviation to the average. Example XMaxResult = (TryParseWithDefault(item.XMax, double.NaN) <= averageMaxX + stdDevMaximumX && TryParseWithDefault(item.XMax, double.NaN) >= averageMaxX - stdDevMaximumX) ? "pass" : "FAIL"
{ "language": "en", "url": "https://stackoverflow.com/questions/7501820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Basic Express project is not (always) saved on disk I'm a Visual Basic newbie, doing a quick'n'dirty VB app in Visual Studio 2010 Express (under Windows 7, 64-bit). I save constantly. I have used the "Save All" option. I have rebuilt the app. Still, the project is not always written to disk when I save! (sometimes, my changes are written to disk, but I haven't found out yet the pattern). This is really bugging me, since quite a few times I saved my project, closed VB, and then I realized all my changes had not been saved. Is this some limitation of VB Express? I am using Visual C++ Express, too, and I had no such problems there. EDIT: For even more clarification -- I am not getting any errors, and I am not having problems with version control. What I do is: * *I make changes in source file. *I press save. *I rebuild, at a certain time hh:mm. *I look on the disk, and sometimes my source file's "last modified time" is not hh:mm, and if I open it, the changes from 1) are not in the source file. Sometimes it is there, but I can't say for sure when or why. The config on my machine is nothing special as far as I know, just normal Windows 7, 64-bit. I guess if it were some access rights related issue, the saving would never happen, instead of what I'm experiencing now. By now, I think one can safely assume that this is no Visual Studio Express issue (just installed it as it came, using it "out of the box").
{ "language": "en", "url": "https://stackoverflow.com/questions/7501826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASHX Files Compiled For Deployment? Looking at my web app, when it is all compiled and ready to be deployed, the folder I have has a bunch of .ASPX and .ASHX files. The ASHX files are of course some custom handlers I made for very specific instances where they could be image handlers or a something else where I didnt want a whole Page class life cycle. I noticed that .ASPX files have all the HTML content (all the tags) and the .aspx.cs files are compiled into .DLL files (as expected) which is just loaded up into IIS. That is great. But I also saw that the .ASHX files are just the way they are. All the code is in my .ASHX file and that is the exact same file in the folder deployed to my server. No compiled DLL or anything. So the question is this: Do the .ASHX files execute slower because it is somewhat of an interpreted file? I know I am probably wrong but there is nothing compiled it seems for .ASHX files and I originally used them for speed. Or is the code compiled once into memory by IIS and kept there for later use? Or is that maybe what the IsReusable bool is property is for? A: They're compiled, so performance won't be an issue. It is, however, possible to use a code-behind for .ashx files in the same way as .aspx files and suchlike. In your .ashx file: <%@ WebHandler Language="C#" CodeBehind="UserImageHandler.ashx.cs" Class="Namespace.UserImageHandler" %> and then in a code-behind: using System; using System.Web; // more here if you need them... namespace Namespace { public class UserImageHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { // etc. etc. } public bool IsReusable { get { return false; } } } } Doing it this way instead of inline can make life easier if you have lots of code. A: As I understand it, the ashx file is a location to request, which simply directs the request to the code behind ( which is compiled as everything else ). So yes, an ashx file is probably very slightly slower, the first time, as it is compiled on request. But the performance hit is minimal - a simple redirect to a code block.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Iterating through a foreach loop - only show 1 item rather than all I've setup a Google map that has several plotted markers, each one when clicked on has a little popup with info within. I'm using the following code to show the company name per plotted marker, but it's going through the foreach loop and showing ALL the company names within one popup. How can loop through and show one company name per plotted marker? I need it to show the first company in the list on the first marker, the second company in the list on the second marker and so on. // Setting the content of the InfoWindow infowindow.setContent(' <?php $pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order')); foreach($pages as $post) { setup_postdata($post); $fields = get_fields(); ?> <p><?php echo $fields->company_name; ?></p> <?php } wp_reset_query(); ?> '); A: Look at your code. what a mess! You would never have missed these obvious mistakes, if you would care to structure your code well! Don't write all your code on one line! Use best practice for code style! Don't put all that PHP code inside the javascript function. Instead, use a variable $contentMarkup, store everything in there and in the end echo this variable into the javascript code. <?php $contentMarkup = ''; //do all your stuff like $contentMarkup .= '<p>'; $contentMarkup .= $fields->companyName; $contentMarkup .= '</p>'; ?> infowindow.setContent('<?php echo $contentMarkup; ?>'); Regarding your actual question: If you want to generate more than one tooltip/window/younameit, they have to have unique identifiers so you can create one for each company. But to say more I'd need to know a bit more about what exactly you're trying to do. What information is available and from what source. A: show what you want based on if statement inside foreach loop
{ "language": "en", "url": "https://stackoverflow.com/questions/7501831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Couple of questions about asp.net MVC view model patterns I'm new to MVC. I have read this short bit detailing three ways of dealing with the view model in MVC: http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx The gist of it seems to me that: Method 1, pull an object out the database and use it as your view model. Quick and simple, but if you want data from multiple tables you're totally screwed (I can't think of a way around it without Method 2). Method 2, create a class that has references to multiple objects, and use this as your view model. This way you can access everything you need. The article says that when views become complicated it breaks down due to impedance mismatch between domain/view model objects... I don't understand what this means. Googling impedance mismatch returned a lot of stuff, the gist of it being that you're representing database stuff using objects and stuff doesn't map across cleanly, but you'd presumably have this problem even with Method 1. Not sure what I am missing. Also seems to me that creating a class for each View to get the data you want isn't ideal from a maintenance point of view, not sure if you have a choice. Method 3, I am still getting my head around it, but I don't quite understand why their checkbox example wouldn't work in method 2, if you added a bool addAdditional to your class that wasn't connected to the domain model. Method 3 seems to say rather than return the domain stuff directly, just pull out the properties you specifically need, which I think is nicer but is gonna be harder to maintain since you'll need some big constructors that do this.x = domain.x, this.y = domain.y etc. I don't understand the builder, specifically why the interface is used, but will keep working on it. Edit: I just realised this isn't really a question, my question is, is my thinking correct? A: The problem I've run into with #2 is that I have to do one of these two things: * *Include every single field on every single object on the form -- those that aren't going to be displayed need to be included but hidden. *Only include the specific fields I need but use AutoMapper or something similar to map these fields back onto the actual objects. So with #2 I see a mismatch between what I want to do and what I'm required to do. If we move on to #3, this mismatch is removed (from what I understand, briefly glanced at it). It also fixes the problem that a determined hacker could submit values like id fields or similar when using method #2 that unless I was very careful could be written to my data store. In other words, it is possible to update anything on any of the objects unless one is very careful. With method #3 you can use AutoMapper or similar to do the dirty work of mapping the custom object to the data store objects without worrying about the security issues/impedance exposed by method #2 (see comment for more details on security issues with #2). A: You're probably right about impedance mismatch being present in both Methods 1 and 2 - it shows up anywhere you're going between objects in code and DB objects with relational mapping. Jeff Atwood writes about it, and cites this article, which is a fantastic discussion of everything dealing with Object-Relational mapping, or "The Vietnam of Computer Science". What you'll pretty much end up doing is weighing the pros and cons of all these approaches and choose the one that sounds like it fits your needs the best, then later realizing you chose the wrong one. Or perhaps you're luckier than I am and can get it right the first go 'round. Either way, it's a hairy problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: WinAPI - avoid redraw of window I'm drawing into a WinAPI-Window by using the SetPixel()-Function. If I scale the window or lose focus (another window is on top) I lose the whole content that I draw into the window. I just used RECT rc; GetClientRect(hwnd, &rc); RedrawWindow(hwnd, &rc, NULL, RDW_NOERASE | RDW_NOFRAME | RDW_VALIDATE); which helped to avoid redrawing the content when I move the window but scaling and losing focus still removes the content. Does anyone have an idea what I missed? A: Draw it to a buffer/bitmap and then draw that to your window. A: When a window needs to be repainted it will be sent a WM_PAINT message. At this point you must redraw all of the window, or at least all parts of it which are contained within a clipping region. Windows does some buffering and automatic painting, specifically it will repaint parts of a window which are covered by other windows then uncovered. Once the window has been resized though, or (presumably) invalidated, you're on your own. As @daniel suggested, if painting is an intensive process and you don't want to do it every time a repaint is required, render your content into a bitmap (which in this case will be an off-screen buffer) and BitBlt (copy) it into the window as necessary. Grab yourself a copy of Charles Petzold's book "Programming Windows" for information about how you should go about painting. If you are writing a WinAPI app but have used SetPixel I'd recommend reading the entirety of the first few chapters to get an idea of how an old-school Windows programme should be structured. A: SetPixel is very slow, you cannot improve your program significantly. Create in-memory bitmap and draw it on the window. For example, you can do this using StretchDIBits function, which draws the whole memory area as bitmap to the window, instead of SetPixel. The most important StretchDIBits parameters are: CONST VOID *lpBits - memory array (pixels). You need to fill it in memory instead of SetPixel calls. CONST BITMAPINFO *lpBitsInfo - BITMAPINFO structure which must describe bitmap structure. For example, if lpBits has BGRW structure (4 bytes per pixel), BITMAPINFO must describe true color bitmap. A: You need to draw the content into memory and then draw it to the window when you got WM_PAINT message. There is no way to avoid using memory buffer because window device context does not save what you draw. A: Create a DIB surface and draw into it instead. Then redraw the bitmap when redrawing a window. You're trying to draw with a pre-Windows way in Windows. ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7501839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XML Serialize dynamic object I need to construct a set of dynamically created XML nodes from objects on the following format: <Root> <Name>My Name</Name> <DynamicValues> <DynamicValue1>Value 1</DynamicValue1> <DynamicValue2>Value 2</DynamicValue2> </DynamicValues> </Root> The name of the nodes within the DynamicValues-tag are not known in advance. My initial thought was that this should be possible using an Expando Object, e.g: [DataContract] public class Root { [DataMember] public string Name { get; set; } [DataMember] public dynamic DynamicValues { get; set; } } by initializing it with the values: var root = new Root { Name = "My Name", DynamicValues = new ExpandoObject() }; root.DynamicValues.DynamicValue1 = "Value 1"; root.DynamicValues.DynamicValue2 = "Value 2"; and then Xml-serialize it: string xmlString; var serializer = new DataContractSerializer(root.GetType()); using (var backing = new StringWriter()) using (var writer = new XmlTextWriter(backing)) { serializer.WriteObject(writer, root); xmlString = backing.ToString(); } However, when I run this, I get an SerializationException saying: "Type 'System.Dynamic.ExpandoObject' with data contract name 'ArrayOfKeyValueOfstringanyType:http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer." Any ideas how I can achieve this? A: [Serializable] public class DynamicSerializable : DynamicObject, ISerializable { private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>(); public override bool TrySetMember(SetMemberBinder binder, object value) { dictionary[binder.Name] = value; return true; } public void GetObjectData(SerializationInfo info, StreamingContext context) { foreach (var kvp in dictionary) { info.AddValue(kvp.Key, kvp.Value); } } } [KnownType(typeof(DynamicSerializable))] [DataContract] public class Root { [DataMember] public string Name { get; set; } [DataMember] public dynamic DynamicValues { get; set; } } Output: <Program.Root xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http:// schemas.datacontract.org/2004/07/"> <DynamicValues i:type="Program.DynamicSerializable"> <DynamicValue1 xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:st ring" xmlns="">Value 1</DynamicValue1> <DynamicValue2 xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:st ring" xmlns="">Value 2</DynamicValue2> </DynamicValues> <Name>My Name</Name> </Program.Root>
{ "language": "en", "url": "https://stackoverflow.com/questions/7501846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Can't access listbox.InvokeRequired Hy! I can't access listbox.InvokeRequired Code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Threading; namespace PrimeNumbers { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private delegate void AddListItem(string item); Thread t; bool interrupt; public MainWindow() { InitializeComponent(); } private void btss_Click(object sender, RoutedEventArgs e) { if (t == null) { t = new Thread(this.calculate); t.Start(); btss.Content = "Stop"; } else { t.Interrupt(); } } private void calculate() { int currval = 2; int devide = 2; while (!interrupt) { for (int i = 2; i < currval/2; i++) { if (2 % i != 0) { if ( lbPrimes.Items.Add(currval.ToString()); } } currval++; } } private void AddListBoxItem(string item) { if (this.lbPrimes.InvokeRequired) //Error: Expression to evaluate { } } } } Please help! A: InvokeRequired is a winforms thing. For WPF, you'll have to use Dispatcher. Check out this post that explains it all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: explanation of bit array implementation in C-FAQ I was reading the C-FAQ question no: 20.8 which basically deals with bit arrays: http://c-faq.com/misc/bitsets.html One of the macros defined looks something like: #define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT) Is this macro meant to calculate the num of elements(or slots) in the char array (each slot = 8 bits) ? I am not sure what this macro is doing, in particular what the purpose of "+CHAR_BIT -1/CHAR_BIT" is. Any clues will be appreciated! A: * *It is a way to round up. If nb is smaller than CHAR_BIT, you'll still need at least one character. A: Yes, it calculates how many chars are needed to hold the bits. The addition stuff is to make it round up. A: Remember the division is integer division: there's no "... and three eighths". Suppose you want to group into slots of size 6 (yeah ... I know CHAR_BIT is 8 or more) * *1 element: 1 slot: (1 + 6 - 1) / 6 == (6 / 6) == 1 *... *5 elements: 1 slot: (5 + 6 - 1) / 6 == (10/6) == 1 *6 elements: 1 slot: (6 + 6 - 1) / 6 == (11 / 6) == 1 *7 elements: 2 slots: (7 + 6 - 1) / 6 == (12 / 6) == 2 *...
{ "language": "en", "url": "https://stackoverflow.com/questions/7501852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to execute or call a method with jquery? I'm trying to execute a number of methods in sequence: var objMethods = [JqueryAjaxViaPageMethod, JqueryWebServiceZeroParams, JqueryWebServiceOneParam, JqueryWebServiceTwoParams, JqueryWebServiceObjectParam, JqueryWebServiceClassArray]; $.each(objMethods, executeMethod(this)); function executeMethod(methodname) { methodname(); alert("done"); } this does not work, however, singularly, this does: executeMethod(JqueryAjaxViaPageMethod); How do I execute the 'array' of methods? A: It depends on which scope(context) they are declared function executeMethod(methodname,context) { context = context || window; context[methodname](); alert("done"); } $.each(objMethods, function(){ executeMethod(this); }); A: if the methods were declared like this function JqueryAjaxViaPageMethod () { ... } Then you can simply call the method like this function executeMethod(methodname) { window[methodname](); alert("done"); } If the methods were declared as a part of an object var objMethods = { JqueryAjaxViaPageMethod : function () { ... }, ... }; Then you would call it like this function executeMethod(methodname) { objMethods[methodname](); alert("done"); } A: In $.each(objMethods, executeMethod(this)), this most likely refers to window. What you are doing is calling executeMethod and passing the return value as callback to $.each. I think you want: $.each(objMethods, function(index, method) { executeMethod(method); // of course you could just do `method()` here as well }); A: your each method is wrong i guess. it should be $.each(objMethods, function(i,l) { executeMethod(l); }); where i = index of the element l = element of the index i
{ "language": "en", "url": "https://stackoverflow.com/questions/7501862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: BitmapFactory.decodeResource returning null I can't seem to figure this out. I have 2 java classes with different characteristics, each calling BitmapFactory.decodeResource to get the same image resource, one returns the bitmap while the other returns null. Both classes are in the same package. Here is the class that works, it calls BitmapFactory.decodeResource which returns the bitmap. I've only included relevant code. package advoworks.test; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; public class MainScreen extends SurfaceView implements SurfaceHolder.Callback { private static final String TAG = MainScreen.class.getSimpleName(); public MainScreen(Context context) { super(context); Bitmap bitmap; bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.droid_1); //adding the callback (this) to the surface holder to intercept events; getHolder().addCallback(this); // make the GamePanel focusable so it can handle events setFocusable(true); } } Here is the class that doesn't work. BitmapFactory.decodeResource returns a NULL in debug. I've only included code i felt was relevant. package advoworks.test; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.util.Log; public class Segment { private int x; private int y; private Bitmap bitmap; public Segment(int x, int y) { Log.d(TAG, "Creating Segment"); try { this.bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.droid_1); } catch (Exception e) { Log.d(TAG,"Error is " + e); } this.x = x; this.y = y; Log.d(TAG, "Created Segment"); } } Any clue anyone? A: Check the resolution of your image, if its too big, the BitmapFactory.decodeResource will just return null (no exception) A: The getResources() is a Context class method and you are not using a context in your Segment class. How does it work. You should call getApplicationContext().getResources() You should pass the context to the Segment constructor. public Segment(Context context, int x, int y) { .... bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.droid_1); .... } A: make sure your image is not in drawable-v24 folder, move it to drawable folder. this worked for me. A: My solution is to create a drawable (I had no issues creating it), then convert it to a bitmap val drawable = context.getDrawable(context.resources, R.drawable.droid_1) val bitmap = drawable.toBitmap(width = 100, height = 100, config = null) You can also use drawable.width and drawable.height to have the same scale and resolution
{ "language": "en", "url": "https://stackoverflow.com/questions/7501863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Is there a way to specify the command line width in octave? I would like to use octave as a "calculator" in a python script. Currently I am running octave like so: octave -q --eval 'some code' and read the stdout to interpret the results. However, I am running into problems once matrices reach a certain width so that octave starts to output them with column numerations like so: ans = Columns 1 through 5: 6.6264e-01 2.6142e-01 9.2413e-01 1.6814e-01 6.3117e-01 Columns 6 and 7: 6.6392e-01 4.0483e-01 which makes the interpreting of the result a little harder. Is there a way to tell octave not to split up the printing of results? A: The split_long_rows () command should be able to change this behavior. From the documentation, Query or set the internal variable that controls whether rows of a matrix may be split when displayed to a terminal window
{ "language": "en", "url": "https://stackoverflow.com/questions/7501876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I dynamically change Header's DataGrid TextColumn? I'm trying to build a DataGrid layout where the first column's name will be dinamically changed. How can I do, into DataGridTextColumn's Header property, to change that? I've saw some examples than the Header property is connected into a StaticResource, but a StaticResource is a fixed value, and that's doesn't work for me, once what I need is several values. Example: *If a user select a RadioButton, filtering by hour, the header will be X *If filters by day, header will be Y *If Filters by month, header will be Z... Remembering, this is one of several examples than i would need to change. Thanks. A: This can be done easily with Databinding. The CodeBehind Way Create a property in the codebehind of your window to hold the string value; I will call mine TextProp. I will assume the elementname of your window is "Window" for this example. In the DataGridTextColumn tag, databind the Header attribute to that property. <DataGridTextColumn Header="{Binding TextProp, ElementName=Window}"/> The MVVM Way Do the same as above, except put the property on your viewmodel to which the datagrid is bound. Change the XAML to: <DataGridTextColumn Header="{Binding TextProp}"/> Then all you have to do is change that Property value in whatever way you choose. To get this to update the value when the property changes, you will need to implement INotifyPropertyChanged (Check at the bottom of that post).
{ "language": "en", "url": "https://stackoverflow.com/questions/7501878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to synchronize a content of animated gif with link which should lead to proper site according to displayed frame I am preparing some banners in GIFs. GIF will contain for instance 3 images, which will be displayed 10s each of them in neverending loop. example: * *images with logo stackoverflow.com - 20s *images with logo superuser.com - 20s *images with logo webmasters.stackexchange.com - 20s together in one gif. I am preparing this keeping in mind, that user can use it for instance on phpBB forums: [url=link_to_site][img]someaddress/imageWithThreeFrames.gif[/img][/url] The whole thing is that link_to_site should lead to proper site... if superuser.com frame is displayed, then link in somehow should lead to http://superuser.com, etc. I know that this is almost impossible in traditional way.. so please let me explain how I see it... gif is not traditional gif, but PHP script, which will be return normal gif and also save information on what time specific gif was requested. Is it possible to save a kind of fingerprint of user, which requested this PHP? Or this will be rather a fingerprint of forum? link_to_site could be a indirect link of another PHP script on my server, which will calculate which frame was displayed if link was clicked X second after generating gif. Does it have any chance of working? A: If you're using BBcode to display the .gif as you mentioned above, then unfortunately, there is no way of doing what you're asking. If you really wanted to make that work, you would have to use some sort of javascript code, which I don't think you can on a forum, at least not without special privileges or a mod of some sort. As for saving the fingerprint of the user, you won't be able to retrieve any date from the forum itself, but you should be able to get the users IP address with "$_SERVER['REMOTE_ADDR']" in your PHP script. A: I think I've found a solution! link_to_site will lead to PHP script, which will redirect to proper site according to TIME on server! * *hh:mm:01 - hh:mm:10 -> site 1 *hh:mm:21 - hh:mm:40 -> site 2 *hh:mm:41 - hh:mm:30 -> site 3 if gif will be requested in hh:mm:24, knowing average time of creating gif(in this case assume 1s) I can set duration of each frame like this: * *15s - (hh:mm:25-hh:mm:40] second image *20s - (hh:mm:41-hh:mm:00] third image *20s - (hh:mm:01-hh:mm:20] first image *5s - (hh:mm:21-hh:mm:24] second image and loop... so more or less on 10:22:48 (server time) everywhere should be visible this same, third frame :) What do you think about that? :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7501880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I increase the scope of a variable in JavaScript? I've got the following code: $('.task-list').each(function(list, response) { response = $('#' + this.id).sortable('toArray'); }); console.log(response); The error I'm getting is response is undefined. I tried adjusting line 2 to be var response but got the same error. I'm trying to build an array of data by looping over the items on the page and then submitting a single ajax response to the server to update it. A: You probably want $.map instead: var response = $('.task-list').map(function() { return $(this).sortable('toArray'); }); console.log(response) A: It's not very clear what you're trying to accomplish, as you're overriding the value of response during each iteration. This might be closer to what you're looking for: var response = []; $('.task-list').each(function() { response.push($(this).sortable('toArray')); }); // response will now be an array, where each item is another array from each .task-list console.log(response); A: Not sure if I have the right parameters for the each delegate, but this is how to get the scope outside: var response; $('.task-list').each(function(list) { response = $('#' + this.id).sortable('toArray'); }); console.log(response); A: Move (or rather, declare) the variable outside the function: var response; $('.task-list').each(function(list, response) { response = $('#' + this.id).sortable('toArray'); }); console.log(response); This second example is closer to what I think you want, but I'm not clear what data you're trying to collect. var response = []; $('.task-list').each(function() { response.push($('#' + this.id). <<some data from this element??>> }); console.log(response);
{ "language": "en", "url": "https://stackoverflow.com/questions/7501884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio 2010 "default-ing" custom build as it might be clear while looking at this posts title, I'm not quite sure what to google for. Hence I hope someone here can help me out. Recently I happened to begin using Qt. I don't want to use Qt creator, rather stick with Visual Studio. The problem is when I use the Meta Object Compiler within Visual Studio. So far I was just adding a custom build step for those header files which need to be moc-ed. But it is very annoying to add the command-line/etc each time I add a header file which needs to be moc-ed. So I was wondering if its possible to add an option ( like "MOC-Build" ) into the dropdown box where I usually selected "Custom Build" which does the job. I found ( tho not tested yet ) this msdn page http://blogs.msdn.com/b/msbuild/archive/2005/10/06/477064.aspx which explains how to add an option to the drop down box, but how can I provide a command-line/etc ? Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/7501885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to simulate or trigger a Machine Check Exception? I've setup the mcelog tool on my Linux server, and I'd like to verify that it's working properly but I'm not sure how to test it. Does anyone know of any ways to generate or trigger an exception event so I confirm that the hardware errors are logged correctly. A: mcelog includes a test suite with a tool called mce-inject, designed to do exactly this. The developer has a copy of the source on github. It seems to require Linux 2.6.31 or better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Closure compiler treats definitions inside closures as redefinitions I've been working with google closure, trying to get a large body of JavaScript to compile cleanly for minimization using the Google compiler. I came across a problem though: goog.provide('test'); goog.provide('test2'); /** * @constructor */ test = function () { this.x = 10; this.y = 13; }; (function () { /** * @constructor */ test2 = function () { this.x = 10; this.y = 13; }; })(); The former is fine. The latter generates a constant-redefinition error: JSC_CONSTANT_REASSIGNED_VALUE_ERROR. constant test2 assigned a value more than once at /home/hbrown/tmp/closure-test/foo.js line 16 : 10 BUILD FAILED: 1 error(s), 0 warning(s) Is there some way to coerce plovr/closure compiler to allow this construct? I've looked around and found nothing. Later: on a further point, why does closure/plovr consider test2 a constant? I suspect it has to do with plovr/closure's creation of a namespace for test2 when goog.provide is called. it would be nice to see the intermediate form that it is working with when it generates the error. A: I'm typing this as an answer even though it's just a guess, because comments are terrible for code. Have you tried something like this: test2 = (function () { /** * @constructor */ function inner_test2() { this.x = 10; this.y = 13; }; // ... return inner_test2; })(); I wouldn't suggest that that's a convenient refactoring, particularly if that anonymous function is big and complicated, but it'd be interesting (sort-of) to see what it is that's confusing the compiler. A: Depending on why you need the anonymous function, you might try replace the the anonymous function with a goog.scope http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html A: Declare test 2 outside the function closure, without assigning it: var test2; (function() { test2 = function(... I realize this isn't a Closure Compiler configuration change like you wanted, but it will both improve code readability and resolve Closure Compiler's objections. A little bit of what you get with Closure Compiler is really Google internal Javascript code guidelines, because of its history. So for example you can't use the with statement because that's against policy, even though you as a public user just want to minify your code, and may have a policy that allows for the with statement at your company. That said, I do think it's not the best practice to declare a global inside a function closure (even though it's legal Javascript). And it wouldn't be that hard to write a script that goes around looking for /(\w[\w\d-]+) = function/ and declaring it with var at the top of the offending files. And, it would probably result in all the files modified that way being easier to analyze by coders new to a given file. Your remaining option is to modify the open source Closure Compiler code so it warns instead of errors about this violation of Google JS policy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7501890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }