text
stringlengths
8
267k
meta
dict
Q: Get the value of a property from a Class in Form2, and that value have been set in Form1 in C# Here is the scenario. I want to set the value of Server in Class1, i am setting the value in Form1. Then get the value of Server in Class1 in Form2. Here is what i have. class Class1 { private string server; public string Server { get { return server; } set { server = value; } } } //Form1 where i want to set the value of server private void setBtn_Click_1(object sender, EventArgs e) { Class1 sample = new Class1(); sample.Server = serverTxt.Text; } //Form2 where i want to get the value of server that i've set in Form1 private void setBtn_Click_1(object sender, EventArgs e) { Class1 sample = new Class1(); string serVer = sample.Server; } I know i can't have a value of server because i declared a new instance of Class1. But is there any way that i can still get the value of Server in Form2 that i have set in Form1? Please spare with me, i am new in C#, thanks in advance guys :D A: There are number of alternatives but static instance of Class1 would be easier. In form1, declare/create static instance of Class1 class //Form1 where i want to set the value of server public static Class1 sample=new Class1(); private void setBtn_Click_1(object sender, EventArgs e) { sample.Server = serverTxt.Text; } and in Form2, //Form2 where i want to get the value of server that i've set in Form1 private void setBtn_Click_1(object sender, EventArgs e) { string serVer = Form1.sample.Server; } A: Not only you can't do that, but in your code after the execution of setBtn_Click_1 the object of type Class1 that you created is gone - this is because you only have a reference to it in the method, so when the method executes the reference is gone! A: You could send it in a constructor when creating the second form. Something like this then class Class1 { private string server; public string Server { get { return server; } set { server = value; } } } //form 1 private void setBtn_Click_1(object sender, EventArgs e) { Class1 sample = new Class1(); sample.Server = serverTxt.Text; prevForm = sample; } //form 2 private void setBtn_Click_1(object sender, EventArgs e) { Class1 sample = new Class1{ Server=prevForm.Server }; } For this you should keep the result or the reference to you first form somewhere so you can acces it later on A: one solution to this is to declare the server property in the Calss1 as static class Class1 { public static string Server { get; set; } } so that you can get its value between the two forms private void setBtn_Click_1(object sender, EventArgs e) { Class1.Server = serverTxt.Text; } private void setBtn_Click_1(object sender, EventArgs e) { string serVer = Class1.Server; } use this only if you if you have one Server for all the instances of Class1 A: You have to set the value of serverTxt.Text in Form1 to the Global variable(the simpliest way). Then just take the value of this global variable in Form2 A: You can send the relevant data in the Form2 constructor and initialize it from Form1 (pass the data when you initialize Form2 in Form1) [EDIT] You could also pass the information via a database that keeps that data or using an external file that both forms have access to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: listener for sd-card removal im trying to do something similar to this: android: how to listen to "sd card removed unexpectedly" but onReceive of the listener never gets called, when i dont have sdcard mounted or i remove the sdcard. Here is the code. public class MyClass1 extends Activity{ BroadcastReceiver mSDCardStateChangeListener = null; /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSDCardStateChangeListener = MyClass2.registerSDCardStateChangeListener(this); //some code which needs SDCard and throws unhandled exception if sdcard is not there } @Override protected void onDestroy () { MyClass2.unRegisterSDCardStateChangeListener(this, mSDCardStateChangeListener); super.onDestroy(); } //in MyClass2 public static BroadcastReceiver registerSDCardStateChangeListener(Activity act) { BroadcastReceiver mSDCardStateChangeListener = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent arg1) { String action = arg1.getAction(); if(action.equalsIgnoreCase(Intent.ACTION_MEDIA_REMOVED) || action.equalsIgnoreCase(Intent.ACTION_MEDIA_UNMOUNTED) || action.equalsIgnoreCase(Intent.ACTION_MEDIA_BAD_REMOVAL) || action.equalsIgnoreCase(Intent.ACTION_MEDIA_EJECT)) { //i never come here ;( //do something } } }; IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_REMOVED); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL); filter.addAction(Intent.ACTION_MEDIA_EJECT); filter.addDataScheme("file"); act.registerReceiver(mSDCardStateChangeListener, filter); return mSDCardStateChangeListener; } public static void unRegisterSDCardStateChangeListener(Activity act, BroadcastReceiver mSDCardStateChangeListener) { act.unregisterReceiver(mSDCardStateChangeListener); } i do not want to check if sdcard is present or not by if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) but use receiver instead. Any help is welcome.Thanks!. A: Ok I think the code I posted is meant for the action & not the state & works fine. from documentation: android.content.Intent.ACTION_MEDIA_REMOVED Broadcast Action: External media has been removed. The path to the mount point for the removed media is contained in the Intent.mData field. so what I was expecting(I was wrong, see the first two lines of the Question) that if i dont have SDCard(i.e. it has been removed earlier) and then I launch the app I would get the call implying that I dont have the SDCard (I know sounds stpid ;)) . The intent are actions(and not state).So If I remove the sdcard while the app is active I do receive the callback. Thanks for your time Vegas.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: "An error occurred while parsing EntityName" while Loading an XmlDocument I have written some code to parse RSS feeds for a ASP.NET C# application and it works fine for all RSS feeds that I have tried, until I tried Facebook. My code fails at the last line below... WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream rss = response.GetResponseStream(); XmlDocument xml = new XmlDocument(); xml.Load(rss); ...with the error "An error occurred while parsing EntityName. Line 12, position 53." It is hard to work out what is at thhat position of the XML file as the entire file is all in one line, but it is straight from Facebook and all characters appear to be encoded properly except possibly one character (♥). I don't particularly want to rewrite my RSS parser to use a different method. Any suggestions for how to bypass this error? Is there a way of turning off checking of the file? A: Look at the downloaded stream. It doesn't contain the RSS feed, but a HTML page with message about incompatible browser. That's because when downloading the URL like this, the user agent header is not set. If you do that, your code should work: var request = (HttpWebRequest)WebRequest.Create(url); request.UserAgent = "MyApplication"; var xml = new XmlDocument(); using (var response = request.GetResponse()) using (var rss = response.GetResponseStream()) { xml.Load(rss); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Integrating facebook chat API into iOS application I have an iOS application that already using some methods of Facebook Graph API, but i need to implement sending private message to friend by Facebook from my application. As i know, there is no way to sending private messages by Graph API, but it maybe possible by help Facebook Chat API. I already read documentation but it don't help me. If anybody has some kind of example or tutorial, how to implement Facebook Chat API in iOS application, how sending requests or something, it will be very helpfull. Thanks. A: Have a look at the XMPPFramework which has sections on both integrating the XMPP framework into iOS and implementing Facebook chat. This includes working sample projects. Facebook private messages are accessible, but seem to be read only. See this blog post. A: check this github project. they have integrated facebook api using xmppframework https://github.com/KanybekMomukeyev/FacebookChat
{ "language": "en", "url": "https://stackoverflow.com/questions/7552419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: reading flashvars problem for swfobject I have a flash swf of 1.2mb. am embeding it with swfobject using dynamic embeding . <script type="text/javascript"> var flashvars = {}; flashvars.campaignid = "12345678890"; var params = {}; params.allowscriptaccess = "always"; var attributes = {}; swfobject.embedSWF("soccer.swf", "myAlternativeContent", "550", "400", "10.0.0", false, flashvars, params, attributes); </script> am tring to read campaignid inside my document class ... the code is like public function Main() { loaderInfo.addEventListener(ProgressEvent.PROGRESS,update); loaderInfo.addEventListener(Event.COMPLETE,onLoadedMovie); } private function update(e:ProgressEvent):void { } private function onLoadedMovie(e:Event) { campId=this.root.loaderInfo.parameters["campaignid"]; } when i alert the value i got null when i use the same method in a small file it works.. can anyone help me? regards A: I got the answer by adding variable in the embed code. like this swfobject.embedSWF("soccer.swf?campaignid=1234556"", "myAlternativeContent", "550", "400", "10.0.0", false, flashvars, params, attributes); Thanks for the help :) A: Adam Harte's answer is correct, I think the problem lies somewhere within your AS3 code, the following especially confused me: public function Main() { loaderInfo.addEventListener(ProgressEvent.PROGRESS,update); loaderInfo.addEventListener(Event.COMPLETE,onLoadedMovie); } private function update(e:ProgressEvent):void { } private function onLoadedMovie(e:Event) { campId=this.root.loaderInfo.parameters["campaignid"]; } I've created a simple(and working) example of how your code should look: index.html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FlashVars</title> <meta name="language" content="en" /> <meta name="description" content="" /> <meta name="keywords" content="" /> <script src="js/swfobject.js" type="text/javascript"></script> <script type="text/javascript"> var flashvars = { campaignid: "12345678890" }; var params = { menu: "false", scale: "noScale", allowFullscreen: "true", allowScriptAccess: "always", bgcolor: "", wmode: "direct" }; var attributes = { id:"FlashVars" }; swfobject.embedSWF("FlashVars.swf", "altContent", "100%", "100%", "10.0.0", "expressInstall.swf", flashvars, params, attributes); </script> <style type="text/css"> html, body { height:100%; overflow:hidden; } body { margin:0; } </style> </head> <body> <div id="altContent"> <h1>FlashVars</h1> <p>Alternative content</p> <p> <a href="http://www.adobe.com/go/getflashplayer"> <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /> </a> </p> </div> </body> </html> Main.as(document class): package { import flash.display.Sprite; import flash.events.Event; import flash.text.TextField; import flash.text.TextFieldAutoSize; public class Main extends Sprite { public function Main():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); }// end function private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); if (loaderInfo.parameters.campaignid) { var textField:TextField = new TextField(); textField.autoSize = TextFieldAutoSize.LEFT; textField.text = loaderInfo.parameters.campaignid; addChild(textField); }// end if }// end function }// end class }// end package The following is an image of the example beening run in a browser: A: Maybe try getting the var after your Main class has been added to the stage. This will make sure everything is loaded and ready. Try something like this: public function Main() { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); var campId:String = this.root.loaderInfo.parameters["campaignid"]; trace('campId', campId); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Craeting QueueTable in OracleAQ 11.2.0 I have installed Oracle11.2.0(windows,32 bit) and tried to create a queuetable.. (I have granted all permissions for the jmsuser,AQ_ADMINISTRATOR_ROLE,AQ_USER_ROLE,DB_Access). when try to create a queuetable, Oracle gives following issue; oracle.jms.AQjmsException: ORA-01017: invalid username/password; logon denied ORA-06512: at "SYS.DBMS_AQADM", line 81 My sample code is as follows, createQueue(Session session) { AQQueueTableProperty qt_prop; AQQueueTable q_table; AQjmsDestinationProperty dest_prop; Queue queue; qt_prop = new AQQueueTableProperty("SYS.AQ$_JMS_BYTES_MESSAGE"); /* create a queue table */ q_table = ((AQjmsSession) session).createQueueTable("jmsuser", "test_queue_table", qt_prop); } Any idea? Thanks A: I solved this with following setting; ALTER SYSTEM GLOBAL_TOPIC_ENABLED = FALSE;
{ "language": "en", "url": "https://stackoverflow.com/questions/7552422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Authentication from multi source in Plone 4? How can I authenticate user from multiple source altogether ? For example local (ZODB or ldap), facebook and openid. Do I need to write a new PAS plugin ? Or We can achieve this the existed products ? A: There's no need to do anything. The authentication is already done from all sources at the same time. For ex, if you configure the ldap plugin, Plone's local users can still do login.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving and displaying data with NSUserDefaults I've saved some input from a UITextField using the following code: NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:myTextField.text forKey:@"myTextFieldKey"]; [defaults synchronize]; I'd like to display this saved text on a UILabel in another view controller. I tried this: myLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTextFieldKey"]; but nothing displays. Any help with this would be great. thanks. A: Well the loading and saving code is correct, so it looks like the problem is something else. Try this to debug: NSString *aValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTextFieldKey"]; NSLog(@"Value from standardUserDefaults: %@", aValue); NSLog(@"Label: %@", myLabel); myLabel.text = aValue; Now you will see if the value retriever from the NSUserDefaults is set and if the label is assinged. A: [[NSUserDefaults standardUserDefaults] setValue:myTextField.text forKey:@"myTextFieldKey"]; [[NSUserDefaults standardUserDefaults] synchronize]; After that use valueForKey not objectForKey: myLabel.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"myTextFieldKey"]; A: Try: myLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey:@"myTextFieldKey"]; A: Check that myTextField and myLabel aren't nil.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery event handling for HTML5 media events I want to listen to some of the events fired by HTML5 <audio> element. Some of event attributes for <audio> element are : onplaying, onprogress, onseeked, onseeking etc., I tried to listen to these events in jquery using conventional live() function like below, but it didn't work. $('audio#voice').live('progress', function(){ $('a#play').replaceWith("Playing...") }); I also tried with $('audio#voice').live('onprogress', function(){ $('a#play').replaceWith("Playing...") }); Is there any other way I can listen to these HTML5 media events in jQuery? A: You can only use live() and delegate() for events that bubble. The audio events probably don't so you can only bind() them on existing elements. A: I was trying to listen to onloadedmetadata, $('audio').bind('onloadedmetadata', function(){....});, but it was not working. At least for that I had to use 'loadedmetadata' in bind and then it worked. $('audio').bind('loadedmetadata', function(){....}); just a heads up for other events. A: This may also be helpful. I quote from the jQuery bind api doc: As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. A: live() didn't work. bind() worked. $('audio#voice').bind('progress', function(){ $('a#play').replaceWith("Playing...") });
{ "language": "en", "url": "https://stackoverflow.com/questions/7552426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to set up for multi-product Eclipse plug-in development? I have a set of plug-ins which need to support different Eclipse products. There is a core plug-in, which is product-independent, and an adaptation plug-in each for Product X, Product Y, etc. Deployment-wise, I'm thinking one feature for the core plug-in and one for each product, containing the adaptation plug-in and having a dependency to the core feature, so the core plug-in gets installed without the user having to select it. 1) Is there a better way of structuring the features? On the development side, I would like to be able to work with both the core and adaptation plug-ins within the same workspace, which as I understand it gives me two main options: a) working within each product using their respective installations as target platforms, or b) working in raw Eclipse with an explicitly defined target platform for each product. 2) What would be the best way to set up the development environment? If option a), can I use the same workspace for different products or would I need to set up separate workspaces? In other words, are different Eclipse products able to share a workspace as long as they're all based on the same (say) major version, eg 3.x? If option b), can Eclipse manage multiple simultaneous target platforms? In other words, can different plug-in projects within the same workspace be compiled against different target platforms during the same build? And if not, how could I automate switching between them so I wouldn't have to do that manually during a workspace build? Or indeed, am I missing something fundamental and is there a much better way of doing all this? A: The short answer is you can do it either way. You can have 1 workspace per product, and each workspace has the target platform of that product. At the moment, eclipse supports one target platform active per workspace, not per project though. Or you can have eclipse and the 3rd party plugins you need as your target platform, and simply work on all 3 products and the common plugin in one workspace. If your total source plugins is <20, this would probably be fine. For >20, eclipse supports Working Set which would hide the plugin you are not working on at the moment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get textbox helper to display valid HTML markup for HTML 4.01 strict? I have the following code in my page/view: @Html.TextBoxFor(x => x.Name, new { maxlength = "50", size = "50" }) The output generated is: <input id="Name" maxlength="50" name="Name" size="50" type="text" value="" /> I am using the following doctype: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> My page is not validating using the HTML validation tool because of the closing /> of the input element. How do I get the helper to create me an input element looking like: <input id="Name" maxlength="50" name="Name" size="50" type="text" value=""> A: I think that html generated by TextBoxFor helper is correct or at least can be used in any browser, but if you want to create your own helper method, you can add a extension method to the HtmlHelper. For example: public static class MyExtension { public static MvcHtmlString MyTextBox(this HtmlHelper html, string var1, string var2) { StringBuilder tag= new StringBuilder(); // create your tag and wrtite it in string buffer return MvcHtmlString.Create(tag.ToString()); } } A: Html generated by HTML helpers is XHTML valid and difference between HTML 4.01 strict and XHTML is that XHTML requires empty elements (as input, br, link, etc.) to close as in xml. I think that XHTML is more current standard and if there are no specific limitations you should use it, one of the reasons would be, that you HTML in such case can be used as XML (for XSLT processing and so on). A: Html helpers in asp.net mvc are just the helpers that simplify html generation process. They do not include anything magical behind them, just render html. If you want to have absolute control over generated html, you can create your own helpers or write the pure html in your view. There's nothing wrong about that. By the way, asp.net mvc 3 by default uses data-* attributes that are part of html5. If you absolutely do not wish to use them, turn off in web.config <appSettings> <add key="ClientValidationEnabled" value="false" /> <add key="UnobtrusiveJavaScriptEnabled" value="false" /> </appSettings>
{ "language": "en", "url": "https://stackoverflow.com/questions/7552428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inheritance in datacontracts I have a class say supplierAddress which comes from a webservice (it is a datacontact). I then have a second class myAddress which inherits from that class and has a few more constructors and metods. What I want to do is pass a myAddress back to the webservice. When I pass a cast down myAddress it throws seriazation errors, which makes sence as its a refrence object and the whole object is still being passed even if im casting down. Is it possible to clone just the base class of an object? Is what im trying to do possible/correct ? A: You should specify Known types for your base class. UPDATE: additional clarification. SOA (Service-Oriented Architecture) paradigm doesn't support such common features like polymorphism or method overloading. This behaviour based on very simple fact: you don't know which platform will consume your service. Its definitely possible to consume your service in platform or language that doesn't support such thing like inheritance or method overloading. That's why you should create your service functions with unique names and that's why you should explicitly stated what types you're going to pass instead of base class reference. When you specify known types this information would expose out of your service through metadata and every client could understand how to deal with your responses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QRegexp for (??) I'm fighting for some time to create a QRegExp for matching the string (??) (ie: an opening parantheses, two question marks and a closing parantheses and this should be a separate word, so before and after this can be spaces, tab, newline), The closest I came up with is QRegExp("\\b\\(\\?\\?\\)\\b"); but even this is not matching it... Can you help me with this? Thanks f. A: I don't know QRegexp, but \b only matches between alphanumeric and non-alphanumeric characters, so your regex would match (??) only if it was directly surrounded by alnums (like abc(??)123). So you need a different approach. Hoping QRegexp supports lookaround, you could use QRegExp("(?<=\\s|^)\\(\\?\\?\\)(?=\\s|$)"); so the regex checks if there is whitespace or start/end of string before/after (??). If that doesn't work, you'll have to match the whitespace explicitly: QRegExp("(?:\\s|^)\\(\\?\\?\\)(?:\\s|$)"); A: You could try with \B instead of \b: QRegExp("\\B\\(\\?\\?\\)\\B");
{ "language": "en", "url": "https://stackoverflow.com/questions/7552431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the equivalent for Hibenate.saveOrUpdate() in entity framework In entity framework you have to write a lot of code for saving or updating a single entity: using (DataContext context = new DataContext()) { context.Task.Attach(task); if (task.ID == 0) { context.ObjectStateManager.ChangeObjectState(task, System.Data.EntityState.Added); } else { context.ApplyOriginalValues(task.GetType().Name, task); } context.SaveChanges(); } in hibernate it is just saveOrUpdate() This is not about being lazy, it is about making it short and clean. A: There is no equivalent. You really have to write it like: using (DataContext context = new DataContext()) { context.Task.Attach(task); if (task.ID == 0) { context.ObjectStateManager.ChangeObjectState(task, System.Data.EntityState.Added); } else { context.ObjectStateManager.ChangeObjectState(task, System.Data.EntityState.Modified); } context.SaveChanges(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android - Translating language codes I get a response from a webservice that will return several language codes (ISO 639-2) as options. I now want to translate those into a human understandable word. For example: eng-> English ger -> German fre -> French How would you translate those words. Should I be using the strings.xml? But how will I get the Resource ID of those words? Thanks a lot A: You can convert 639-2 codes to 639-1 code using answer for this question and after you get a 2 letter code construct Locale object and use getDisplayLanguage method
{ "language": "en", "url": "https://stackoverflow.com/questions/7552436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding images side by side in pdf using itextsharp I am writing some data to the pdf using itextsharp. I am adding 2 images. I used this code: iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(System.Windows.Forms.Application.StartupPath + "\\t.jpg"); iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(System.Windows.Forms.Application.StartupPath + "\\teiasLogo.jpg"); pdfDocCreatePDF.Add(img); pdfDocCreatePDF.Add(img2); I want to see them like that : As a result I don't want new line ( \n ) between the images, I want spaces. How can I do that? Thanks.. A: You can produce that by using PdfPTable. Create a new table. Then you can assign your images to each cell (with border=0). A: PdfPTable resimtable = new PdfPTable(2); // two colmns create tabble resimtable.WidthPercentage = 100f;//table %100 width iTextSharp.text.Image imgsag = iTextSharp.text.Image.GetInstance(Application.StartupPath+"/sagkulak.jpg"); iTextSharp.text.Image imgsol = iTextSharp.text.Image.GetInstance(Application.StartupPath + "/sagkulak.jpg"); resimtable.AddCell(imgsag);//Table One colmns added first image resimtable.AddCell(imgsol);//Table two colmns added second image
{ "language": "en", "url": "https://stackoverflow.com/questions/7552438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ICustomTypeDescriptor and XAML Serialization I have a business object that can be edited via PropertyGrid. It contains list of labels (let's say strings for simplification). public class MyObject { // bunch of properties here, cut for readiness public LabelsList List {get;set;} // ... } List of labels is simple class inherited from List : public class LabelsList : List<T> {} For proper displaying of my object in property grid (by that i mean expandable editable list of labels too) i've implemented an ICustomTypeDescriptor for LabelsList, changing notably GetProperties() method : public PropertyDescriptorCollection GetProperties() { var props = new PropertyDescriptorCollection(null); for (var i = 0; i < this.Count; i++) { var descriptor = new LabelsListPropertyDescriptor(this, i); props.Add(descriptor); } return props; } Now the problem - when i use standard XAML serialization by calling XamlWriter.Save(this) on underlying type, it adds excessive LabelsList.LabelName tag inside resulting XAML : <wpfdl:LabelsList> *<wpfdl:LabelsList.Label1Name>* <wpfdl:Label LabelText="Label1Name"/> *</wpfdl:LabelsList.Label1Name>* ... </wpfdl:LabelsList> That actually disables following (MyObject)XamlReader.Parse(exportedXaml) call because label names can contain special characters. What is proper workaround to achieve both correct editing and serializing of objects? Thanks in advance. update Made unnecessary tags go away by changing respective PropertyDescriptor : public override bool ShouldSerializeValue(object component) { return false; } Resulting xaml is as follows (Primitive is name of my object custom type): <Primitive> <Primitive.Labels> <Label LabelText="text1" LabelPosition="position1" /> <Label LabelText="text2" LabelPosition="position2" /> </Primitive.Labels> </Primitive> That's pretty much it, but now <LabelsList> tags inside <Primitive.Labels> are missing : 'Collection property 'WPF_DrawingsTest.Primitive'.'Labels' is null.' Line number '1' and line position '96'. Still need to make this work. Maybe test project will help to see what i'm looking for : Test project, 100 kb, no viruses A: Refactored initial business object, serialization/deserialization now is done automatically and works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fixed positioning a list element on mouse over - jQuery I want to show overflow area in a list element when the mouse over. Normally element's height set to 200px and has an overflow area (not showing.). $('#extra_product ul li').live('mouseenter',function(){ var t = $(this); var sHeight = t.height(); t.css({"height":"auto","z-index":"999"}); var eHeight = t.height(); t.height( sHeight ).animate({ height: eHeight }); }); This is working but other elements are affecting and moving to next and down. I don't want to affect other elements, just animate to actual height and stay over the below element. Working demo URL : http://jsfiddle.net/D9P7V/ A: this is how i did it, it is not perfect yet you might need some css tweaks of course the trick i used: in javascript, clone the element to be shown, and append it to the body, so it cannot influence the other markup anymore, then position it over the element, and show it (animate it, anything you like) example started from your code: http://jsfiddle.net/D9P7V/4/ edit added solution without cloning another solution, if you want to leave the markup in, and don't clone, is setting the LI element on position: relative, and placing the div with extra about content absolute to that LI. example can be found here: http://jsfiddle.net/D9P7V/5/ end edit A: you should use position absolute ( inside a relative div) and then your bottom div wont be affected
{ "language": "en", "url": "https://stackoverflow.com/questions/7552441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the numerically best way to calculate the average what's the best way to calculate the average? With this question I want to know which algorithm for calculating the average is the best in a numerical sense. It should have the least rounding errors, should not be sensitive to over- or underflows and so on. Thank you. Additional information: incremental approaches preferred since the number of values may not fit into RAM (several parallel calculations on files larger than 4 GB). A: Sort the numbers in ascending order of magnitude. Sum them, low magnitude first. Divide by the count. A: I always use the following pseudocode: float mean=0.0; // could use doulbe int n=0; // could use long for each x in data: ++n; mean+=(x-mean)/n; I don't have formal proofs of its stability but you can see that we won't have problems with numerical overflow, assuming that the data values are well behaved. It's referred to in Knuth's The Art of Computer Programming A: Just to add one possible answer for further discussion: Incrementally calculate the average for each step: AVG_n = AVG_(n-1) * (n-1)/n + VALUE_n / n or pairwise combination AVG_(n_a + n_b) = (n_a * AVG_a + n_b * AVG_b) / (n_a + n_b) (I hope the formulas are clear enough) A: A very late post, but since I don't have enough reputation to comment, @Dave's method is the one used (as at December 2020) by the Gnu Scientific Library. Here is the code, extracted from mean_source.c: double FUNCTION (gsl_stats, mean) (const BASE data[], const size_t stride, const size_t size) { /* Compute the arithmetic mean of a dataset using the recurrence relation mean_(n) = mean(n-1) + (data[n] - mean(n-1))/(n+1) */ long double mean = 0; size_t i; for (i = 0; i < size; i++) { mean += (data[i * stride] - mean) / (i + 1); } return mean; } GSL uses the same algorithm to calculate the variance, which is, after all, just a mean of squared differences from a given number. A: If you want an O(N) algorithm, look at Kahan summation. A: You can have a look at http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.43.3535 (Nick Higham, "The accuracy of floating point summation", SIAM Journal of Scientific Computation, 1993). If I remember it correctly, compensated summation (Kahan summation) is good if all numbers are positive, as least as good as sorting them and adding them in ascending order (unless there are very very many numbers). The story is much more complicated if some numbers are positive and some are negative, so that you get cancellation. In that case, there is an argument for adding them in descending order.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: How to clear already sent notification message I've a working notifications part in my project. And I want to give user to disable notifications in app itself. Once user checks this option, I bring tile image and title to original state. Even this part works fine. Count can be removed by sending 0, But i didn't understand how to remove already sent message, esp: <wp:BackContent> </wp:BackContent> I tried sending empty message but it didn't work. Any idea, how to clear this message on tile? A: See this post on the AppHub: How do I reset a flipping Mango Tile after push notification? A: Here is the answer: Need to send "clear", if you want to clear anything. Very intuitive but not documented well. <wp:BackBackgroundImage Action=”Clear”></wp:BackBackgroundImage> <wp:BackTitle Action=”Clear”></wp:BackTitle> <wp:BackContent Action=”Clear”></wp:BackContent>
{ "language": "en", "url": "https://stackoverflow.com/questions/7552446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can multiple processes append to a file using fopen without any concurrency problems? I have a process opening a file in append mode. In this case it is a log file. Sample code: int main(int argc, char **argv) { FILE *f; f = fopen("log.txt", "a"); fprintf(f, "log entry line"); fclose(f); } Two questions: * *If I have multiple processes appending to the same file, will each log line appear distinctly or can they be interlaced as the processes context switch? *Will this write block if lots of processes require access to the file, therefore causing concurrency problems? I am considering either doing this in its simplest incarnation or using zeromq to pump log entries over pipes to a log collector. I did consider syslog but I don't really want any platform dependencies on the software. The default platform is Linux for this btw. A: The standard (for open/write, not fopen/fwrite) states that If the O_APPEND flag of the file status flags is set, the file offset shall be set to the end of the file prior to each write and no intervening file modification operation shall occur between changing the file offset and the write operation. For fprintf() to be used, you have to disable buffering on the file. A: You'll certainly have platform dependencies since Windows can't handle multiple processes appending to the same file. Regarding synchronization problems, I think that line-buffered output /should/ save you most of the time, i.e. more than 99.99% of short log lines should be intact according to my short shell-based test, but not every time. Explicit semantics are definitely preferable, and since you won't be able to write this hack system-independently anyway, I'd recommend a syslog approach. A: When your processes will be going to write something like: "Here's process #1" "Here's process #2" you will probably get something like: "Hehere's process #2re's process #1" You will need to synchronize them. A: EDIT to answer your questions explicitly: * *If I have multiple processes appending to the same file, will each log line appear distinctly or can they be interlaced as the processes context switch? Yes, each log line will appear intact because according to msdn/vs2010: "This function [that is, fwrite( )] locks the calling thread and is therefore thread-safe. For a non-locking version, see _fwrite_nolock." The same is implied on the GNU manpage: "— Function: size_t fwrite (const void *data, size_t size, size_t count, FILE *stream) This function writes up to count objects of size size from the array data, to the stream stream. The return value is normally count, if the call succeeds. Any other value indicates some sort of error, such as running out of space. — Function: size_t fwrite_unlocked (const void *data, size_t size, size_t count, FILE *stream) The fwrite_unlocked function is equivalent to the fwrite function except that it does not implicitly lock the stream. This function [i.e., fwrite_unlocked( )] is a GNU extension. " * *Will this write block if lots of processes require access to the file, therefore causing concurrency problems? Yes, by implication from question 1. A: I don't know about fopen and fprintf but you could open the file using O_APPEND. Then each write will go at the end of the file without a hitch (without getting mixed with another write). Actually looking in the standard: The file descriptor associated with the opened stream shall be allocated and opened as if by a call to open() with the following flags: a or ab O_WRONLY|O_CREAT|O_APPEND So I guess it's safe to fprintf from multiple processes as long as the file has been opened with a. A: Unless you do some sort of synchronization the log lines may overlap. So to answer number two, that depends on how you implement the locking and logging code. If you just lock, write to file and unlock, that may cause problems if you have lots of processes trying to access the file at the same time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Path.GetTempPath() unexpected symbol at the end of path I am trying to read Windows 2008 SP2 temp path using the code Path.GetTempPath(); and get unexpected result. Instead of C:\Users\Administrator\AppData\Local\Temp\ I get C:\Users\Administrator\AppData\Local\Temp\2\ Why I get "2" at the end of path? There is no such temp path on my machine. A: I've seen this when remotely connecting to a server that supports multiple sessions: each remote session, even for the same user, gets its own temp path. I assume this is to prevent temporary files from two sessions by the same user possibly interfering. I understand that setting "Use Temporary folders per session" in Terminal services configuration controls this behaviour. A: Path.GetTempPath() looks for the Temp folder using * *The path specified by the TMP environment variable. *The path specified by the TEMP environment variable. *The path specified by the USERPROFILE environment variable. *The Windows directory. You might want to check the environment variables to see if any of those have a "2" at the end by mistake.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: groovy sql framework Hi I want to design a class using Groovy Sql which I will be able to use in any of my future db related projects. At present I came up with the below class, which has separate functions for individual queries, I want to learn how can I make it generic! So that I just need to pass 1 query and some bind parameters (if not pass null) Please help me get a solution My code import java.sql.*; import java.util.List; import groovy.sql.Sql public class ProductInfo { ReadProperty prop def sql public ProductInfo() { prop=ReadProperty.getInstance("db") sql = Sql.newInstance("jdbc:oracle:thin:@"+prop.getProperty("hostname")+":"+prop.getProperty("port")+":"+prop.getProperty("service"), "asimonc", "asimon","oracle.jdbc.OracleDriver") } public List executeSelection(String query) { List result=new ArrayList() sql.eachRow(query) { String[] rows=new String[5] rows[0]=(String)it.id rows[1]=(String)it.name rows[2]=(String)it.description rows[3]=(String)it.active rows[4]=(String)it.release_date result.add(rows) } return result } public executeInsert(String query,Object[] paramValues) { sql.execute(query,[paramValues[0], paramValues[1],paramValues[2], paramValues[3], paramValues[4]]) } public executeUpdation(String query,Object[] paramValues) { sql.executeUpdate(query,[paramValues[1], paramValues[2],paramValues[4],paramValues[5], paramValues[0]]) } public int executeSelectMax(String query) { int max sql.eachRow(query) { max=it.max } if(max==null) return 0 else return max } } My oracle table CREATE TABLE PRODUCTINFO ( "ID" NUMBER NOT NULL ENABLE, "NAME" NVARCHAR2(200), "DESCRIPTION" NVARCHAR2(200), "ACTIVE" NVARCHAR2(2), "RELEASE_DATE" DATE, PRIMARY KEY ("ID") ) for finding out max id (selection) ProductInfo pinfo= new ProductInfo(); int max=pinfo.executeSelectMax("select max(id) as max from productinfo"); for updation Object[] paramValues={iid,name,desc,"A",date,active}; pinfo.executeUpdation("update productinfo set name=?, description=?, release_date=?, active=? where id=?",paramValues); for insertion Object[] paramValues={max+1,name,desc,"A",date}; pinfo.executeInsert("insert into productinfo(ID,NAME,DESCRIPTION,ACTIVE,RELEASE_DATE) values (?,?,?,?,?)",paramValues); for yet another selection List result=pinfo.executeSelection("select ID,NAME,DESCRIPTION,ACTIVE,RELEASE_DATE from productinfo where ACTIVE='A'"); A: How about: import groovy.sql.Sql public class ProductInfo { ReadProperty prop def sql public ProductInfo() { prop=ReadProperty.getInstance("db") sql = Sql.newInstance( "jdbc:oracle:thin:@"+prop.getProperty("hostname")+":"+prop.getProperty("port")+":"+prop.getProperty("service"), "asimonc", "asimon","oracle.jdbc.OracleDriver") } public List executeSelection(String query) { List result = [] sql.eachRow(query) { result << [ it.id, it.name, it.description, it.active, it.release_date ] } result } public void executeInsert( GString query ) { sql.execute( query ) } public void executeUpdation( GString query ) { sql.executeUpdate( query ) } public int executeSelectMax( String query ) { sql.firstRow(query)?.max ?: 0 } } Then, your update and insert examples become: update: pinfo.executeUpdation( "update productinfo set name=$name, description=$desc, release_date=$date, active=${'A'} where id=$iid" ) insert: pinfo.executeInsert( "insert into productinfo(ID,NAME,DESCRIPTION,ACTIVE,RELEASE_DATE) values (${max+1}, $name, $desc, ${'A'}, $date )" ) As you can see... a lot of your code is simply wrapping things that already exist in the groovy.sql.Sql class
{ "language": "en", "url": "https://stackoverflow.com/questions/7552457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Relational Database query MySQL I have modified the names of my Tables. The sportevents table is the main table and it should get its data from the tables: event_date, events, results, and members. Is there a way to do this. Please not i need to keep this structure. sportevents (link table) • id • event_id • date_id • result_id event_date • id • date events • id • eventname results • id • result members • id (the ID number of a person) userlogin • id • username • password I have managed to get it right without joins. The following: $query = "SELECT * FROM members, sportevents, dates, results, event, userlogin ". "WHERE userlogin.username = '$un' " . "AND sportevents.id = members.id " . "AND sportevents.event_id = event.id " . "AND sportevents.date_id = dates.id " . "AND sportevents.result_id = results.id"; $results = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($results)) { echo $row['eventname']; echo " - "; echo $row['year']; echo " - "; echo $row['result']; } Gives me this: Karoo Cycle - 2008 - 1h14mins A: I presume that you have member's data stored in to $_SESSION['member'] or smth. And i dont know exactly why you have separated tabes on event, event_date (there should be one in my perspective) and I guess that main_events is something like event's group/category. and you are missing MEMBER - EVENT link. add field 'member_id' to the events table. If that's what it is then it's something like that. $q = 'SELECT e.*, ed.year, r.result FROM events As e LEFT JOIN event_date As ed ON ed.id = e.id LEFT JOIN result As r ON r.id = e.id WHERE e.member_id = ' . $_SESSION['member']['id']; from that you get event id, event name, event year, result. "JohnSmith" you can get from $_SESSION['member']. If you decide not to use separate tables for event, event_date, result and use only one table with more fields u can do this without any LEFT JOINS just very simple SELECT query. A: First, you need to link event with a result. It depends on your domain model, but I'll assume you have only one result per event, so I'll add result_id to the events table. Also, you need to link members with events somehow, I'll use events_members member_id main_event_id table. With this vcersion you'll be able to have multiple members participate in multiple events. And finally, the query would be something like the following: select m.username, e.eventname, y.year, r.result from members m join events_members em on em.member_id = m.id join main_events me on em.main_event_id = me.id join event e on e.id = me.event_id join year y on y.id = me.year_id join result r on r.id = e.result_id where m.username = $username
{ "language": "en", "url": "https://stackoverflow.com/questions/7552459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Tomcat 6.0.24 Exception: javax.servlet.ServletException: Servlet execution threw an exception I am using java RestEasy Framwork for my application. I have some exception when I am trying to make a requet in tomcat server. Full stackTrace is: Sep 26, 2011 1:50:06 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet my-servlet threw exception java.lang.VerifyError: Cannot inherit from final class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632) at java.lang.ClassLoader.defineClass(ClassLoader.java:616) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2331) at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:976) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1451) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1329) at org.codehaus.jackson.jaxrs.MapperConfigurator.getDefaultMapper(MapperConfigurator.java:69) at org.codehaus.jackson.jaxrs.JacksonJsonProvider.locateMapper(JacksonJsonProvider.java:587) at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:404) at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:105) at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.read(GZIPDecodingInterceptor.java:61) at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:108) at org.jboss.resteasy.security.doseta.DigitalVerificationInterceptor.read(DigitalVerificationInterceptor.java:35) at org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl.proceed(MessageBodyReaderContextImpl.java:108) at org.jboss.resteasy.core.MessageBodyParameterInjector.inject(MessageBodyParameterInjector.java:168) at org.jboss.resteasy.core.MethodInjectorImpl.injectArguments(MethodInjectorImpl.java:114) at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:137) at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:255) at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:220) at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:209) at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:519) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:496) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:119) at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208) at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55) at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:662) What could be the problem? A: The exception says that your servlet/JSP extends some other class, and that class is marked as final. Anyway, if it is a servlet (and not a JSP) that should have been detected at compile time. A: MAke sure the spring-expressions.jar exists in your tomcat libs directory... i had to copy it there (apart from copying it to my WEB-INF/libs) but doing the copy of that jar to my tomcat directory solved my similar problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7552470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to keep a task alive after phone sleeps? my application needs to send a message to my server every 30 seconds or so. I understand I need to use AlarmManager using RTC_WAKEUP or ELAPSED_REALTIME_WAKEUP. now I don't understand two things: 1) If the AlarmManager wakes up the device, why do I need to aquire a WakeLock? 2) I saw an example for using AlarmManager with WakeLock. In this example, its setting the alarm to send a broadcast to a broadcast receiver which then acquires a static wake lock and then start an IntentService which runs a task. now, my question is, in my case, I need to follow this example entirely? why don't set the alarm to start a service instead?
{ "language": "en", "url": "https://stackoverflow.com/questions/7552471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: make function which returns the title of data structure There are several data types. data Book =BName| Author deriving (Eq,Show) data Video = VName deriving (Eq,Show) data CD =Cname | Auth | NOC deriving (Eq,Show) data Product = Product Book Video CD deriving (Eq,Show) make function getTitle which return the name(BName,CName or VName) of structure. For example getTitle (Book "name "noname") -> "name" getTitle (Vide "name") -> "name" and etc. Is it possible? Exist data type Book with fields title and author,Videocassete with field author, CDdisk with fields title,number of compositions and author. 1)create data type Product which can introduce this data types 2)make function getTitle which returns titles. 3)make function getTitles which returns all titles in the list of products(use function getTtitle) 4)make function bookAuthors which return books' authors in the list of products 5)make function lookupTitle::String->[Product]->Maybe Product which returns product with input name 6)make function lookupTitles::[String]->[Product]->[Product] which input params are the list of names and the list of products and for every name it gets products from list of products. Ignor names in the first list without products in the second list for them.Use function lookipTitle. That's all task. data Book = Book String String deriving(Eq,Show) data Video = Video String deriving(Eq,Show) data CDisk = CDisk String String Int deriving(Eq,Show) --titles class Titleable a where getTitle :: a ->String instance Titleable Book where getTitle (Book title _) = title instance Titleable Video where getTitle (Video title) = title instance Titleable CDisk where getTitle(CDisk title _ _) = title --get titles getTitles (x:xs) = [ getTitle x | x<-xs ] lookupTitle _ [] =Nothing lookupTitle::String->[Product]->Maybe Product lookupTitle a (x:xs) | getTitle x==a =Just x | otherwise = lookupTitle a (x:xs) lookupTitles::[String]->[Product]->[Product] lookupTitles (x:xs) (y:ys) = [y|x<-xs,y<-ys,x==lookupTitle y] but 1)I don't know how to make function bookAuthors(how can function find that the parameter is book-type?) 2)how to make Product type?I mean it is either Book or Video or CDisk 3)lookupTitle and lookupTitle are correct? A: Are you sure you want the data types like this? data Book = BName | Author deriving (Eq,Show) Means a Book is either a BName (book name?) or an Author? I suspect you want something similar to data Book = Book BName Author e.g. a book has a book name and an author If you want to capture the essence of "titleable" things you could use type classes. class Titleable a where getTitle :: a -> String instance Titleable Book where getTitle (Book title _) = title And write instances for your other types. A: From the task description, it sounds like the data type they are looking for is something like this: type Title = String type Author = String data Product = Book Title Author | Video Title | CD Title Integer Author deriving (Eq, Show) The function getTitle can then be implemented using pattern matching. getTitle (Book title _) = title getTitle (Video title) = title getTitle (CD title _ _) = title I'll leave the implementation of the remaining functions to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Does CompositionContainer.SatisfyImportsOnce reuse components? In a WCF service project, I have created a simple wrapper for MEF CompositionContainer to simplify its instantiation : internal class CompositionProxy { private static Lazy<CompositionContainer> m_lazyCC; static CompositionProxy() { m_lazyCC = new Lazy<CompositionContainer>(() => { var batch = new CompositionBatch(); var dc1 = new DirectoryCatalog( HttpContext.Current.Server.MapPath("~/bin") ); return new CompositionContainer(dc1); } ); } public static CompositionContainer DefaultContainer { get { return m_lazyCC.Value; } } } The idea is to have one CompositionContainer for the application lifetime, which search for export in the bin directory. Then, I set up some webservices, that requires to have on imported property : All of them are built like this : public class MyService: IMyService { public MyService() { CompositionProxy.DefaultContainer.SatisfyImportsOnce(this); } [Import] private IContext Context { get; set; } public void DoTheJob() { // Logic goes here } } Elsewhere, I have one class that match this export : [Export(typeof(IContext))] public class MyContext { public MyContext(){ Log("MyContext created"); } } In the constructor, I ask the composition container to populate the IContext Context property. This seems to work, in my service, I can see the Context property is correctly populated. However, I'm experiencing memory leaks, and my tracing show me the MyContext class is instantiated only once. Can you clarify if I'm misusing the composition framework ? * *I supposed it's a good idea to have one composition container for the application lifetime, was I wrong ? *the multiple calls to SatisfyImportsOnce seems to populate the target with the same unique instance. Is it true ? If true, how can I simply change my code to have a new instance each time the method is called ? *Any suggestion to improve my code ? A: I supposed it's a good idea to have one composition container for the application lifetime Yes, you are supposed to create one container for the application lifetime. the multiple calls to SatisfyImportsOnce seems to populate the target with the same unique instance. Is it true ? If true, how can I simply change my code to have a new instance each time the method is called ? You need [Import(RequiredCreationPolicy=CreationPolicy.NonShared)]. Any suggestion to improve my code ? If possible, do not expose the container as a global and litter your code with calls to it. That's the Service Locator pattern, which has some disadvantages when compared to Dependency Injection. Instead of your service trying to compose itself, just declare what it needs: [Export(typeof(IMyService))] public class MyService: IMyService { private readonly IContext context; public MyService( [Import(typeof(IContext), RequiredCreationPolicy=CreationPolicy.NonShared)] IContext context) { if (context == null) throw new ArgumentNullException("context"); this.context = context; } public void DoTheJob() { // Logic goes here } } In a WCF service, I think you should only need to call the container in your ServiceHostFactory implementation. I'm not really familiar with WCF though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Parse Apache config file, PHP config, FTP Server config I've just bough VPS account for testing and development. Is there a function of PHP to parse Apache config file, PHP config, FTP Server config, zone files, etc? Also a way to insert data into config file. I want to create a simple Control Panel to add ftp accounts and web account (with domain). If you have done it before - how did you do it? It would be quite challenging to learn Thanks. A: No, PHP has no functions to parse the config files of those programs - you'll have to write a custom parser for most of those formats. However, for php.ini you might be able to use PHP's ini functions. Most webhosting control panels either create the whole config file based on their database - i.e. they never read it but only (over)write it or they require you to include (apache and bind support that for example, for PHP you can use php_admin_value in the apache virtualhosts) their generated file - which is also never read by the tool. If you really want to create a tool that actually modifies existing files, don't forget that you cannot simply skip comments as nobody would want an application to rewrite his config file stripping all comments. A: You may be able to use the follow pear library to parse apache config files: http://pear.php.net/manual/en/package.configuration.config.avail-container.apache.php Parsing a php.ini file, depending on what you want to do, is probably best done with ini_get A: I'm not aware of such functions and I highly doubt they exist for the simple reason that there are just too many HTTP / FTP / SMTP / ... server implementations. Control panels like cPanel, WebMin and others usually do the heavy lifting for you and some even provide an API to automatize things from PHP. For the PHP configuration the following functions will probably do the trick: * *ini_get() *ini_set() *ini_get_all() *get_cfg_var() Bare in mind however that not all PHP configuration directives can be changed with ini_set().
{ "language": "en", "url": "https://stackoverflow.com/questions/7552485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Visual Studio 2008 Web application strange behaviour - Work only when debugging, Did not work when deployed I created a .NET 3.5 Web application using Visual Studio 2008. (It is basically a text field, a button and a label field. When the button is pressed, the label field will display the text field content) When I start debugging, everything work fine. However, when I deploy it on IIS 6, the button did not work at all. I have give the folder (which I created using IIS Virtual Directory) IUSR account access (Read, 'List Folder Contents' and 'Read & Execute' - When I click the 'Read & Execute' permission checkbox, the checkbox for 'List Folder Contents' also get checked.). Did I miss anything? A: i think while running you are using Visual studio self host, not IIS. Can you please go to project properties -> Web tab and configure with IIS and verify? If the problem with IIS please try the ASP.NET configuration is done for your IIS. You don't need to enable any permission for the directory. http://www.asp.net/learn/whitepapers/aspnet-and-iis6 Hope these helps.. A: Thanks Rafeeque, Actually I used another command to perform the deploy. reference: http://msdn.microsoft.com/en-us/library/ms229863%28v=vs.80%29.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7552496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC3 and User Model I'm using the generic membership class and have had my user sign up for workshops. I need to have something like this User 1 --Workshop 1 --Workshop 2 --Workshop 5 User 2 --Workshop 1 --Workshop 2 --Workshop 5 How do i get the user model? A: If I understand right you wnat ot extend the standard asp membership user. If I'm right, this answer should help you
{ "language": "en", "url": "https://stackoverflow.com/questions/7552497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if WCF(namedpipes) host is available? Hi, We have a winform application that is only to be executed as a singelton, If a second instance try to start this new instance will connect to the current and transmit parameters over namedpipes. The problem is that when starting the first instance there will be a try to connect to existing host. If the host is not existing(like in this case) an exception will be thrown. There is no problem to handle this exception but our developers is often using "Break on Exception" and that means that every time we startup the application the developer will get two(in this case) breaks about exception. Thay will have to hit F5 twice for every start. Is there any way to check if the service is available without throw exception if its not? BestRegards Edit1: [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr OpenFileMapping(uint dwDesiredAccess, bool bInheritHandle, string lpName); The following code says : Error 152 Cannot implicitly convert type 'System.IntPtr' to 'Orbit.Client.Main.Classes.Controllers.MyClientController.SafeFileMappingHandle' using (SafeFileMappingHandle fileMappingHandle = OpenFileMapping(FILE_MAP_READ, false, sharedMemoryName)) { A: If there is already a WCF server listening on the named pipe endpoint, there will be a shared memory object created, via which the server publishes the actual name of the pipe. See here for details of this. You can check for the existence of this shared memory object with code something like the following, which will not throw, just return false, if there is no server running already. (I've extracted this from code I already have working, and then edited it to do what you want - but without testing the edited version, so apologies if you have to fix up assembly/namespace refs etc to get it running.) public static class ServiceInstanceChecker { public static bool DoesAServerExistAlready(string hostName, string path) { return IsNetNamedPipeSharedMemoryMetaDataPublished(DeriveSharedMemoryName(hostName, path)); } private static string DeriveSharedMemoryName(string hostName, string path) { StringBuilder builder = new StringBuilder(); builder.Append(Uri.UriSchemeNetPipe); builder.Append("://"); builder.Append(hostName.ToUpperInvariant()); builder.Append(path); byte[] uriBytes = Encoding.UTF8.GetBytes(builder.ToString()); string encodedNameRoot; if (uriBytes.Length >= 0x80) { using (HashAlgorithm algorithm = new SHA1Managed()) { encodedNameRoot = ":H" + Convert.ToBase64String(algorithm.ComputeHash(uriBytes)); } } else { encodedNameRoot = ":E" + Convert.ToBase64String(uriBytes); } return Uri.UriSchemeNetPipe + encodedNameRoot; } private static bool IsNetNamePipeSharedMemoryMetaDataPublished(string sharedMemoryName) { const uint FILE_MAP_READ = 0x00000004; const int ERROR_FILE_NOT_FOUND = 2; using (SafeFileMappingHandle fileMappingHandle = OpenFileMapping(FILE_MAP_READ, false, sharedMemoryName)) { if (fileMappingHandle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); if (ERROR_FILE_NOT_FOUND == errorCode) return false; throw new Win32Exception(errorCode); // The name matched, but something went wrong opening it } return true; } } private class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeFileMappingHandle() : base(true) { } public SafeFileMappingHandle(IntPtr handle) : base(true) { base.SetHandle(handle); } protected override bool ReleaseHandle() { return CloseHandle(base.handle); } } } The host name and path you pass in are derived from the WCF service url. Hostname is either a specific hostname (e.g. localhost) or +, or *, depending on the setting for HostNameComparisonMode. EDIT: You'll also need a couple of P/Invoke declarations for the Win API functions: [DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] static extern SafeFileMappingHandle OpenFileMapping( uint dwDesiredAccess, bool inheritHandle, string name ); EDIT2: We need to tweak the return value of DeriveSharedMemoryName to specify the Local kernel namespace, assuming that your application is not run with elevated privileges. Change the last line of this function to read: return @"Local\" + Uri.UriSchemeNetPipe + encodedNameRoot; You also need to specify the hostname parameter correctly to match the hostNameComparisonMode setting used in your binding. As far as I recall, this defaults to StrongWildcard matching in the NetNamedPipeBinding, so you probably need to pass in "+" rather than "localhost". A: Can you try to list the named pipes available using String[] listOfPipes = System.IO.Directory.GetFiles(@"\.\pipe\"); and then determine is your named pipe is amongst them? A: My solution is the following : if (Debugger.IsAttached) return true; This will make sure that the code for checking the service is never runned during debugging. BestRegards
{ "language": "en", "url": "https://stackoverflow.com/questions/7552502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compile Android project in Continuous Integration System Hudson? I'm setting up a Continuous Integrations System with Hudson and it's just amazing. I got a SVN repository and integrated a post-commit hook that notifies Hudson when someone commits to the repository. This part is working splendid. The general idea is, that if the project fails, with unit-tests or anything else, it should tell the collaborator(i'm using a simple e-mail notifier atm). But if it successes I want it to compile the project and build either an unsigned or a signed .apk file. What's the easiest or smartest way to do this? I've read you can use a Shell Command to build the .apk but I can't seem to figure out how this works? Can anyone tell me how I can do this or should I go for another solution? Thanks in advance Finn Larsen A: There is a guide on the Jenkins wiki about building Android apps with Hudson or Jenkins, including building and running a test app, obtaining code coverage and static analysis stats. Essentially you can use the Ant support built-in to build your application. If you want to run automated tests, you can also use the Android Emulator Plugin. Since you're just starting out with Hudson, I would say now is a good time to upgrade to Jenkins. ;) A: As far as I remeber hudson supports ant's builds. And android apps can be built using ant use this link for more info about building android apps with ant. Be aware that you'll have to install Android SDK on your build agent. A: Android provides ant build script. So, you can make apk easily. * *install android-sdk in hudson server *install ant in hudson server ( ant version should be > 1.8 ) *in hudson, call cmd android update project -p <PATH to your project> *in hudson, call ant debug. debug target generates debug apk build
{ "language": "en", "url": "https://stackoverflow.com/questions/7552504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to select unique row according to last accessed time I want to get only distinct rows with their respective AnsId, like Qid: 01 have last AnsId: 01 I have following data structure, Qid Time AnsId 01 2011-09-26 12:55:10 01 02 2011-09-26 12:58:32 03 03 2011-09-26 12:59:05 02 01 2011-09-26 01:02:10 01 03 2011-09-26 01:30:10 01 02 2011-09-26 01:59:10 02 I have written following query but it returns all the rows: SELECT DISTINCT Qid, Time, AnsId FROM table ORDER BY Time DESC Then what is missing part in the select query? A: You could use row_number() to find the last answer per Qid: select * from ( select row_number() over (partition by Qid order by Time desc) as rn , * from YourTable ) as SubQueryAlias where rn = 1 The subquery is required because SQL Server doesn't allow row_number directly in a where. A: declare @T table ( Qid char(2), [Time] datetime, AnsId char(2) ) insert into @T values ('01', '2011-09-26 12:55:10', '01'), ('02', '2011-09-26 12:58:32', '03'), ('03', '2011-09-26 12:59:05', '02'), ('01', '2011-09-26 01:02:10', '01'), ('03', '2011-09-26 01:30:10', '01'), ('02', '2011-09-26 01:59:10', '02') select T.Qid, T.[Time], T.AnsId from ( select T.Qid, T.[Time], T.AnsId, row_number() over(partition by T.Qid order by T.[Time] desc) as rn from @T as T ) as T where T.rn = 1 order by T.[Time] desc Result: Qid Time AnsId ---- ----------------------- ----- 03 2011-09-26 12:59:05.000 02 02 2011-09-26 12:58:32.000 03 01 2011-09-26 12:55:10.000 01
{ "language": "en", "url": "https://stackoverflow.com/questions/7552506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JOOMLA : how to use multiple modules in the same webpage? my question sounds simple, but for me it isn't, i'm developing a joomla module and i want to use it multiple times and at different different position on each page load, can you just guide me? or gimme an example to accomplish this task? your help will be much appreciated. Googling didn't helped me this time A: Are you creating a module or a component? A component can only be displayed once per page and only in the area designated in the template by the tag. A module can be displayed several times per page and in several positions in your site. Simply go to the module manager, click on "New", fill in the details and the position and click on save. A: It depends a little on which version of Joomla you're using (you don't say?), but in Joomla 1.7: Administration Area -> Extensions -> Module Manager Select the module you want to duplicate (tickbox to the left), hit the 'Duplicate' button at the top. Now there are two separate modules, that use the same /DOCROOT/modules/mod_MODULENAME.php file for their logic. They can be assigned to separate module positions (or different pages), and given separate module parameters. You can have as many 'copies' of a module as you want. You can give them different names - but they'll all have the same 'Type' (this refers to the actual PHP file they use). You'll probably notice that the example modules that come with Joomla are often copies - especially of common modules like 'Custom HTML'. I've seen this confusion before, between a module (a small bunch of files you install that go in the /modules/ directory), and a module (the use of that bunch of files in the admin area, that appears on your site - it's actually a row in the Joomla database). When you first install a modules files, Joomla creates a single copy of the database row for you to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What are the specifications of Flex usable FLV videos? I have a server which streams FLV files to a Flex client. In this flex client, the video timeline advances incoherently, and no video can be seen on screen (only the sound can be heard). My FLV file has been generated using ffmpeg, which says (about this generated file) FFmpeg version 0.6, Copyright (c) 2000-2010 the FFmpeg developers built on Aug 8 2010 04:24:04 with gcc 4.3.2 configuration: --prefix=/home/marpada/ffmpegfull --enable-gpl --enable-version3 --enable-nonfree --disable-ffplay --disable-ffserver --enable-libmp3lame --enable-libfaac --enable-libvpx --enable-libfaad --enable-libvorbis --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libxvid --enable-libx264 --enable-libtheora --extra-ldflags=-static --extra-libs='-lvorbis -logg -lxvidcore -lx264 -lopencore-amrnb -lopencore-amrwb -lfaad -lfaac -lvpx -ltheora -lm -lpthread' --enable-small --enable-runtime-cpudetect libavutil 50.15. 1 / 50.15. 1 libavcodec 52.72. 2 / 52.72. 2 libavformat 52.64. 2 / 52.64. 2 libavdevice 52. 2. 0 / 52. 2. 0 libswscale 0.11. 0 / 0.11. 0 [flv @ 0x95c6aa0]Estimating duration from bitrate, this may be inaccurate Seems stream 0 codec frame rate differs from container frame rate: 1000.00 (1000/1) -> 25.00 (25/1) Input #0, flv, from '/appli/perigee_70ri/data/files/ged_bur%0/Imagettes/70ri/279/2/8/20_109021138o.70ri_FLV_preview_.flv': Metadata: hasMetadata : true hasVideo : true hasAudio : true duration : 589 lasttimestamp : 589 lastkeyframetimestamp: 589 width : 352 height : 288 videodatarate : 199 framerate : 25 audiodatarate : 125 audiosamplerate : 44100 audiosamplesize : 16 stereo : true filesize : 25058444 videosize : 15195503 audiosize : 9690850 datasize : 23027 metadatacreator : flvmeta 1.1-r202 audiocodecid : 2 videocodecid : 2 audiodelay : 0 canSeekToEnd : false hasCuePoints : false hasKeyframes : true Duration: 00:09:48.78, start: 0.000000, bitrate: 332 kb/s Stream #0.0: Video: flv, yuv420p, 352x288, 204 kb/s, 25 tbr, 1k tbn, 1k tbc Stream #0.1: Audio: mp3, 44100 Hz, 2 channels, s16, 128 kb/s At least one output file must be specified Which, as far as it seems to me, is OK. Furthermore, the video plays nice in VLC. A: Use H.264 for the video stream.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issues Resizing Image to fit on a printed page I am trying to print an image (from file) to a the printer using a PrintDocument. I am re-sizing my image so that it is scaled to be full page on the printout when I print this the image is cropped slightly. EDIT 2 I am using the margins to calculate the area to use: With printSettings.DefaultPageSettings Dim areaWidth As Single = .Bounds.Width - .Margins.Left - .Margins.Right Dim areaHeight As Single = .Bounds.Height - .Margins.Top - .Margins.Bottom End With The bounds of the page are 1169x827 (A4) and with the margins it is 1137x795. After resize my image size is 1092x682 and I am using the following code to draw it: e.Graphics.DrawImage(printBitmap, .Margins.Left, .Margins.Top) The annoying thing is that when I print to the PrintPreviewDialog it is scaled perfectly but when I print the exact same code to the actual printer it does not fit. EDIT 3 Full code can be found at this url Usage: Dim clsPrint As New clsPrinting With clsPrint .Landscape = True .SetMinimumMargins() If .ShowPrintDialog Then .Documentname = "Some doc name" .Preview = False 'When True shows ok .PrintImage("filename of a png file") End If End With A: Try using e.graphics.VisibleClipBounds for the printable page size in the PrintPage function. As Hans said, it's better not to resize your image before printing. A: You must work with MarginBounds: in C#: e.Graphics.DrawImage(your_image, e.MarginBounds); in C++/CLI: e->Graphics->DrawImage(your_image, e->MarginBounds); Note: If your image doesn't have the same aspect ratio you'll need to adjust. In this example width of the image exceeded the page width: Dim adjustment As Double = img.Width / e.MarginBounds.Width e.Graphics.DrawImage(img, New Rectangle(New Point(0, 0), New Point(img.Width / adjustment, img.Height / adjustment))) A: Sounds like you are wanting to print a page with a full bleed which most personal printers are not capable of. As one of the comments above mentions, factor in the margins to re-size the image to the appropriate size. A: I did not find a solution to this problem. I worked around it by using the printer margins when performing a print preview and ignoring the margins (start at 0,0 origin) when actually printing. I believe that this is possibly a bug in the printer driver? But I can't confirm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: c++ undefined reference class constructor I'm trying to use a library where one of the classes has a constructor like so: public: AreaNodeIndex(size_t cacheSize); I'm trying to instantiate an object of this class in my program like so: size_t const cacheSize = 50000; AreaNodeIndex areaNodeIndex(cacheSize); The linker gives me the following error: main.o: In function `main': make: Leaving directory `/home/Dev/_quicktest_build' main.cpp:(.text+0x212): undefined reference to osmscout::AreaNodeIndex::AreaNodeIndex(unsigned int) I think I have the necessary includes and I'm linking to the library with the compiler. For example, if I try to instantiate the object without any arguments on purpose I get this error: ../quicktest/main.cpp: In function ‘int main()’: ../quicktest/main.cpp:36: error: no matching function for call to ‘osmscout::AreaNodeIndex::AreaNodeIndex()’ /usr/local/include/osmscout/AreaNodeIndex.h:75: note: candidates are: osmscout::AreaNodeIndex::AreaNodeIndex(size_t) /usr/local/include/osmscout/AreaNodeIndex.h:33: note: osmscout::AreaNodeIndex::AreaNodeIndex(const osmscout::AreaNodeIndex&) So I can see the correct prototype (though here it says size_t and before it said unsigned int)... I can use other parts of the library fine. Here are the actual source files for the class in question: http://libosmscout.git.sourceforge.net/git/gitweb.cgi?p=libosmscout/libosmscout;a=blob;f=libosmscout/include/osmscout/AreaNodeIndex.h http://libosmscout.git.sourceforge.net/git/gitweb.cgi?p=libosmscout/libosmscout;a=blob;f=libosmscout/src/osmscout/AreaNodeIndex.cpp I'm pretty lost as to why this is happening. I feel like I've missed something obvious. *In response to the replies: The library gets size_t from "sys/types.h", so I don't think we're using different versions. The library was compiled on my system with the same compiler (g++, linux). Changing the 'const' specifier location has no effect. I am linking to the library. As I mentioned, I can use other classes from the library without issue. Here's the linking command: g++ -Wl,-O1 -Wl,-rpath,/home/QtSDK/Desktop/Qt/473/gcc/lib -o quicktest main.o -L/home/QtSDK/Desktop/Qt/473/gcc/lib -losmscout -lpthread The library name is 'osmscout'. kfl A: Possible cause of the problem in your case could be because of mixing of different size_t as mentioned by @rodrigo. For consistency maybe you can include <cstddef> where you are using size_t unless your project declares it own typedef for size_t. Please refer the link below. Please refer Does "std::size_t" make sense in C++? Hope this helps! A: The problem may be that the actual size_t typedef depends on several compiler options. Even in a full 32-bit machine, it can be unsigned int or unsigned long depending on the mood of the developers. So, if the library is compiled with typedef unsigned long size_t; and your program is with typedef unsigned int size_t; you have a problem. You can check it with objdump -t library | c++filt | grep AreaNodeIndex or something like that. A: You don't show us the most important part: the command line used to edit. You're probably not specifying the library to be linked in (options -l and -L, or you can specify the library as you would any other file). As for the linker specifying unsigned int, and the compiler size_t, that's just an artifact of the way the errors are displayed: the compiler will display the name of the typedef if that's what was used when declaring the function. The linker doesn't have this information, so displays the name of the actual type. A: It looks like you're not linking with the library correctly. A: can you try const size_t cacheSize = 50000; instead? [edit] Well, I'd guess that if that declaration is giving you an unsigned long than there is some compiler option that's being overlooked, and that size_t is defined as a typedef over an unsigned long, in your compiler, and not a type that would match up with what the library see's.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Routing in Kohana without changing URL How can I re-rout execution to another controller/action in Kohana PHP framework, w/o redirecting. A: if you using default routing you can do this: Request::factory('welcome/index2')->execute(); General case: $this->request ->controller('welcome') ->action('index2') ->execute(); Or look at Request->execute()
{ "language": "en", "url": "https://stackoverflow.com/questions/7552522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery ui autocomplete not showing result so i'm using jquery ui autocomplete instead of combobox to make it easier for my users to select hundreds of products from database. $(function() { $(".autocomplete").autocomplete({ source: function(request, response) { $.ajax({ 'url': "http://localhost/project/index.php/product/search_data/", 'data': { 'txt_product_name': $('#txt_product_name').val()}, 'dataType': "json", 'type': "POST", 'success': function(data){ response(data); } }) }, minLength: 2, focus: function( event, ui ) { $(".txt_product_id").val(ui.item.product_id); return false; }, select: function( event, ui ) { $( ".txt_product_id" ).val(ui.item.product_id); $( ".txt_product_code" ).val(ui.item.product_code); $( ".txt_product_name" ).val(ui.item.product_name); return false; } }).data("autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( "<a>" + item.product_code + "<br>" + item.product_name + "</a>" ) .appendTo(ul); }; }); firebug tells me that php successfully generates requested data, like below. [ {"product_id":"92","product_code":"TURE3052","product_name":"Choose Your Own Adventure"}, {"product_id":"89","product_code":"UMPS3447","product_name":"Goosebumps"}, {"product_id":"15","product_code":"ROSE7302","product_name":"The Name of the Rose"}, {"product_id":"34","product_code":"LIFE1226","product_name":"The Purpose Driven Life"} ] but somehow, the result does not show. any ideas? i copied parts of the codes from http://jqueryui.com/demos/autocomplete/#custom-data. i have tested the example and it worked. A: ok, i don't quite understand how and why, but it so happened that i need to create clones of the autocomplete textbox. for that purpose, i use live() in order for jquery to catch the event of new clone. i modify the above code to look like below: $(function() { $(".autocomplete").live('keyup.autocomplete', function() { $(".autocomplete").autocomplete({ source: function(request, response) { $.ajax({ 'url': "http://localhost/project/index.php/product/search_data/", 'data': { 'txt_product_name': $('#txt_product_name').val()}, 'dataType': "json", 'type': "POST", 'success': function(data){ response(data); } }) }, minLength: 2, focus: function( event, ui ) { $(".txt_product_id").val(ui.item.product_id); return false; }, select: function( event, ui ) { $( ".txt_product_id" ).val(ui.item.product_id); $( ".txt_product_code" ).val(ui.item.product_code); $( ".txt_product_name" ).val(ui.item.product_name); return false; } }).data("autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( "<a>" + item.product_code + "<br>" + item.product_name + "</a>" ) .appendTo(ul); }; }) }); as i say, i don't understand how and why, but the autocomplete result does show up. felt a little relieved. but since it is a must for me to understand my own work, i think i have to figure out the explanation. ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7552523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check date validation in iphone? I want to add date into my database .. and I want to add it in some specific format ..like dd/mm/yyyy how to check the validation for it? Like e-mail validation .. I want to check is it in specified format or not? how to do this ? A: 1) What is the input method for your date? * *If it is thru a UIDatePicker, you have nothing to do, the UIDatePicker will return a valid NSDate. I encourage you to manipulate NSDate objects and use UIDatePickers as date inputs especially to avoid the question of date validation. *If it is thru a text field, you can set the UITextField's inputView to an UIDatePicker and you won't have to bother about date validation either as you will obviously directly have a (parsed) NSDate that you can manipulate directly, being sure it is valid. Then in either case, use NSDateFormatter to convert your NSDate (entered by the user thru UIDatePicker) to an NSString (to insert in your database). 2) If you have a plain text entered by the user thru the keyboard, and can't or don't want to use a UIDatePicker (even as the inputView of your UITextField), you can convert your NSString to an NSDate thru an NSDateFormatter to check if it returns a non-nil NSDate (meaning it is a valid date). Note: You may also use NSRegularExpression or NSPredicate classes to check the format of your string... but you won't have the subtleties of NSDate validation (like checking that 31/02/2011 or 67/13/99 is invalid)
{ "language": "en", "url": "https://stackoverflow.com/questions/7552529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: A Simple Mac OS X Sound App I'm new to XCode and I have this project that I want to get on with. I want to create a small app for OS X that can get an audio input from whatever output and input device I set on System Preferences\Sound and output it to a specific then play that sound to a different device on System Preferences\Sound\Output. I'm fairly new to coding Mac apps (in XCode probably) and please don't take me for granted. If you need any more clarification about my question, please do so in the comments below so that I can provide you with more detail as to what I want to do. Also, please include a set of programming languages where I can achieve such a goal. (Eg; Objective-C, etc) A: Well if you're new to it you're best off sticking with Objective-C for the moment, it's the platform standard and whilst there's plenty of other resources every road leads back to Cocoa eventually. I'm making an assumption you've programmed before but if you need a ground up on Cocoa/Obj-C there's a good one on Cocoa Dev Central to get you up and running. A good starting point would be the CoreAudio overview which explains about how Cocoa handles sound in/out, and then there's an Apple coded example at CAPlaythrough, which is about 3 years out of date but should be a good starting point on looking at the way CoreAudio works and how to get the input to head to the output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Advanced Linq sorting C# I have an IQueryable that has a list of pages. I want to do: Pages.OrderByDescending(o => CalculateSort(o.page)); the method calculate sort is similar to that here is a plain english version: public int calculatesort(page p) { int rating = (from r in db.rating select r). sum(); int comments = //query database for comments; float timedecayfactor = math.exp(-page.totalhoursago); return sortscore = (rating +comments)* timedecayfactor; } when I run a code similar to the one above an error is thrown that the mothode calculatesort cannot be converted to sql. How can I do a conver the function above to be understood by sql so that I can use it to sort the pages? Is this not a good approach for large data? Is there another method used to sort sets of results other than dynamically at the database? I havent slept for days trying to fix this one :( A: The error occurs because LINQ cannot convert custom code/methods into SQL. It can convert only Expression<Func<>> objects into SQL. In your case, you have a complex logic to do while sorting, so it might make sense to do it using a Stored Procedure, if you want to do it in the DB Layer. Or load all the objects into main memory, and run the calculate sort method on the objects in memory EDIT : I don't have the code, so Describing in english is the best I can do : * *Have table with structure capable of temporarily storing all the current users data. *Have a calculated field in the Pages table that holds the value calculated from all the non-user specific fields *Write a stored procedure that uses values from these two sources (temp table and calc field) to actually do the sort. *Delete the temp table as the last part in the stored proc *You can read about stored procs here and here A: your code is nowhere near compiling so I'm guessing a lot here but I hope this gives an idea none the less. As several have posted you need to give Linq-2-Sql an expression tree. Using query syntax that's what happens (by compiler magic) from p in pages let rating = (from r in db.rating where r.PageId == p.PageId select r.Value).Sum() let comments = (from c in db.Comments where c.PageId == p.PageId select 1).Count() let timedecayfactor = Math.Exp(-(p.totalhoursago)) orderby (rating + comments)*timedecayfactor descending select p; I haven't actually tried this against a database, there's simply too many unknown based on your code, so there might still be stuff that can't be translated. A: Linq is expecting Calculatesort to return a "queryable" expression in order to generate its own SQL. In can embed your 'calculatesort' method in this lambda expression. (I replaced your variables with constants in order to compile in my environment) public static void ComplexSort(IQueryable<string> Pages) { Pages.OrderByDescending(p => { int rating = 99;//(from r in db.rating select r). sum(); int comments = 33;//query database for comments; double timedecayfactor = Math.Exp(88); return (rating + comments) * timedecayfactor; }); } Also, you can even try to run that in parallel (since .net 4.0) replacing the first line with Pages.AsParallel().OrderByDescending(p => A: var comments = db.comments.Where(...); Pages.OrderByDescending(p=>(db.rating.Sum(r=>r.rate) + comments.Count()) * Math.Exp(-p.totalhoursago)) A: Yes, counting previous answers: the LINQ to SQL doesn't know how to translate CalculateSort method. You should convert LINQ to SQL to ordinary LINQ to Object before using custom method. Try to use this in the way you call the CalculateSort by adding AsEnumerable: Pages.AsEnumerable().OrderByDescending(o => CalculateSort(o.page)); Then you're fine to use the OrderByDescending extension method. UPDATE: LINQ to SQL will always translate the query in the code into Expression tree. It's quite almost the same concept as AST of any programming language. These expression trees are further translated into SQL expression specific to SQL Server's SQL, because currently LINQ to SQL only supports SQL Server 2005 and 2008.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: renaming a temporary table into a physical one Can I do something like this? create table #tbl_tmp (col1 int) insert into #tbl_tmp select 3 exec sp_rename '#tbl_tmp','tbl_new' A: No. If you are running this from a database other than tempdb you get No item by the name of '#tbl_tmp' could be found in the current database .... Which is not surprising as all the data pages etc. are in the tempdb data files so you wouldn't be able to rename this to suddenly become a permanent table in an other database. If you are running this from tempdb you get An invalid parameter or option was specified for procedure 'sys.sp_rename'. If you do EXEC sp_helptext sp_rename and look at the definition the relevant bit of code disallowing this is -------------------------------------------------------------------------- -------------------- PHASE 32: Temporay Table Isssue ------------------- -------------------------------------------------------------------------- -- Disallow renaming object to or from a temp name (starts with #) if (@objtype = 'object' AND (substring(@newname,1,1) = N'#' OR substring(object_name(@objid),1,1) = N'#')) begin COMMIT TRANSACTION raiserror(15600,-1,-1, 'sys.sp_rename') return 1 end Why wouldn't you just create a permanent table in the first place then do the rename? A: As far as I know this is not possible outside of tempdb. Instead of renaming the table, you can create a new one from the temporary one. Untested: SELECT * INTO tbl_new FROM #tbl_tmp A: The answer is Yes. You can implement something like it but in a workaround way. Try the following approach, a lil bit old school but bypasses the restriction. I tested it myself as well /* Create an empty temporary staging table **/ use aw_08r2 go -- create temporary table select * into #temp from person.address -- select data from temporary staging table select * from #temp -- convert the temporary table and save as physical table in tempdb select * into tempdb.dbo.test from #temp -- save a copy of the physical table from tempdb in aw_08r2 select * into person.test from tempdb.dbo.test -- select data from physical table select * from #temp select * from tempdb.dbo.test select * from person.test -- drop temporary table and physical table from tempdb drop table #temp drop table tempdb.dbo.test go
{ "language": "en", "url": "https://stackoverflow.com/questions/7552550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: no overload for matches delegate 'system.eventhandler' As I'm pretty new to C#, I struggle with the following piece of code. When I click to button 'knop', the method 'klik' has to be executed. The method has to draw the Bitmap 'b', generated by 'DrawMandel' on the form. But I constantly get the error 'no overload for matches delegate 'system.eventhandler'. using System; using System.Windows.Forms; using System.Drawing; class Mandelbrot : Form { public Bitmap b; public Mandelbrot() { Button knop; knop = new Button(); knop.Location = new Point(370, 15); knop.Size = new Size(50, 30); knop.Text = "OK"; this.Text = "Mandelbrot 1.0"; this.ClientSize = new Size(800, 800); knop.Click += this.klik; this.Controls.Add(knop); } public void klik(PaintEventArgs pea, EventArgs e) { Bitmap c = this.DrawMandel(); Graphics gr = pea.Graphics; gr.DrawImage(b, 150, 200); } public Bitmap DrawMandel() { //function that creates the bitmap return b; } static void Main() { Application.Run(new Mandelbrot()); } } A: Yes there is a problem with Click event handler (klik) - First argument must be an object type and second must be EventArgs. public void klik(object sender, EventArgs e) { // } If you want to paint on a form or control then use CreateGraphics method. public void klik(object sender, EventArgs e) { Bitmap c = this.DrawMandel(); Graphics gr = CreateGraphics(); // Graphics gr=(sender as Button).CreateGraphics(); gr.DrawImage(b, 150, 200); } A: You need to change public void klik(PaintEventArgs pea, EventArgs e) to public void klik(object sender, System.EventArgs e) because there is no Click event handler with parameters PaintEventArgs pea, EventArgs e. A: You need to wrap button click handler to match the pattern public void klik(object sender, EventArgs e) A: Change the klik method as follows: public void klik(object pea, EventArgs e) { Bitmap c = this.DrawMandel(); Button btn = pea as Button; Graphics gr = btn.CreateGraphics(); gr.DrawImage(b, 150, 200); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Excel interop - Problem with recalculating the specific range Here's the current code I have got private void recalculateRRange(Excel.Range UsedRange) { Excel.Range currentRRange = null, firstRRange = null; currentRRange = (Excel.Range)UsedRange.Find("#HERE#", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing); while (currentRRange != null) { if (firstRRange == null) { firstRRange = currentRRange; } else if (currentRRange.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing) == firstRRange.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing)) { break; } //force current range to recalculate currentRRange.Calculate(); currentRRange = (Excel.Range)UsedRange.FindNext(currentRRange); } } The above method is used to find the cells that marked as #HERE# and to force this cell to recalculate so we can get the updated results. I managed to get this code working a day ago but somehow it's not working now. I guess that code is somewhat buggy anyway as I have been able to capture the exception just one time. I wonder if there's any better way to implement it? Exception captured: Exception from HRESULT: 0x800AC472 at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData) at Microsoft.Office.Interop.Excel.Range.Calculate() I don't know whether or not it meant something. My best guess is that probably something prevents currentRRange from calling Calculate(). A: The error you get means VBA_E_IGNORE which in turn means that something/someone is running/interacting on that sheet... this could be a user and/or some complex calculation. You should set Visible = false on the Excel application object and wait a little while after selecting the Range and retry the Calculate call when you receive this error... Another point: you should avoid accessing the Excel application object from multiple threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: change background of textview for listview item get focused i have this listview each listview item has a textview that have background , i want to change the background of the textview of listview item get focused . A: You should use Selector. Edit: Use selector drawable as a background for ListView elements, or specify a android:listSelector for a ListView A: you have change background color in onfocusChangeListener. Try with following code, livView.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { TextView tv=(TextView)v.findViewById(R.id.yourId); if(hasFocus){ tv.setBackgroundColor(bg_color); } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7552565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CPPFlags in config.mk In Arch Linux PKGBUILD for surf browser, there is: sed -i 's/CPPFLAGS =/CPPFLAGS +=/g' config.mk sed -i 's/CFLAGS =/CFLAGS +=/g' config.mk sed -i 's/LDFLAGS =/LDFLAGS +=/g' config.mk Why must the flags be changed from CPPFLAGS = -DVERSION=\"${VERSION}\" to CPPFLAGS += -DVERSION=\"${VERSION}\" I've looked into google, but don't see anything there about this. Can someone please explain and tell me where to read more about these flags? A: I did quite a lot of googling and found that this pattern (Surf's is here) seems fairly common in Arch Linux PKGBUILD files. Another example was in DWM's PKGBUILD. Obviously it is patching the config.mk file so that when make is called, the values are appended to the flags instead of overriding the flags (which must already be set elsewhere). So there must be existing settings that need to be retained. This seems to just be done by default by the package builders so it was hard to find the reason. Looking further I found this bug report relating to DWM's config.mk file, where the author notes that a version of that file was overriding flags set in makepkg.conf which is the main configuration file for makepkg, which allows tuning compilation settings per machine. This seems like a reasonable explanation for what you found. From that page, a default value for CFLAGS would be something like this: CFLAGS="-march=x86-64 -mtune=generic -O2 -pipe" So the patched config.mk file would result in the following when building the package: CFLAGS="-march=x86-64 -mtune=generic -O2 -pipe -std=c99 -pedantic -Wall -Os -I. ....."
{ "language": "en", "url": "https://stackoverflow.com/questions/7552566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove QLayoutItem from a Layout, but still use it later on? Here is the environment first: I have a self defined "Property Editor" which is a QGroupBox (derives from QWidget) Currently I have a class let's call it "Holder", which has a reference to two of the Property Editors. Now I have multiple "Holder" classes and one vertical QVBoxLayout (called Sidebar). In this layout I want both of the Property Editors of the currently selected Holder class to be displayed. And there is the issue: When the user selects another holder class, I want the Property Editors of the previously selected Holder class to disappear, and add the Property Editors of the new selected Holder class. Selecting another Holder class works once. But when I select the first Holder class again, The editors don't seem to change. Why? Does "takeAt(..)" destroy the reference in the holder class? How can I get the desired behavior? Here is the code, thanks in advance: void App::setSelection(Holder * holder){ if(m_currentlySelected == holder) return; m_viewer->sideBarRemoveAt(0); m_viewer->sideBarInsertAt(0, holder->firstPropEditor); m_viewer->sideBarRemoveAt(1); m_viewer->sideBarInsertAt(1, holder->secondPropEditor); m_currentlySelected = holder; } void QtViewer::sideBarRemoveAt(int i){ m_sideBar->m_layout->takeAt(i); } void QtViewer::sideBarInsertAt(int i, QWidget * widget){ m_sideBar->m_layout->insertWidget(i, widget); } A: QLayout::takeAt() doesn't remove the widget of the QLayoutItem from its parent widget. The only reason it may seem to work the first time is probably because the other widgets were above (z-index wise) the first ones. Rather than playing with the layout, you could * *just hide/show your 2 PropertyEditor whenever the holder changes, hidden items don't generate holes in the layout, the next visible item is displayed as if the hidden items were not part of the layout, or *use a QStackedWidget to stack all the PropertyEditor at the same place and select which one is displayed (with QStackedWidget::setCurrentIndex()). A: Does "takeAt(..)" destroy the reference in the holder class? No, this method removes the QLayoutItem from the layout. See reference page for takeAt. This class doesn't release the layout item (it is your responsibility to do). But when I select the first Holder class again, The editors don't seem to change. Why? I am not quite clear what you are trying to achieve (not enough code in your example), but if you are trying to change the layout using QLayoutItem's, then it is the simplest to create new layout and add items you want to display to it. Or simply, remove all items from the layout, and add the items that should be visible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem importing wx with PyDev - undefined variable import I am getting errors like Undefined variable from import: BOLD while I do: import wx print(wx.BOLD) I looked at wx module initialization and it does something like from wx._core import * del wx import wx._core I am not sure why it does this trick, but it's clear that this makes PyDev go insane. What is the proper way of importing wx if you want to use wx.BOLD or other constants and not have PyDev complain about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are those java threads starting with "pool"? I have a problem with a Tomcat server that is unable to shutdown gracefully. I have taken a thread dump after I issued the shutdown command, and it looks like this: http://pastebin.com/7SW4wZN9 The thread which I believe is the "suspect" that does not allow the VM to shut down is the one named "pool-4-thread-1". The rest of them are either daemon threads or internal VM threads. While trying to find out what this thread is for, I noticed that there are other java programs out there that create threads with similar names (For example, JVisualVM creates such threads). So I'm wondering if someone else knows what this thread is and how it can be created. A: These threads are probably created by an ExecutorService that you created in your code somewhere (directly or indirectly through a library) and that needs to be shutdown (for example in a ServletContextListener).
{ "language": "en", "url": "https://stackoverflow.com/questions/7552570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Select options in sencha touch is not working for android I have an application where i am using sencha touch JS API for UI rendering. The UI works fine in chrome browser but not working in Android or iPhone device. i have used the following code. Ext.regModel('Contact', { fields: ['firstName', 'lastName'] }); var store1 = new Ext.data.JsonStore({ model : 'Contact', autoLoad : true, autoDestroy : true, data: [ {firstName: 'Tommy', lastName: 'Maintz'}, {firstName: 'Rob', lastName: 'Dougan'}, {firstName: 'Ed', lastName: 'Spencer'}, {firstName: 'Abraham', lastName: 'Elias'}, {firstName: 'Jay', lastName: 'Robinson'} ] }); new Ext.Application({ launch: function() { var panel = new Ext.Panel({ fullscreen: true, id:'thePanel', layout: 'auto', style: 'background-color:darkblue', scroll:'vertical' }); //do this in your dynamically called function var list = new Ext.List({ id :'theList', itemTpl : '{firstName} {lastName}', store: store1, width: '100%', scroll:false }); var stateList = new Ext.form.Select({ label : 'State', widht: '100%', options: [ {text: 'First Option', value: 'first'}, {text: 'Second Option', value: 'second'}, {text: 'Third Option', value: 'third'} ], autoLoad : true, autoDestroy : true }); panel.items.add(list); panel.items.add(stateList); panel.doLayout(); } }); It gives the UI like as shown in the image. But the select control is not working for (State list in not populating). please help me. A: Each form field needs to have a name property, i.e. the name of the parameter to be send when the form is submitted. Updated your stateList object like this: var stateList = new Ext.form.Select({ label : 'State', name: 'selectField', width: '100%', options: [ {text: 'First Option', value: 'first'}, {text: 'Second Option', value: 'second'}, {text: 'Third Option', value: 'third'} ], autoLoad : true, autoDestroy : true });
{ "language": "en", "url": "https://stackoverflow.com/questions/7552571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting Error when using response.write() I need to save a file as .csv in client machine. I am using the code below. protected void btnGen_Click(object sender, EventArgs e) { try { string fileName = "test"; string attachment = "attachment; filename=" + fileName + ".csv"; List<string> lst1 = new List<string> { "wert", "fds", "hjgfh", "hgfhg" }; List<string> lst2 = new List<string> { "hgfds", "hdfg", "yretg", "treter" }; List<string> lst3 = new List<string> { "hgfdgf", "gfdg", "gfdgf", "ghfdg" }; List<List<string>> lst = new List<List<string>> { lst1, lst2, lst3 }; StringBuilder sb = new ExportFacade().GenerateStringBuilder(lst); Response.ContentType = "text/csv" ; lblProgress.ForeColor = System.Drawing.Color.Green; lblProgress.Text = "File created and write successfully!"; HttpContext.Current.Response.AddHeader("content-disposition", attachment); Response.Write(sb.ToString()); lblProgress.ForeColor = System.Drawing.Color.Green; lblProgress.Text = "File created and write successfully!"; Response.Flush(); Response.End(); } catch (Exception ex) { lblProgress.ForeColor = System.Drawing.Color.Red; lblProgress.Text = "File Saving Failed!"; } } I am not using update panels. When I click on the button I get the following error Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. It will be a great help to me if you can help me to get rid of this problem. thank you. A: I solved it. Ajax script manager in the master page has created the problem. After removing it, the function worked properly. But labels are not being updated as response is not for the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to test assert throws exception in Android is there a more elegant way to do an assert throws exception in Android then this? public void testGetNonExistingKey() { try { alarm.getValue("NotExistingValue"); fail( ); } catch (ElementNotFoundException e) { } } Something like this does not work?! @Test(expected=ElementNotFoundException .class) Thanks, Mark A: Are you using a junit4 test runner? The @Test annotation won't work if you're running a junit3 test runner. Check the version that you're using. Secondly, the recommended way to check for exceptions in your code is to use a Rule (introduced in junit 4.7). @Rule public ExpectedException exception = ExpectedException.none(); @Test public void throwsIllegalArgumentExceptionIfIconIsNull() { // do something exception.expect(IllegalArgumentException.class); exception.expectMessage("Icon is null, not a file, or doesn't exist."); new DigitalAssetManager(null, null); } You can continue to use the @Test(expected=IOException.class), but the above has the advantage that if an exception is thrown before the exception.expect is called, then the test will fail. A: I did something very similar to hopia's answer with a couple of improvements. I made it return the exception object so that you can check its message or any other properties, and I declared a Testable interface to replace Runnable because Runnable doesn't let your code under test throw checked exceptions. public interface Testable { public void run() throws Exception; } public <T extends Exception> T assertThrows( final Class<T> expected, final Testable codeUnderTest) throws Exception { T result = null; try { codeUnderTest.run(); fail("Expecting exception but none was thrown."); } catch(final Exception actual) { if (expected.isInstance(actual)) { result = expected.cast(actual); } else { throw actual; } } return result; } Here's an example of calling it. InvalidWordException ex = assertThrows( InvalidWordException.class, new Testable() { @Override public void run() throws Exception { model.makeWord("FORG", player2); } }); assertEquals( "message", "FORG is not in the dictionary.", ex.getMessage()); A: If you're using Kotlin, you can take advantage of reified types to avoid passing the Exception subclass as an argument: inline fun <reified T : Exception> assertThrows(runnable: () -> Any?) { try { runnable.invoke() } catch (e: Throwable) { if (e is T) { return } Assert.fail("expected ${T::class.qualifiedName} but caught " + "${e::class.qualifiedName} instead") } Assert.fail("expected ${T::class.qualifiedName}") } @Test fun exampleTest() { val a = arrayOf(1, 2, 3) assertThrows<IndexOutOfBoundsException> { a[5] } } A: This is how I do it. I create a static method called assertThrowsException that takes in as arguments an expected exception class and a Runnable which contains the code under test. import junit.framework.Assert; public SpecialAsserts { public void assertThrowsException(final Class<? extends Exception> expected, final Runnable codeUnderTest) { try { codeUnderTest.run(); Assert.fail("Expecting exception but none was thrown."); } catch(final Throwable result) { if (!expected.isInstance(result)) { Assert.fail("Exception was thrown was unexpected."); } } } } This is the sample code to use the special assert in your test class (that extends AndroidTestCase or one of its derivatives): public void testShouldThrowInvalidParameterException() { SpecialAsserts.assertThrowsException(InvalidParameterException.class, new Runnable() { public void run() { callFuncThatShouldThrow(); } }); } Yes, there's a lot of work, but it's better than porting junit4 to android. A: With junit3 the following might help. public static void assertThrows(Class<? extends Throwable> expected, Runnable runnable) { try { runnable.run(); } catch (Throwable t) { if (!expected.isInstance(t)) { Assert.fail("Unexpected Throwable thrown."); } return; } Assert.fail("Expecting thrown Throwable but none thrown."); } public static void assertNoThrow(Runnable runnable) { try { runnable.run(); } catch (Throwable t) { Assert.fail("Throwable was unexpectedly thrown."); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: problem with shell variables in awk I have a command which is executed successfully on command line: ls -l | awk '/Sep 26/{split($8,a,":");if(a[1]a[2]>=1045 && a[1]a[2]<=1145)print $9}' I am including the same thing in a shell script below: #!/bin/ksh date1=$1 date2=$2 time1=$3 time2=$4 ls -l| awk -v d1=${date1} -v d2=${date2} -v t1=${time1} -v t2=${time2} '/d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 && a[1]a[2]<=t2) print $9}' But this does not work.please see below the execution ksh -vx test.sh Sep 26 1045 1145 #!/bin/ksh date1=$1 + date1=Sep date2=$2 + date2=26 time1=$3 + time1=1045 time2=$4 + time2=1145 ls -l| awk -v d1=${date1} -v d2=${date2} -v t1=${time1} -v t2=${time2} '/d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 &&a[1]a[2]<=t2)print $9}' + awk -v d1=Sep -v d2=26 -v t1=1045 -v t2=1145 /d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 &&a[1]a[2]<=t2)print $9} + ls -l awk: syntax error near line 1 awk: bailing out near line 1 I am using Solaris OS:I have tried with nawk now but there is no error but also there is no output. pearl[ncm_o11.2_int.@].293> ksh -vx test.sh Sep 26 1045 1145 #!/bin/ksh date1=$1 + date1=Sep date2=$2 + date2=26 time1=$3 + time1=1045 time2=$4 + time2=1145 ls -l| nawk -v d1=${date1} -v d2=${date2} -v t1=${time1} -v t2=${time2} '/d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 &&a[1]a[2]<=t2)print $9}' + ls -l + nawk -v d1=Sep -v d2=26 -v t1=1045 -v t2=1145 /d1 d2/{split($8,a,":");if(a[1]a[2]>=t1 &&a[1]a[2]<=t2)print $9} When i am executing with out the shell variables inside the script.its executing perfectly. *Note:*I am using Solaris OS. I figured out the problem lies in the final framed command inside shell script: ls -l|nawk -v d1=Sep -v d2=26 -v t1=1045 -v t2=1145 '/d1 d2/{split($8,a,":");if(a[1]a[2] >=t1 && a[1]a[2]<=t2)print $9}' But i am not sure why this is failing to give the correct output with -v flags A: As already suggested, if you need a dynamic regular expression, you need to use $0 ~ d1 " " d2 instead of /d1 d2/. A: Which operating system? It's possible that when you run the command interactively awk points to a different awk implementation. If you're on Solaris, for example, try running your script with nawk (or gawk), instead of awk.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: validity plugin jquery problem? I'm using the validity plugin to validate a form. It's working fine but is it possible to execute a callback function if the validity function succeeded like the following $("form").validity(function(){ $("#place").require().range(3, 50); $("#location").require().greaterThan(4) }, function(){ /* Here to put the call back code */ }); because i want to to run some code if the form validation successes , Any idea would be appreciated A: According to the docs it's not easily possible. However, you might be able to write a custom "output mode" that executes your callback: http://validity.thatscaptaintoyou.com/Demos/index.htm#CustomOutputMode A: You could use the validate.start / validate.end method -> http://validity.thatscaptaintoyou.com/Demos/index.htm#UsingValidityWithAjax it would look something like this (untested!): function validateMyAjaxInputs() { $.validity.start(); $("#place").require().range(3, 50); $("#location").require().greaterThan(4) var result = $.validity.end(); return result.valid; } $("form").validity(function(){ if (validateMyAjaxInputs()) { // Do ajax request here } }); A: Okay, validity supports pluggable "output modules". Here's one (admittedly hacky and untested one) that will call your callback function. Just append the code to jquery.validity.outputs.js or put it into your own file that you load after validity. (function($) { $.validity.outputs.callback = { start:function() { buffer = []; }, end:function(results) { $.validity.settings.callback(results); }, raise:function($obj, msg) { buffer.push(msg); }, raiseAggregate:function($obj, msg) { this.raise($obj, msg); }, container:function() {} }; })(jQuery); Usage: $.validity.setup({ outputMode:"callback", callback:function(){ /* your callback */ } }); $("form").validity(function(){ $("#place").require().range(3, 50); $("#location").require().greaterThan(4) }); A: Normally you can do this kind of stuff like this: var IsValid = function(){ $.validity.start(); $("#place").require().range(3, 50); $("#location").require().greaterThan(4) var result = $.validity.end(); return result; } if (IsValid()) { //You callBack or whatewer } Of course using this pattern you are able to implement you js object which would be more convienent to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Timer in java using Eclipse I'm trying to do a little program in Java using Eclipse, and I'm a little bit lost. Could anybody explain me (in a "for dummies way") what do I have to do for repaint a form using a timer? I'm trying to do something as simple as a clock. I need a timer to repaint it every second. Something like this: private void activateTimer() { ActionListener myAction; myAction = new ActionListener () { public void actionPerformed(ActionEvent e) { whatever.redraw(); } }; myTimer = new Timer(1000, myAction); myTimer.start(); } When the action must be performed, I receive the error: *Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access* This is the full exception I receive: Exception in thread "AWT-EventQueue-0" org.eclipse.swt.SWTException: Invalid thread access at org.eclipse.swt.SWT.error(SWT.java:4282) at org.eclipse.swt.SWT.error(SWT.java:4197) at org.eclipse.swt.SWT.error(SWT.java:4168) at org.eclipse.swt.widgets.Widget.error(Widget.java:468) at org.eclipse.swt.widgets.Widget.checkWidget(Widget.java:359) at org.eclipse.swt.widgets.Control.redraw(Control.java:2327) at default.myTimer$1.actionPerformed(myTimer.java:97) at javax.swing.Timer.fireActionPerformed(Unknown Source) at javax.swing.Timer$DoPostEvent.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$000(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) Any idea or any sample about refreshing a screen every second? I've followed the instructions in one of the answers but I'm still receiving the same error. A: you have to split that to the separete methods, better would be using javax.swing.Action instead of ActionListener private void activateTimer(){ myTimer = new Timer(1000, myAction); myTimer.start(); } private Action myAction = new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { whatever.redraw(); } }; A: Why not use the timer functionality that is built into the SWT Display class? private void activateTimer(final Display display) { display.timerExec( 1000, new Runnable() { public void run() { whatever.redraw(); // If you want it to repeat: display.timerExec(1000, this); } }); } A: This page may be useful. If you use SWT, do it in SWT way :) EDIT: The problem is widget should be updated by eclipse's thread. Try this code. Job job = new Job("My Job") { @Override protected IStatus run(IProgressMonitor monitor) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { while(true) { Thread.sleep(1000); whatever.redraw(); } } }); return Status.OK_STATUS; } }; job.schedule();
{ "language": "en", "url": "https://stackoverflow.com/questions/7552596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Text Change event fired when button clicked I am working on .net 2.0 I am populating a Grid View with multiple textboxes. The textbox has text change event. There is also a button with click event. The problem I am facing is that when the I enter the text in textbox and then click on button, the text change event gets fired, and the execution does not come to button click block. How can I detect if button has been clicked when both the events are fired. There is the textbox with call to function for text change event <asp:TextBox ID="txtChassis" runat="server" CssClass="form_text_box" AutoPostBack="true" OnTextChanged="Chassis_TextChanged"></asp:TextBox> and also call to function for button click event. <input class="form_button" id="btnSearch" title="Show Details" accesskey="S" type="submit" value="SAVE" name="btnSave" runat="server" onserverclick="btnSearch_ServerClick"/> However, in case text is placed in textbox and button is clicked, then the text change event function gets called. A: Your Problem is, that events in ASP are only raised after a PostBack. The Post back happens if the Button is pressend, and the Client Posts Back (therfor the Name) his Data of the Fields. After this PostBack the Server (your application) calls all events that happend during the last Page_Load. As far as i know, there is no real order in which the events are thrown, but the textChanged event should be thrown anyway. If you want to hand your textChanged event directly after the Text hast changed you have to use "AutoPostBack" as Myat Thu already mentioned. Be aware that this increases your traffic signifficant, and can also change the flow of your code! I suggest designen the events indipendet so the user can hit the "PostBack Button" and all events are called at one post back. This saves traffic and load on the server. But this is just my personal oppinion. A: Are you writing code for a window application or a web application? If you're writing for a web application, there are properties for TextBoxes which are: CaseValidation AutoPostBack You should try out both of these properties for your TextBox object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Binding nested lists using Lambda (C#) I have this piece of code that I'm trying to convert to lambda - foreach (var facet in response.Result.Facets) { var newFacet = new Facet {Parent = facet.Title}; foreach (var element in facet.Subelements) { newFacet.Items.Add(new Facet { Title = element.Title, TotalResults = element.TotalResults }); } searchModel.Facets.Add(newFacet); } Here's what I have so far - response.Result.Facets.ForEach(x => searchModel.Facets.Add(new Facet { Parent = x.Title, Items = ???//x.Subelements.ForEach(y=>) })); And the classes - public class Facet { public Facet() { Items = new List<Facet>(); } public string Parent { get; set; } public List<Facet> Items { get; set; } public int TotalResults { get; set; } public string Title { get; set; } } public class SearchElement { public string Parent { get; set; } public string Title { get; set; } public int TotalResults { get; set; } public IList<ESearchElement> Subelements { get; set; } } How do I bind List<SearchElement> to List<Items> by mapping each element (title = y.Title..) all in one line within a lambda expression? Is it possible? A: Try something like this: searchModel.Facets.AddRange( from facet in response.Result.Facets select new Facet { Parent = facet.Title, Items = new List<Facet>( from element in facet.Subelements select new Facet { Title = element.Title, TotalResults = element.TotalResults }), }); EDIT: Lambda version per request in comment. searchModel.Facets.AddRange( response.Result.Facets.Select( facet => new Facet { Parent = facet.Title, Items = new List<Facet>( facet.Subelements.Select( element => new Facet { Title = element.Title, TotalResults = element.TotalResults })), })); Much the same as with LINQ. Is this what you were after?
{ "language": "en", "url": "https://stackoverflow.com/questions/7552600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I protect the source of my HTML Metro app? I'm really interested in building applications in a Windows 8 Metro style. I would like to use HTML5 but I am very concerned about protecting my front end UI from deconstruction and ultimately being ripped off by others. Unfortunately, my service is all open source so I cannot really hide things there unless i implement some sort of middle man between the open source service and my front end HTML5 app. So as the title says, how do I protect the source of my HTML Metro Application? A: You have two options: * *Run a JavaScript obfuscator over your code. This will make it much harder to figure out, but not impossible. *Implement the critical functions as C++ methods. You can call these using WinRT easily from JavaScript. This will make it much harder to understand what is going on. A: If you want to keep something (anything) secret, do NOT pass it to the client. There might be some kind of obfuscation that I don't know about (yet) but still it will be possible to reconstruct the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to get dynamic field in LINQ Here's my LINQ query: var settingViewModels = from l in settingsByEnvironment["Localhost"] join d in settingsByEnvironment["Dev"] on l.Key equals d.Key join p in settingsByEnvironment["Prod"] on d.Key equals p.Key select new MyKeyValue { Key = p.Key, LocalhostValue = l.Value, DevValue = d.Value, ProdValue = p.Value }; As you see, I've hard coded the three environment Localhost, Dev, and Prod in two parts of my code. What if tomorrow, I have a new environment? My code is not dynamic. I tried to use ExpandoObject, but still I cannot have a full dynamic query. Here's the equivalent of my previous LINQ code using ExpandoObject; // listSettingsEnvLocalhost is of type Tuple<string (environmentName), List<SettingViewModels>> public void GetSettingsValueForEachEnvironment() { var foo = from p in listSettingsEnvLocalhost.Item2 join a in listSettingsEnvDev.Item2 on p.Key equals a.Key let environmentLocalhost = listSettingsEnvLocalhost.Item1 let environmentDev = listSettingsEnvDev.Item1 select ToExpando(p, a, environmentLocalhost, environmentDev); } private dynamic ToExpando(SettingViewModel first, SettingViewModel second, string environmentLocalhost, string environmentDev) { dynamic o = new ExpandoObject(); ((IDictionary<string, object>)o).Add("Key", first.Key); ((IDictionary<string, object>)o).Add(environmentLocalhost, first.Value); ((IDictionary<string, object>)o).Add(environmentDev, second.Value); return o; } Is an expression tree a solution? A: If you want create a dynamic query, you can use dynamic LINQ operators that are available at this link: http://msdn.microsoft.com/en-us/bb330936.aspx (download the C# example and get the code in the \LinqSamples\DynamicQuery directory) There is also a dynamic Join operator defined by Royd Brayshay. See Stack Overflow question How to create a dynamic LINQ join extension method. A: I would store your setting variables in a dictionary instead. Then it would be more dynamic. The dictionary should look like Dictionary<string, Dictionary<string, string>. The first key is environment and the key in the inner dictionary is the settings key. Then you would be all set, and it would be dynamic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I merge images in memory (.py) or in view (HTML)? My facebook app lets the user upload an image, select what the image is (eyes, nose, mouth or other body part) and then can combine by selecting three random images by category and that's works fine and the code looks ok and readable though not very advanced: class CyberFazeHandler(BaseHandler): def get_random_image(self, category): fileinfos = FileInfo.all().filter("category =", category) return fileinfos[random.randint(0, fileinfos.count()-1)] def get(self): eyes_image = self.get_random_image(category="eyes") nose_image = self.get_random_image(category="nose") mouth_image = self.get_random_image(category="mouth") eyes_data = None try: eyes_data = blobstore.fetch_data(eyes_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find eyes data for file '+str(eyes_image.key().id())+' (' + unicode(e) + u')') eyes_img = None try: eyes_img = images.Image(image_data=eyes_data) ...now I just fetch 3 random images and then combine then in the template: <a href="/file/{{eyes_image.key.id}}"><img src="{{eyes_url}}"></a><br> <a href="/file/{{nose_image.key.id}}"><img src="{{nose_url}}"></a><br> <a href="/file/{{mouth_image.key.id}}"><img src="{{mouth_url}}"></a> Could this be improved by sending a composite image combining the three images into one? With the advantage that everything on the image will load at the same time and that it will be saved already if a randomization comes up next time the result is already saved. What do you think? Thank you (the application is apps.facebook.com/cyberfaze you may inspect I did for fun and learning) The entire class is class CyberFazeHandler(BaseHandler): def get_random_image(self, category): fileinfos = FileInfo.all().filter("category =", category) return fileinfos[random.randint(0, fileinfos.count()-1)] #optimize def get(self): eyes_image = self.get_random_image(category="eyes") nose_image = self.get_random_image(category="nose") mouth_image = self.get_random_image(category="mouth") eyes_data = None try: eyes_data = blobstore.fetch_data(eyes_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find eyes data for file '+str(eyes_image.key().id())+' (' + unicode(e) + u')') eyes_img = None try: eyes_img = images.Image(image_data=eyes_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find eyes img for file '+str(eyes_image.key().id())+' (' + unicode(e) + u')') nose_data = None try: nose_data = blobstore.fetch_data(nose_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find nose data for file '+str(nose_image.key().id())+' (' + unicode(e) + u')') nose_img = None try: nose_img = images.Image(image_data=nose_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find nose img for file '+str(nose_image.key().id())+' (' + unicode(e) + u')') mouth_data = None try: mouth_data = blobstore.fetch_data(mouth_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find mouth data for file '+str(eyes_image.key().id())+' (' + unicode(e) + u')') mouth_img = None try: mouth_img = images.Image(image_data=mouth_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find mouth img for file '+str(mouth_image.key().id())+' (' + unicode(e) + u')') minimum = min(int(eyes_img.width), int(nose_img.width), int(mouth_img.width)) eyes_url = images.get_serving_url(str(eyes_image.blob.key()), size=minimum) nose_url = images.get_serving_url(str(nose_image.blob.key()), size=minimum) mouth_url = images.get_serving_url(str(mouth_image.blob.key()), size=minimum) self.render(u'cyberfaze', minimum=minimum, eyes_image=eyes_image, eyes_url=eyes_url, nose_image=nose_image, nose_url=nose_url, mouth_image=mouth_image, mouth_url=mouth_url, form_url = blobstore.create_upload_url('/upload'),) After rewrite it's working like said: class CyberFazeHandler(BaseHandler): def get_random_image(self, category): q = FileInfo.all() q.filter('category =', category) q.filter('randomvalue >=', random.random()) return q.get() def get_random_image_legacy(self, category): fileinfos = FileInfo.all().filter('category =', category) return fileinfos[random.randint(0, fileinfos.count() - 1)] def get(self): eyes_image = self.get_random_image(category='eyes') if not eyes_image: logging.debug("getting eyes failed, trying legacy method") eyes_image = self.get_random_image_legacy(category='eyes') nose_image = self.get_random_image(category='nose') if not nose_image: nose_image = self.get_random_image_legacy(category='nose') mouth_image = self.get_random_image(category='mouth') if not mouth_image: mouth_image = self.get_random_image_legacy(category='mouth') eyes_data = None try: eyes_data = blobstore.fetch_data(eyes_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find eyes data for file ' + str(eyes_image.key().id()) + ' (' + unicode(e) + u')') eyes_img = None try: eyes_img = images.Image(image_data=eyes_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find eyes img for file ' + str(eyes_image.key().id()) + ' (' + unicode(e) + u')') nose_data = None try: nose_data = blobstore.fetch_data(nose_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find nose data for file ' + str(nose_image.key().id()) + ' (' + unicode(e) + u')') nose_img = None try: nose_img = images.Image(image_data=nose_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find nose img for file ' + str(nose_image.key().id()) + ' (' + unicode(e) + u')') mouth_data = None try: mouth_data = blobstore.fetch_data(mouth_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find mouth data for file ' + str(eyes_image.key().id()) + ' (' + unicode(e) + u')') mouth_img = None try: mouth_img = images.Image(image_data=mouth_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find mouth img for file ' + str(mouth_image.key().id()) + ' (' + unicode(e) + u')') minimum = min(int(eyes_img.width), int(nose_img.width), int(mouth_img.width)) eyes_url = images.get_serving_url(str(eyes_image.blob.key()), size=minimum) nose_url = images.get_serving_url(str(nose_image.blob.key()), size=minimum) mouth_url = images.get_serving_url(str(mouth_image.blob.key()), size=minimum) self.render( u'cyberfaze', minimum=minimum, eyes_image=eyes_image, eyes_url=eyes_url, nose_image=nose_image, nose_url=nose_url, mouth_image=mouth_image, mouth_url=mouth_url, form_url=blobstore.create_upload_url('/upload'), ) A: Which is more efficient depends on how it'll be used. If the user will be loading a lot of these mashups, it makes more sense to send them as separate images, because there will be fewer images for the browser to cache (a+b+c images instead of a*b*c). Your code has a much more egregious performance issue, however: def get_random_image(self, category): fileinfos = FileInfo.all().filter("category =", category) return fileinfos[random.randint(0, fileinfos.count()-1)] Every time you call this function, it will perform a count operation, which is O(n) with the number of FileInfo entities, then perform an offset query, which is O(n) with the offset. This is extremely slow and inefficient, and will get more so as you increase the number of images. If you expect the set of images to be small (less than a few thousand) and fairly constant, simply store them in code, which will be faster than any other option. If the set is larger, or changes at runtime, assign a random value between 0 and 1 to each entity, and use a query like this to retrieve a randomly selected one: q = FileInfo.all() q.filter('category =', category) q.filter('random >=', random.random()) return q.get()
{ "language": "en", "url": "https://stackoverflow.com/questions/7552604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Random memcache calls take extra-ordinarily long Please see this appstats log, randomly some memcache calls take extraordinarily longer than others. These are all get calls for memcached counters so there is absolutely nothing different about the calls that are taking longer than others. Any explanation? A: Memcache like all GAE service is done using a remote procedure call and the response time is not generated. If the machine/network is busy it might lag. The real question here is way are you calling memcache 20 times in a single request? There are two ways go work around it: * *Use the get_multi to retreive all the values at once (if possible) *Use the async memcache, start retrving the values but don't wait for them use them when they are all ready.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: address=data via macro define #define PORTC *(unsigned char volatile *)(0x1003) #define DDRC *(unsigned char volatile *)(0x1007) So I've been trying to read some stuff about embedded C. Initially I thought this macro was a pointer-to-pointer type but then I soon assumed the last star is actually a dereference rather than a type-cast, am I correct? Dereferencing to the location 0x1003/0x1007. It is used like: PORTC = <some hex value> Question is what makes this different from a pointer type-cast? Is there some sort of 'provision' in the C specifications? Or am I just an idiot... Also I don't quite know how to phrase this and so I couldn't do a quick search first... A: No, it is quite a cast. First, the memory location (as integer) is cast into an appropriate pointer which is then dereferenced. A: It's just the way the C grammar is defined. To be a cast, the expression needs parenthesis: (type)sub-expression casts sub-expression to type type. Your example, *(unsigned char volatile *)(0x1003) is composed of 2 sub-expressions: * *a "lonely" star: * *a cast: (unsigned char volatile *)(0x1003) The cast is composed of the type inside () and a value. So, the whole expression is interpreted as a pointer, then de-referenced to set the memory area pointed to. A: That code is basically equivalent to: Put <some hex value> in the memory at the address (0x1003) (or whatever the value is). In some embedded devices (and not only) ports are mapped at memory locations. A: The cast instructs the compiler that the memory addresses 0x1003 and 0x1007 are to be treated as unsigned char volatile * pointers, and the * dereferencing operator acts on that pointer to fetch the pointed-to value, which in this case is 1 byte. Applying the unary * makes this expression a valid lvalue (it wouldn't be so without it) which means that it is something you can assign to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java UDP packet read failing I am trying to send packets from one host to another peer host using java UDP protocol. The one host sends data, while the other reads it. The corresponding read however keeps blocking, thus receiving no data. I can see the sender packets going to the right destination using wireshark, but the receiver just wont pick it up. The read operation keeps blocking indefinitely. Please help. Code for cient: //CLIENT CLASS //Sections ommited.... DatagramSocket so = new DatagramSocket(port); protected void send(byte[] buffer,int packetsize){ DatagramPacket p; try { myClient.notifyInform("Sending data to "+inetaddress+" on"+port+"\n"); p=new DatagramPacket(buffer,buffer.length,InetAddress.getByName(inetaddress),port); writeLock.lock(); try{ so.send(p); }finally{ writeLock.unlock(); } } catch (UnknownHostException e) { myClient.perror("Could not connect to peer:"+e.getMessage()+"\n"); e.printStackTrace(); } catch (IOException e) { myClient.perror("IOException while sending to peer.\n"); e.printStackTrace(); } } protected DatagramPacket read(){ byte[] buf=new byte[bufsize]; DatagramPacket p=new DatagramPacket(buf,buf.length);//TODO check these values, what should buffer be? just made it psize*10 for now readLock.lock(); try{ myClient.notifyInform("receiving data\n"); so.receive(p); this.myclient.notifyInform(String.valueOf(p.getData().length)+"\n"); } catch (IOException e) { myClient.perror("IOException while reading from peer.\n"); e.printStackTrace(); }finally{ readLock.unlock(); } return p; } protected void beginRead() { while(active) { System.out.println("########################"); byte[] data=this.read().getData(); myClient.notifyInform("Receiving data\n"); } } protected void beginSend(){ forkWork(new Runnable(){ @Override public void run() { byte[] sendBuffer=new byte[bufsize]; int cnt; while(callActive){ try{ sourceLock.lock(); cnt=dataSource.read(sendBuffer, 0, bufsize); }finally{ sourceLock.unlock(); } if (cnt >0) { send(sendBuffer, packetsize); } } } }); } UPDATE:I made a mistake that I finally tracked down. After binding the port, and fixing that error, it now works. A: You need to specify the port that the datagram socket is listening on like this: this.so = new DatagramSocket(SOME_NUMBER_HERE); and make sure you send it to the same port number in the send() method A: Is your receiving DatagramSocket listening at the IP:port the sender is sending to?
{ "language": "en", "url": "https://stackoverflow.com/questions/7552612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to define a dynamic scope in Ruby Sunspot? I want to search the tracks either by "all of" the filters, or by "any of" the filters. So here is what I got: tracks_controller.rb def search if params[:scope] == "any_of" Track.search do any_of do with(:name, "Thriller") with(:artist, "Michael Jackson") end with(:user_id, current_user.id) end elsif params[:scope] == "all_of" Track.search do all_of do with(:name, "Thriller") with(:artist, "Michael Jackson") end with(:user_id, current_user.id) end end It works as expected. But how to refactor the code to make it DRY? A: Here it is Sir: def search Track.search do mode = (params[:scope] == 'any_of' ? method(:any_of) : method(:all_of)) # don't use method(params[:scope]) for obvious security reason) mode.call do with(:name, "Thriller") with(:artist, "Michael Jackson") end with(:user_id, current_user.id) end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7552613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hibernate insert with single column table problem I'm using Hibernate with a SQLite database. I have the following class : @Entity @Inheritance(strategy=InheritanceType.JOINED) public abstract class Authority { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int idAuthority; (...) I then have a class Author, that extends Authority and add 4 or 5 fields. When I try to save an Author object, Hibernate generates the following request : Hibernate: insert into Authority values ( ) And sqlite doesn't like that. If I add a dummy String field, like "private String test" and set this property in the constructor, everything works fine. I'm quite new to hibernate, so I'm not sure how to proceed. Do you have any idea ? Edit : As requested, the mapping of the Author class : @Entity @Table(name="Authors") @PrimaryKeyJoinColumn(name="idAuthority") public class Author extends Authority { @Column(name = "firstName") protected String firstName; @Column(name = "lastName") protected String lastName; @Column(name = "alias") protected String alias; (...) } Edit : As requested (bis), the insert code : public void save(Object data) { currentSession.saveOrUpdate(data); } Nothing fancy... And to give you more possible leads, here is the database schema : create table Authority (idAuthority integer, primary key (idAuthority)) create table Authors (alias varchar, firstName varchar, lastName varchar, idAuthority bigint not null, primary key (idAuthority)) N.B. : in SQLite, an integer that is primary key is automatically set to AUTO-INCREMENT. The Exception raised is this one : java.sql.SQLException: near ")": syntax error The request should be more like : insert into Authority values (NULL) to let SQLite do its auto-increment, not this weird "insert into Authority values ()". Edit : This is definetely a problem with the SqlLite for Hibernate package. I just tried with Hsqldb, and it gives me a proper query : insert into Authority (idAuthority) values (default) (Then it fails too, but for very different reasons :p ). I'm not sure there is a solution to this problem... other than using a different DB. A: If you use InheritanceType.JOINED your table associated with class Authority must contain column associated with idAuthority and your table associated with class Author must contain column associated with idAuthority that is a foreign key to the primary identifier in table which presents Authority. It's required for table relations accociation A: Try Overriding the ID. @Entity @Table(name="Authors") @PrimaryKeyJoinColumn(name="idAuthority") @AttributeOverride(name="idAuthority", column=@Column(name="id")) public class Author extends Authority { @Column(name = "firstName") protected String firstName; @Column(name = "lastName") protected String lastName; @Column(name = "alias") protected String alias; (...) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Regular expression for a formatted time I have a time format that I want to check if it is correct. The format should be [H]H.MM[a|p]. Hours should be from 1 to 12, minutes as usual and the ending character either an a or p. There should also be a dot between the hours and minutes. I tried with this reg ex, but it didn't work: var reg = /^([1-9|10|11|12])\.[0-5][0-9][pa]$/; A: You meant var reg = /^([1-9]|10|11|12)\.[0-5][0-9][pa]$/; A: Try that: ^([1-9]|10|11|12)\.[0-5][0-9][ap]$
{ "language": "en", "url": "https://stackoverflow.com/questions/7552617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Paramiko bug: SSHClient.connect() method hangs when the peer is unreachable even if I set the 'timeout' Here is a python code snippet that uses paramiko: import paramiko sshClient = paramiko.SSHClient() sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy) sshClient.connect(_peerIp, username=_username, password=_password, timeout=3.0) As soon as I run the script, I also unplug _peerIp's network cable. And connect() method hangs. Even though the timeout is 3.0, it has been 10 minutes and it still hangs. (I think the TCP connection was established in a split second and I unplugged the cable during the ssh establishment) So, do you know any workaround for this? My script will run at a manufacturing factory and it must not hang in such a scenario and handle it properly. EDIT: It just gave an exception: No handlers could be found for logger "paramiko.transport" Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 327, in connect self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys) File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 438, in _auth self._transport.auth_publickey(username, key) File "/usr/lib/pymodules/python2.6/paramiko/transport.py", line 1234, in auth_publickey return self.auth_handler.wait_for_response(my_event) File "/usr/lib/pymodules/python2.6/paramiko/auth_handler.py", line 163, in wait_for_response raise e socket.error: [Errno 113] No route to host Ok, at least it eventually raised an exception but I believe this is not the expected behaviour. If the timeout is 3.0, connect() method should return something after timeout expires.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: problem in taking screenshots in android by programmatically in my app i am taking screenshot of the current screen and save it in sdcard. but in the case screenshot is not saved in sdcard. how to take screen shot and send the captured screen shot in email as attachment. please help me. my coding: View v1 = view.getRootView(); v1.setDrawingCacheEnabled(true); Bitmap bm = v1.getDrawingCache(); try { System.out.println("path "+Environment.getExternalStorageDirectory()); FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/ff"); bm.compress(CompressFormat.PNG, 90, out); } catch (Exception e) { e.printStackTrace(); } Intent emailIntent = new Intent(Intent.ACTION_SEND); Uri U=Uri.parse("file:///sdcard/ff"); emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "aabc@gmail.com" }); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, " from .."); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "from the app"); emailIntent.setType("image/png"); // emailIntent.putExtra(android.content.Intent.EXTRA_STREAM,U); emailIntent.putExtra(Intent.EXTRA_STREAM, U); startActivity(Intent.createChooser(emailIntent, "")); please help me. A: i solved my problem by replace the try clause coding by File file = new File(Environment.getExternalStorageDirectory()+"/filmfestival.png"); try { file.createNewFile(); FileOutputStream ostream = new FileOutputStream(file); bitmap.compress(CompressFormat.PNG, 100, ostream); ostream.close(); } catch (Exception e) { e.printStackTrace(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Macro to delete an email I have created a macro that forwards an email on to a recipient once a button is clicked. However, I want the macro to also delete the email (sending it to the recycle bin). Here is the current code. This currently works and forwards the email. Sub forwardEmail() Dim oExplorer As Outlook.Explorer Dim oMail As Outlook.MailItem Dim oOldMail As Outlook.MailItem Set oExplorer = Application.ActiveExplorer If oExplorer.Selection.Item(1).Class = olMail Then Set oOldMail = oExplorer.Selection.Item(1) Set oMail = oOldMail.forward oMail.Recipients.Add "Recipients email goes here" oMail.Recipients.Item(1).Resolve If oMail.Recipients.Item(1).Resolved Then oMail.Send Else MsgBox "Could not resolve " & oMail.Recipients.Item(1).Name End If Else MsgBox "Not a mail item" End If End Sub I thought by adding oMailItem.Delete to the code would work but it does not. A: It wasn't clear to me which email you wanted deleted, the original email or the forwarded email from Sent items - so these mods provide both options. Sub forwardEmail() Dim oExplorer As Outlook.Explorer Dim oMail As Outlook.MailItem Dim oOldMail As Outlook.MailItem Set oExplorer = Application.ActiveExplorer If oExplorer.Selection.Item(1).Class = olMail Then Set oOldMail = oExplorer.Selection.Item(1) Set oMail = oOldMail.Forward oMail.Recipients.Add "spam_me" oMail.Recipients.Item(1).Resolve If oMail.Recipients.Item(1).Resolved Then 'delete forwarded email from sent items oMail.DeleteAfterSubmit = True oMail.Send 'delete original email from inbox oOldMail.Delete Else MsgBox "Could not resolve " & oMail.Recipients.Item(1).Name End If Else MsgBox "Not a mail item" End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7552620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Changing the selected Menu items class across pages For my website project I am using ASP.NET MVC "Razor". Learning as I go. I have 5 or 6 pages on my site, and one page that is on another site. I want users to feel like they are using the same site for all. There is a typical HTML menu for the pages which follows the standard pattern of using a XHTML unordered list and CSS to layout: <ul id="menu"> <li class="selected"><a href="@Href("~/")">Home</a></li> <li><a href="http://ceklog.kindel.com">cek.log</a></li> <li><a href="@Href("~/Services")">Services</a></li> <li><a href="@Href("~/Charlie")">Charlie's Stuff</a></li> <li><a href="@Href("~/Contact.cshtml")">Contact</a></li> </ul> Elsewhere on SO I found questions similar to mine, where people wanted to track the selected menu item, but within a dynamic page. For example: Javascript Changing the selected Menu items class But this approach won't work in my case because in my case the user is not changing a selection on one page, but navigating to another page completely. How can this be done? A: ...and I figured it out. I used Razor to implement this on the server side. First I implemented a function on my _SiteLayout.cshtml page (the template all pages use): @functions { public string Selected(string PageTitle) { if (Page.Title == PageTitle) return "selected"; else return ""; } } Then I used this function in my list: <ul id="menu"> <li class="@Selected("Home")"><a href="@Href("~/")">Home</a></li> <li class="@Selected("cek.log")"><a href="http://ceklog.kindel.com">cek.log</a></li> <li class="@Selected("Services")"><a href="@Href("~/Services")">Services</a></li> <li class="@Selected("Charlie's Stuff")"><a href="@Href("~/Charlie")">Charlie's Stuff</a></li> <li class="@Selected("Contact")"><a href="@Href("~/Contact.cshtml")">Contact</a></li> </ul> Works perfectly. On my external page, I just hand-coded it since it's based on Wordpress and not Razor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Finishing off my 'make folders from database' class The below is a class for making local folders from database entries where each folder has a name, id and parent-id. I have put it together as best I can but do not know enough to finish it off. I need to "just grab the folder with id 0 and start building your Files on the disk, using folder.getChildren() as a convenient way to move down the tree then just mkdirs()" as told to me in another post but I do not understand how and where to do it. Please help public class Loop { public static void main(String[] args) { int PID = 0; int RepoID = 1; Connection con = null; String url = "jdbc:mysql://localhost/document_manager"; String user = "root"; String password = "Pa55w0rd"; try { con = DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); } Map<Integer,Folder> data = new HashMap<Integer,Folder>(); while( PID < 50 ) { try { Statement st = con.createStatement(); ResultSet result = st.executeQuery("SELECT name, category_id, parent_id FROM categories WHERE parent_id = '"+PID+"' AND repository_id = '"+RepoID+"'"); while (result.next ()) { String FolderName = result.getString ("name"); String FolderId = result.getString ("category_id"); String ParentId = result.getString ("parent_id"); int intFolderId = Integer.parseInt(FolderId); int intParentId = Integer.parseInt(ParentId); System.out.println( FolderId+" "+FolderName+" "+ParentId ); //intFolderId = Integer.valueOf(FolderId); //intParentId = Integer.valueOf(FolderId); Folder newFolder = new Folder(FolderName, intFolderId, intParentId); data.put(newFolder.getId(), newFolder); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } PID++; } for(Folder folder : data.values()) { int parentId = folder.getParentFolderId(); Folder parentFolder = data.get(parentId); if(parentFolder != null) parentFolder.addChildFolder(folder); } } } A: Basically reading hierachies from the database is not trivial, but if you read one level per query that should be doable. What you need to do is the following: * *select all folders that have no parent, those are your root folders *create the folders if they don't exist already *repeat the following until you don't get any more results from the db * *select all folders whose parent id is the id of the folders read in the previous iteration (or the parents) *assign the read subfolders to their parents based on the parent id *create the read subfolders in their parents This would allow you to use a breadth-first approach, i.e. you read one level of folders per iteration and map the children to the parents using parent_id. As an alternative you could read the children for a single parent and iterate over the hierarchy in a depth-first manner.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can onload event fire right after setting image src attribute? What console log can be after this code will be executed? var img = new Image; img.onload = function() { console.log('B'); }; img.src = 'image.jpg'; for (var i=0;i<100000;i++) { console.log('A'); } I know, that most likely it will be A...AB. But can it be A...B...A or BA...A? For example, if image.jpg is very small file and connection is very fast. A: It can be any of them. You don't know how long it takes to load the image. The image could even be cached, minimizing the loading time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What does "^:static" do in Clojure? I've seen the ^:static metadata on quite a few function in the Clojure core.clj source code, e.g. in the definition of seq?: (def ^{:arglists '([x]) :doc "Return true if x implements ISeq" :added "1.0" :static true} seq? (fn ^:static seq? [x] (instance? clojure.lang.ISeq x))) What precisely does this metadata do, and why it it used so frequently throughout core.clj? A: In the development of Clojure 1.3 Rich wanted to add the ability for functions to return types other than Object. This would allow native math operators to be used without having to cram everything into one function. The original implementation required functions that supported this to be marked :static. this meta data caused the compiler to produce two versions to the function, one that returned Object and one that returned that specific type. in cases where the compiler determined that the types would always match the more specific version would be used. This was later made fully automatic so you don't need to add this anymore. A: According to the Google Groups thread “Type hinting inconsistencies in 1.3.0”, it’s a no-op. ^:static has been a no-op for a while AFAIK, made unnecessary after changes to vars a while back. — a May 2011 post by Chas Emerick A: Seems it's a new metadata attribute in clojure 1.3. And you can compare the source between 1.3 and 1.2: * *http://clojuredocs.org/clojure_core/clojure.core/seq_q *http://clojuredocs.org/clojure_core/1.2.0/clojure.core/seq_q So I think it has something to do with ^:dynamic which indicates whether the var is allowed for dynamic binding. Just my guess. Not sure until I see document about this attribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: how to open a socket in php I am completely new to sockets and not that familiar with the concept. I am planning on making a phone application for chatting. now I was told that if you open a socket you can push results (chat entries) to the phone application. now is this something I can do with fsockopen php function?? and how would I keep the connection open and push data from the database to the application? Thanks A: Read this and you'll be up and running in no time. Socket servers are mysterious and fun... :D
{ "language": "en", "url": "https://stackoverflow.com/questions/7552633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# PropertyGrid - How to make array elements read only? I have a PropertyGrid to which I add a array of bool-values. The array itself is marked as ReadOnly, which is recognized properly by the property grid. BUT: If I expand the array in the Grid, all the items are editable by the user. Of course that's not what I want. If the array itself is marked a s ReadOnly all its elements shall be as well! Is there any way to achieve this behavior in the PropertyGrid? A: You can define your own TypeConverter. Using a TypeConverter, you can control the properties that the PropertyGrid shows, and their behavior. A: The readonly keyword doesn't work the way you think it does: using System; class Program { static readonly bool[] arr = { false, true }; static void Main(string[] args) { arr[0] = true; } } Yes, use TypeConverter to alter the behavior of types in PropertyGrid. Or just give it the [Browsable(false)] attribute because nobody wants to look at an array of booleans anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Long Delay in Calling the InCallScreen Process outlined: Why does the call to the new interface (InCallScreen) take such a long time? (From TwelveKeyDialer to InCallScreen). This makes for a poor user experience. First: TwelveKeyDialer.java: dialButtonPressed(){ ... startActivity(intent); } ... why is the jump to the new interface (InCallScreen) slow? Last: InCallScreen.java: onCreate(){ ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Overview of ISharedImages? The Java UI plugin provides the Interface ISharedImages to access standard images which can be used in own plugins. e.g. Image image = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT); This works very well but I did not find an overview of the available images. Can someone please point me to such a documentation? A: Some of them you can find here, but keep in mind that other 3rd party plugins can add another set of shared images for which, you would have to refer to that plugin documentation. A: You can use the Plug-in Image Browser which was added recently: Window > Show View > Other... > Plug-in Development > Plug-in Image Browser See also http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.pde.doc.user%2Fguide%2Ftools%2Fviews%2Fimage_browser_view.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7552638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Is OO Base compatible with MSO Access? Is Open Office Base compatible with MS Office Access? That is, can I successfully edit an Access-made database from Base? Thanks A: By opening oo base (version 3.3), the dialog box proposes to select a database and connect to an existing one. Among the available options, it is possible to connect directly to: * *an Acces Database *an Access 2007 Database *an ODBC database *an ADO database Though the "Acces Specific" connectors will allow you to transfer existing data from an Access database to a ooBase database, the more generic one (ODBC, ADO) can allow you to manipulate any ODBC\ADO compatible database, including Access. Though it is dated, you could refer to this oo version2 document, where there is an example of connecting from ooBase to Access through ADO
{ "language": "en", "url": "https://stackoverflow.com/questions/7552643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Resize CMD Window How can I resize the Command Prompt window programmatically in C or C++? For example 80x25 or 80x40 characters. Thank you in advance. A: SetConsoleWindowInfo A: The MODE command allows you to set the size of the Command Prompt window. The syntax is: MODE [COLUMNS],[LINES] For example for a 80x25 window you would use system("MODE 80,25"); This size is associated with a specific instance of the window so other command windows will be set to the default size. It works in both newer WinNT based OSs (i.e. Win2000/XP/7) and Win9x. If the size is not supported it will not change. Place it before any output, as it clears the screen. A: I did some more research and this is what I came up with: #include <windows.h> int main(){ system("mode 80,25"); //Set mode to ensure window does not exceed buffer size SMALL_RECT WinRect = {0, 0, 80, 25}; //New dimensions for window in 8x12 pixel chars SMALL_RECT* WinSize = &WinRect; SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), true, WinSize); //Set new size for window //Insert your code here return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to pass multiple parameters to a target in Ant? I have this dummy target: <mkdir dir="${project.stage}/release <war destfile="${project.stage}/release/sigma.war"> ... ... </war> What I want to do is provide two parameters say "abc" & "xyz" which will replace the word release with the values of abc and xyz parameters respectively. For the first parameter say abc="test", the code above will create a test directory and put the war inside it.Similarly for xyz="production" it will create a folder production and put the war file inside it. I tried this by using <antcall target="create.war"> <param name="test" value="${test.param.name}"/> <param name="production" value="${prod.param.name}"/> </antcall> in the target which depends on the dummy target provided above. Is this the right way to do this.I guess there must be some way to pass multiple parameters and then loop through the parameters one at a time. A: unfortunately ant doesn't support iteration like for or foreach loops unless you are refering to files. There is however the ant contrib tasks which solve most if not all of your iteration problems. You will have to install the .jar first by following the instructions here : http://ant-contrib.sourceforge.net/#install This should take about 10 seconds. After you can simply use the foreach task to iterate through you custom list. As an example you can follow the below build.xml file : <project name="test" default="build"> <!--Needed for antcontrib--> <taskdef resource="net/sf/antcontrib/antcontrib.properties"/> <target name="build"> <property name="test" value="value_1"/> <property name="production" value="value_2"/> <!--Iterate through every token and call target with parameter dir--> <foreach list="${test},${production}" param="dir" target="create.war"/> </target> <target name="create.war"> <echo message="My path is : ${dir}"/> </target> </project> Output : build: create.war: [echo] My path is : value_1 create.war: [echo] My path is : value_2 BUILD SUCCESSFUL Total time: 0 seconds I hope it helps :) Second solution without using ant contrib. You could encapsulate all your logic into a macrodef and simply call it twice. In any case you would need to write the two parameters at some point in your build file. I don't think there is any way to iterate through properties without using external .jars or BSF languages. <project name="test" default="build"> <!--Needed for antcontrib--> <macrodef name="build.war"> <attribute name="dir"/> <attribute name="target"/> <sequential> <antcall target="@{target}"> <param name="path" value="@{dir}"/> </antcall> </sequential> </macrodef> <target name="build"> <property name="test" value="value_1"/> <property name="production" value="value_2"/> <build.war dir="${test}" target="create.war"/> <build.war dir="${production}" target="create.war"/> </target> <target name="create.war"> <echo message="My path is : ${path}"/> </target> </project> A: I admit that I don't understand the question in detail. Is ${project.stage} the same as the xyz and abc parameters? And why are there two parameters xyz and abc mentioned, when only the word "release" should be replaced? What I know is, that macrodef (docu) is something very versatile and that it might be of good use here: <project name="Foo" default="create.wars"> <macrodef name="createwar"> <attribute name="stage" /> <sequential> <echo message="mkdir dir=@{stage}/release " /> <echo message="war destfile=@{stage}/release/sigma.war" /> </sequential> </macrodef> <target name="create.wars"> <createwar stage="test" /> <createwar stage="production" /> </target> </project> The output will be: create.wars: [echo] mkdir dir=test/release [echo] war destfile=test/release/sigma.war [echo] mkdir dir=production/release [echo] war destfile=production/release/sigma.war Perhaps we can start from here and adapt this example as required.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Improving Image compositing Algorithm c# .NET I was wondering if anyone could shed some light on improvements I can do in making this compositing algorithm faster. What is does is takes 3 images splits them up to get the 1st Images Red Channel, 2nd Images Green channel and the 3rd Images Blue channel and composites them together into 1 new image. Now it works but at an excruciatingly slow pace. The reason i think down to the pixel by pixel processing it has to do on all image components. The process is to : For all images: Extract respective R G and B values -> composite into 1 image -> Save new Image. foreach (Image[] QRE2ImgComp in QRE2IMGArray) { Globals.updProgress = "Processing frames: " + k + " of " + QRE2IMGArray.Count + " frames done."; QRMProgressUpd(EventArgs.Empty); Image RedLayer = GetRedImage(QRE2ImgComp[0]); QRE2ImgComp[0] = RedLayer; Image GreenLayer = GetGreenImage(QRE2ImgComp[1]); QRE2ImgComp[1] = GreenLayer; Image BlueLayer = GetBlueImage(QRE2ImgComp[2]); QRE2ImgComp[2] = BlueLayer; Bitmap composite = new Bitmap(QRE2ImgComp[0].Height, QRE2ImgComp[0].Width); Color Rlayer,Glayer,Blayer; byte R, G, B; for (int y = 0; y < composite.Height; y++) { for (int x = 0; x < composite.Width; x++) { //pixelColorAlpha = composite.GetPixel(x, y); Bitmap Rcomp = new Bitmap(QRE2ImgComp[0]); Bitmap Gcomp = new Bitmap(QRE2ImgComp[1]); Bitmap Bcomp = new Bitmap(QRE2ImgComp[2]); Rlayer = Rcomp.GetPixel(x, y); Glayer = Gcomp.GetPixel(x, y); Blayer = Bcomp.GetPixel(x, y); R = (byte)(Rlayer.R); G = (byte)(Glayer.G); B = (byte)(Blayer.B); composite.SetPixel(x, y, Color.FromArgb((int)R, (int)G, (int)B)); } } Globals.updProgress = "Saving frame..."; QRMProgressUpd(EventArgs.Empty); Image tosave = composite; Globals.QRFrame = tosave; tosave.Save("C:\\QRItest\\E" + k + ".png", ImageFormat.Png); k++; } For reference here is the red channel filter method relatively the same for blue and green: public Image GetRedImage(Image sourceImage) { Bitmap bmp = new Bitmap(sourceImage); Bitmap redBmp = new Bitmap(sourceImage.Width, sourceImage.Height); for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { Color pxl = bmp.GetPixel(x, y); Color redPxl = Color.FromArgb((int)pxl.R, 0, 0); redBmp.SetPixel(x, y, redPxl); } } Image tout = (Image)redBmp; return tout; } A: Move these Bitmap Rcomp = new Bitmap(QRE2ImgComp[0]); Bitmap Gcomp = new Bitmap(QRE2ImgComp[1]); Bitmap Bcomp = new Bitmap(QRE2ImgComp[2]); outside the for-loops! Other very important points: * *avoid using GetPixel - it is VERY SLOW! *Checkout LockBits etc. - this is how pixel-level access is usually done in .NET *Consider using a 3rd-party library (free or commercial)... several have some optimized method built-in to do what you are trying to achieve... A: I totally agree with the points Yahia listed in his answer to improve performance. I'd like to add one more point regarding performance. You could use the Parallel class of the .Net Framework to parallelize the execution of your for loops. The following example makes use of the LockBits method and the Parallel class to improve performance (assuming 32 bits per pixel (PixelFormat.Format32bppArgb)): public unsafe static Bitmap GetBlueImagePerf(Image sourceImage) { int width = sourceImage.Width; int height = sourceImage.Height; Bitmap bmp = new Bitmap(sourceImage); Bitmap redBmp = new Bitmap(width, height, bmp.PixelFormat); BitmapData bd = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb); BitmapData bd2 = redBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb); byte* source = (byte*)bd.Scan0.ToPointer(); byte* target = (byte*)bd2.Scan0.ToPointer(); int stride = bd.Stride; Parallel.For(0, height, (y1) => { byte* s = source + (y1 * stride); byte* t = target + (y1 * stride); for (int x = 0; x < width; x++) { // use t[1], s[1] to access green channel // use t[2], s[2] to access red channel t[0] = s[0]; t += 4; // Add bytes per pixel to current position. s += 4; // For other pixel formats this value is different. } }); bmp.UnlockBits(bd); redBmp.UnlockBits(bd2); return redBmp; } public unsafe static void DoImageConversion() { Bitmap RedLayer = GetRedImagePerf(Image.FromFile("image_path1")); Bitmap GreenLayer = GetGreenImagePerf(Image.FromFile("image_path2")); Bitmap BlueLayer = GetBlueImagePerf(Image.FromFile("image_path3")); Bitmap composite = new Bitmap(RedLayer.Width, RedLayer.Height, RedLayer.PixelFormat); BitmapData bd = composite.LockBits(new Rectangle(0, 0, RedLayer.Width, RedLayer.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); byte* comp = (byte*)bd.Scan0.ToPointer(); BitmapData bdRed = RedLayer.LockBits(new Rectangle(0, 0, RedLayer.Width, RedLayer.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); BitmapData bdGreen = GreenLayer.LockBits(new Rectangle(0, 0, RedLayer.Width, RedLayer.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); BitmapData bdBlue = BlueLayer.LockBits(new Rectangle(0, 0, RedLayer.Width, RedLayer.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); byte* red = (byte*)bdRed.Scan0.ToPointer(); byte* green = (byte*)bdGreen.Scan0.ToPointer(); byte* blue = (byte*)bdBlue.Scan0.ToPointer(); int stride = bdRed.Stride; Parallel.For(0, bdRed.Height, (y1) => { byte* r = red + (y1 * stride); byte* g = green + (y1 * stride); byte* b = blue + (y1 * stride); byte* c = comp + (y1 * stride); for (int x = 0; x < bdRed.Width; x++) { c[0] = b[0]; c[1] = g[1]; c[2] = r[2]; r += 4; // Add bytes per pixel to current position. g += 4; // For other pixel formats this value is different. b += 4; // Use Image.GetPixelFormatSize to get number of bits per pixel c += 4; } }); composite.Save("save_image_path", ImageFormat.Jpeg); } Hope, this answer gives you a starting point for improving your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multidimensional Binding in WPF ListView I have the following Data-Structure: class XItem { public string Name {get;set;} public int Position { get;set;} ... } class MyItemList { public List<XItem> Items{get;set;} ... } Now i want to bind a List of MyItemLists to a WPF-ListView. I want to have a ListViewItem for every XItem. But i cannot bind it directly, because the Items-Property is a List of XItems. Is it possible to realize this without restructuring my Datasource? thanks A: myList.DataSource = myListOfMyItemList.SelectMany(i=>i.Items); You can use SelectMany of Linq to flatten your list before assigning it to datasource property of list. If you're using MVVM then you can have a property of your ViewModel return a flatten version of the List by using code as mentioned above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: XDocument null reference on object that isnt null I have an xml (called xdoc) file like the following: <Root> <ItemContainer> <Item> <Item> <Item> <Item> </ItemContainer> </Root> if i do the following XElement xel = xdoc.Element("ItemContainer"); As far as i understand, i should get back a reference to to my ItemContainer node element, but i keep getting back null. Ive read the msdn docs for this "Gets the first (in document order) child element with the specified XName. " as far as i can see, ItemContainer is the first child element with the specified name. What am i missing? A: Do : XElement xel = xdoc.Root.Element("ItemContainer"); Because, the <Root> has also to be handled. XElement xel = xdoc.Element("Root").Element("ItemContainer"); should also work A: I assume xdoc is of type XDocument. The only child element of the document is the root node <Root>. Because of this, your code should look like this: XElement xel = xdoc.Root.Element("ItemContainer"); A: Have you tried ... xdoc.Root.Element("ItemContainer"); The root element is the first element A: As others explained, the only child of an XDocument is the root element, so to get to a child of the root, you have to get through the root: XElement xel = xdoc.Root.Element("ItemContainer"); Alternatively, you can use XElement.Load(), if you don't need to access things like XML declaration. It returns the root element directly: XElement root = XElement.Load(@"c:\projects\gen\test_xml.xml"); XElement xel = root.Element("ItemContainer");
{ "language": "en", "url": "https://stackoverflow.com/questions/7552655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert float to String and String to float in Java How could I convert from float to string or string to float? In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated. String valueFromTable = "25"; Float valueCalculated =25.0; I tried from float to string: String sSelectivityRate = String.valueOf(valueCalculated); but the assertion fails A: You can try this sample of code: public class StringToFloat { public static void main (String[] args) { // String s = "fred"; // do this if you want an exception String s = "100.00"; try { float f = Float.valueOf(s.trim()).floatValue(); System.out.println("float f = " + f); } catch (NumberFormatException nfe) { System.out.println("NumberFormatException: " + nfe.getMessage()); } } } found here A: Using Java’s Float class. float f = Float.parseFloat("25"); String s = Float.toString(25.0f); To compare it's always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. "25" != "25.0" != "25.00" etc.) A: Float to string - String.valueOf() float amount=100.00f; String strAmount=String.valueOf(amount); // or Float.toString(float) String to Float - Float.parseFloat() String strAmount="100.20"; float amount=Float.parseFloat(strAmount) // or Float.valueOf(string) A: I believe the following code will help: float f1 = 1.23f; String f1Str = Float.toString(f1); float f2 = Float.parseFloat(f1Str); A: This is a possible answer, this will also give the precise data, just need to change the decimal point in the required form. public class TestStandAlone { /** * This method is to main * @param args void */ public static void main(String[] args) { // TODO Auto-generated method stub try { Float f1=152.32f; BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP); System.out.println("f1 --> "+f1); String s1=roundfinalPrice.toPlainString(); System.out.println("s1 "+s1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Output will be f1 --> 152.32 s1 152.32 A: If you're looking for, say two decimal places.. Float f = (float)12.34; String s = new DecimalFormat ("#.00").format (f); A: well this method is not a good one, but easy and not suggested. Maybe i should say this is the least effective method and the worse coding practice but, fun to use, float val=10.0; String str=val+""; the empty quotes, add a null string to the variable str, upcasting 'val' to the string type. A: There are three ways to convert float to String. * *"" + f *Float.toString(f) *String.valueOf(f) There are two ways Convert String to float * *Float.valueOf(str) *Float.parseFloat(str); Example:- public class Test { public static void main(String[] args) { System.out.println("convert FloatToString " + convertFloatToString(34.0f)); System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f)); System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f)); float f = Float.valueOf("23.00"); } public static String convertFloatToString(float f) { return "" + f; } public static String convertFloatToStrUsingFloatMethod(float f) { return Float.toString(f); } public static String convertFloatToStrUsingStringMethod(float f) { return String.valueOf(f); } } A: String str = "1234.56"; float num = 0.0f; int digits = str.length()- str.indexOf('.') - 1; float factor = 1f; for(int i=0;i<digits;i++) factor /= 10; for(int i=str.length()-1;i>=0;i--){ if(str.charAt(i) == '.'){ factor = 1; System.out.println("Reset, value="+num); continue; } num += (str.charAt(i) - '0') * factor; factor *= 10; } System.out.println(num); A: To go the full manual route: This method converts doubles to strings by shifting the number's decimal point around and using floor (to long) and modulus to extract the digits. Also, it uses counting by base division to figure out the place where the decimal point belongs. It can also "delete" higher parts of the number once it reaches the places after the decimal point, to avoid losing precision with ultra-large doubles. See commented code at the end. In my testing, it is never less precise than the Java float representations themselves, when they actually show these imprecise lower decimal places. /** * Convert the given double to a full string representation, i.e. no scientific notation * and always twelve digits after the decimal point. * @param d The double to be converted * @return A full string representation */ public static String fullDoubleToString(final double d) { // treat 0 separately, it will cause problems on the below algorithm if (d == 0) { return "0.000000000000"; } // find the number of digits above the decimal point double testD = Math.abs(d); int digitsBeforePoint = 0; while (testD >= 1) { // doesn't matter that this loses precision on the lower end testD /= 10d; ++digitsBeforePoint; } // create the decimal digits StringBuilder repr = new StringBuilder(); // 10^ exponent to determine divisor and current decimal place int digitIndex = digitsBeforePoint; double dabs = Math.abs(d); while (digitIndex > 0) { // Recieves digit at current power of ten (= place in decimal number) long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10; repr.append(digit); --digitIndex; } // insert decimal point if (digitIndex == 0) { repr.append("."); } // remove any parts above the decimal point, they create accuracy problems long digit = 0; dabs -= (long)Math.floor(dabs); // Because of inaccuracy, move to entirely new system of computing digits after decimal place. while (digitIndex > -12) { // Shift decimal point one step to the right dabs *= 10d; final var oldDigit = digit; digit = (long)Math.floor(dabs) % 10; repr.append(digit); // This may avoid float inaccuracy at the very last decimal places. // However, in practice, inaccuracy is still as high as even Java itself reports. // dabs -= oldDigit * 10l; --digitIndex; } return repr.insert(0, d < 0 ? "-" : "").toString(); } Note that while StringBuilder is used for speed, this method can easily be rewritten to use arrays and therefore also work in other languages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "230" }
Q: Draggable Div with a textarea in it. Drag problem I have a div with a textarea in it. The main div is draggable and works fine, but I'm unable to drag the div while clicking on the textarea in it. Is there a way to drag the div even if I drag it from the textarea inside the div? Here is how I make my div draggable $('.speech_bubble').draggable( { containment: $('#dropHere') }); Thank you A: It is becuase of the cancel option of the draggable. The default is ':input,option', that means that starting the drag from the textarea will be cancelled. Try playing with that option. A: Try adding the following styles: div { padding-bottom:20px; } textarea { width:100%; height:100% } You can then drag the textarea while you drag on the bottom side of the div tag. A: You can try creating a screen (Invisible div) over the textarea using the onmouseover event, then detect if the user wants to edit the text by removing the screen via double click event. A: I know this is a very old question, but I thought it would be better to answer the exact question I had just been working on (i.e. instead of creating a new one). The answer refers to dioslaska's solution of clearing the cancel attribute with adding one additional .focus() call on the intended textarea inside your event handler (say a click). I used a double click in my solution to differentiate from simply moving my object. For selection: Currently it looks like there is a bug (http://bugs.jqueryui.com/ticket/4986). For a workaround, in the event handler disable the draggable by using destroy, and in the blur() (or other disabling event handler) function recreate the draggable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get Application information from an APK using PHP script How can I get the versionCode, versionName, application icon and application label from an APK with PHP A: I'm not that familiar with php so I can't provide any code, but the idea is: * *unzip the APK file (since it's "nomal" zip format) *open the AndroidManifest.xml and *parse the <manifest> tag for android:versionCode and android:versionName A: If I'm not wrong, APKs are simply zip files. And android packages will have some sort of XML file that will mention the version information. In PHP, you can unzip as well as read XMLs. A: As you might know an APK is a simple zip formated archive with it's metadata in XML format. Try and unzip some apks and see which files have the information you need. This can all be easily done in PHP. A: Well, It is correct that the apk is in fact a zip-file and that is easy to unzip. However the manifest xml is not in standard xml format. It is some kind of propitiatory Android format. You can use apktool to unpack the xml, but it is in Java and not very fun if you don't have Java on the server. There is also a Python Library available, AXMLParsePY Then we have AXmlPrinter2, also written in Java I am myself looking for a PHP library and have given up. Now looking for something lightweight I can convert from some other language.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Are empty interfaces code smell? I have a function that returns same kind of objects (query results) but with no properties or methods in common. In order to have a common type I resorted using an empty interface as a return type and "implemented" that on both. That doesn't sound right of course. I can only console myself by clinging to hope that someday those classes will have something in common and I will move that common logic to my empty interface. Yet I'm not satisfied and thinking about whether I should have two different methods and conditionally call next. Would that be a better approach? I've been also told that .NET Framework uses empty interfaces for tagging purposes. My question is: is an empty interface a strong sign of a design problem or is it widely used? EDIT: For those interested, I later found out that discriminated unions in functional languages are the perfect solution for what I was trying to achieve. C# doesn't seem friendly to that concept yet. EDIT: I wrote a longer piece about this issue, explaining the issue and the solution in detail. A: You state that your function "returns entirely different objects based on certain cases" - but just how different are they? Could one be a stream writer, another a UI class, another a data object? No ... I doubt it! Your objects might not have any common methods or properties, however, they are probably alike in their role or usage. In that case, a marker interface seems entirely appropriate. A: If not used as a marker interface, I would say that yes, this is a code smell. An interface defines a contract that the implementer adheres to - if you have empty interfaces that you don't use reflection over (as one does with marker interfaces), then you might as well use Object as the (already existing) base type. A: You answered your own question... "I have a function that returns entirely different objects based on certain cases."... Why would you want to have the same function that returns completely different objects? I can't see a reason for this to be useful, maybe you have a good one, in which case, please share. EDIT: Considering your clarification, you should indeed use a marker interface. "completely different" is quite different than "are the same kind". If they were completely different (not just that they don't have shared members), that would be a code smell. A: Although it seems there exists a design pattern (a lot have mentioned "marker interface" now) for that use case, i believe that the usage of such a practice is an indication of a code smell (most of the time at least). As @V4Vendetta posted, there is a static analysis rule that targets this: http://msdn.microsoft.com/en-us/library/ms182128(v=VS.100).aspx If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types. If this identification will occur at run time, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the properties of the attribute, to identify the target types. If the identification must occur at compile time, then it is acceptable to use an empty interface. This is the quoted MSDN recommendation: Remove the interface or add members to it. If the empty interface is being used to label a set of types, replace the interface with a custom attribute. This also reflects the Critique section of the already posted wikipedia link. A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot "unimplement" a marker. In the example given, if you create a subclass that you do not want to serialize (perhaps because it depends on transient state), you must resort to explicitly throwing NotSerializableException (per ObjectOutputStream docs). A: As many have probably already said, an empty interface does have valid use as a "marker interface". Probably the best use I can think of is to denote an object as belonging to a particular subset of the domain, handled by a corresponding Repository. Say you have different databases from which you retrieve data, and you have a Repository implementation for each. A particular Repository can only handle one subset, and should not be given an instance of an object from any other subset. Your domain model might look like this: //Every object in the domain has an identity-sourced Id field public interface IDomainObject { long Id{get;} } //No additional useful information other than this is an object from the user security DB public interface ISecurityDomainObject:IDomainObject {} //No additional useful information other than this is an object from the Northwind DB public interface INorthwindDomainObject:IDomainObject {} //No additional useful information other than this is an object from the Southwind DB public interface ISouthwindDomainObject:IDomainObject {} Your repositories can then be made generic to ISecurityDomainObject, INorthwindDomainObject, and ISouthwindDomainObject, and you then have a compile-time check that your code isn't trying to pass a Security object to the Northwind DB (or any other permutation). In situations like this, the interface provides valuable information regarding the nature of the class even if it does not provide any implementation contract.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: using long polling with facebook graph API (for "real-time" notifications) I'm looking into implementing a web page to show the user's news feed with real-time updates, without using simple polling to the facebook servers. after browsing through similar questions: * *How to implement facebook line notification? *How does facebook, gmail send the real time notification? *Facebook notification system: Is it polling? As I understand - long polling (see Comet model) is the most preferable way for me to achieve "push"-like events for when a new post is added to a user's feed. I'm using javascript, on IE browser (6 and above), and the page is actually stored locally, and not on a server. I'm aware of the real-time updates subscription graph API, but as I mentioned, my page will run locally, not on a server (not even localhost), that's why long polling seems so attractive at the moment. My question is - does anyone know if and how long polling (or any other Comet model alternative) is available to use via the Facebook API? or maybe any other suggestions? Thanks. A: I think the only long polling available is for the chat API. Otherwise you're stuck with either real-time updates or using a javascript timer to poll.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How pure and lazy can Scala be? This is just one of those "I was wondering..." questions. Scala has immutable data structures and (optional) lazy vals etc. How close can a Scala program be to one that is fully pure (in a functional programming sense) and fully lazy (or as Ingo points out, can it be sufficiently non-strict)? What values are unavoidably mutable and what evaluation unavoidably greedy? A: Feel free to keep things immutable. On the other hand, there's no side effect tracking, so you can't enforce or verify it. As for non-strictness, here's the deal... First, if you choose to go completely non-strict, you'll be forsaking all of Scala's classes. Even Scalaz is not non-strict for the most part. If you are willing to build everything yourself, you can make your methods non-strict and your values lazy. Next, I wonder if implicit parameters can be non-strict or not, or what would be the consequences of making them non-strict. I don't see a problem, but I could be wrong. But, most problematic of all, function parameters are strict, and so are closures parameters. So, while it is theoretically possible to go fully non-strict, it will be incredibly inconvenient. A: Regarding lazyness - currently, passing a parameter to a method is by default strict: def square(a: Int) = a * a but you use call-by-name parameters: def square(a: =>Int) = a * a but this is not lazy in the sense that it computes the value only once when needed: scala> square({println("calculating");5}) calculating calculating res0: Int = 25 There's been some work into adding lazy method parameters, but it hasn't been integrated yet (the below declaration should print "calculating" from above only once): def square(lazy a: Int) = a * a This is one piece that is missing, although you could simulate it with a local lazy val: def square(ap: =>Int) = { lazy val a = ap a * a } Regarding mutability - there is nothing holding you back from writing immutable data structures and avoid mutation. You can do this in Java or C as well. In fact, some immutable data structures rely on the lazy primitive to achieve better complexity bounds, but the lazy primitive can be simulated in other languages as well - at the cost of extra syntax and boilerplate. You can always write immutable data structures, lazy computations and fully pure programs in Scala. The problem is that the Scala programming model allows writing non pure programs as well, so the type checker can't always infer some properties of the program (such as purity) which it could infer given that the programming model was more restrictive. For example, in a language with pure expressions the a * a in the call-by-name definition above (a: =>Int) could be optimized to evaluate a only once, regardless of the call-by-name semantics. If the language allows side-effects, then such an optimization is not always applicable. A: Scala can be as pure and lazy as you like, but a) the compiler won't keep you honest with regards to purity and b) it will take a little extra work to make it lazy. There's nothing too profound about this; you can even write lazy and pure Java code if you really want to (see here if you dare; achieving laziness in Java requires eye-bleeding amounts of nested anonymous inner classes). Purity Whereas Haskell tracks impurities via the type system, Scala has chosen not to go that route, and it's difficult to tack that sort of thing on when you haven't made it a goal from the beginning (and also when interoperability with a thoroughly impure language like Java is a major goal of the language). That said, some believe it's possible and worthwhile to make the effort to document effects in Scala's type system. But I think purity in Scala is best treated as a matter of self-discipline, and you must be perpetually skeptical about the supposed purity of third-party code. Laziness Haskell is lazy by default but can be made stricter with some annotations sprinkled in your code... Scala is the opposite: strict by default but with the lazy keyword and by-name parameters you can make it as lazy as you like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: javascript - changing embedded objects src problem for Firefox (no problem for IE9 or Opera) this will be my first question. Sorry for mistakes. Following code works in IE9 and Opera but does not work in Firefox. In Firefox, I am clicking another link and going back to the page that contains the video then video is starting. Otherwise, video is not starting. (again not starting when refreshing the page) function output_video_URL(id, local_path_of_video, remote_path_of_video) { var http_check = getHTTPObject(); var local_URL = local_server + local_path_of_video; var remote_URL = remote_server + remote_path_of_video; http_check.open("HEAD", local_path_of_video); http_check.onreadystatechange = handleHttpResponse_check; http_check.send(null); function handleHttpResponse_check() { if (http_check.readyState == 4){ if (http_check.status == 200) { var video = document.getElementById(id); video.src = local_URL; video.parentNode.Filename = local_URL; } else if (http_check.status == 404) { var video = document.getElementById(id); video.src = remote_URL; video.parentNode.Filename = remote_URL; } } } } HTML: <object width="364" height="266" classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" id="mediaplayer1"> <param name="Filename" value="filmler/canakkeleklipkucuk.wmv" /> <param name="AutoStart" value="True" /> <param name="ShowControls" value="false" /> <param name="ShowStatusBar" value="false" /> <param name="ShowDisplay" value="false" /> <param name="AutoRewind" value="false" /> <embed id = "canakkeleklip" type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/MediaPlayer/" width="320" height="240" src="filmler/canakkeleklipkucuk.wmv" autostart="True" showcontrols="false" showstatusbar="false" showdisplay="false" autorewind="false"> </embed> </object> <script type = "text/javascript"> output_video_URL('canakkeleklip', 'videos/canakkeleklipkucuk.wmv', 'filmler/canakkeleklipkucuk.wmv') </script> A: The problem is with how you try to set the Filename property. It's not an attribute of the object element, it's an element inside it. (The reason that it works in IE and Opera is that they use the embed element, not the object element.) Assuming that the Filename parameter is the first one, you can use this to set it: video.parentNode.getElementsByTagName('param')[0].value = local_URL; If you don't know the order of the parameter elements, you would have to loop the child nodes and check for the one with the right name attribute. Edit: However, even when actually changing the the parameter value it won't work, as the object is already created. See Is it possible to change the file path of the video using javascript?
{ "language": "en", "url": "https://stackoverflow.com/questions/7552690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check if client has .net 3.5 Client Profile (or any version of .Net) from web site? Is there anyway to check from a website if a client has a specific version of .Net installed and which one it is so you can offer them different downloads based on it? A: Some browsers include this information in the User Agent header, eg. from the log files on a machine with IE8 installed: Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+6.0;+Trident/4.0;+SLCC1;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.30729;+.NET+CLR+3.5.30729;+.NET4.0C;+.NET4.0E) However this information is not included in IE9's user agent string. In general: without trying something on the client you cannot be sure. A: You can parse the user agent. There is MSDN page that describes the format, especially, take a look at the .NET CLR <version> token. However, you can guarantee the information will be present and accurate : non MS browser, customized user agent string, paranoid user agent, etc. can be factors for users to remove such information. [Edit] Probably not an easy things to do, but you can use a setup bootstrapper which will detect the installed version to download the actual setup. Microsoft use this technique for some of their products web installers. A: I discovered this issue recently and IE9 when standards mode doesn't include the CLR versions in the User Agent, as noted in Richard's answer. It seems the only way to get this information server-side is setting compatibility view mode. Alternatively if you wish to preserve standards mode then you will need to get the information via java script. if (navigator.userAgent.match(/\.NET CLR [234].[05]/)) { // do stuff depending on presence } You can adjust the version numbers or drop off that bit depending on your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: continuous scolling ticker - avoiding jumping? I'm trying to get an infinite scrolling ticker type of thing working smoothly. To make it continuous I am removing the first element and replacing it at the back once it is out of view, but this makes the container element jump a little in the amount of time it takes to reposition the element. see here: http://jsfiddle.net/rFwfN/ is there anyway around this? is there a better way of making this scrolling element continuous? I thought of cloning the set of elements so there are two, so making the dom switch less frequent. A: http://jsfiddle.net/rFwfN/6/ You need to reset position before injecting: var scrollone = function() { $('carousel').tween('left',[0, (60 *-1)]); $('carousel').setStyle('left', '0px').getFirst().inject($('carousel')); } A: $('carousel').getFirst().inject($('carousel')); $('carousel').tween('left',[0, (60 *-1)]); Not sure how to do with mootools. Tween must stop before element injection and begin once injection is done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Partitioning and Unix Timestamp I've just started reading on MySQL partitions, they kind of look too good to be true, please bear with me. I have a table which I would like to partition (which I hope would bring better performance). This is the case / question: We have a column which stores Unix timestamp values, is it possible to partition the table in that way, that based on the unix timestamp the partitions are separated on a single date? Or do I have to use range based partitioning by defining the ranges before? Cheers A: You can do whatever you feel like, See: http://dev.mysql.com/doc/refman/5.5/en/partitioning-types.html And example of partitioning by unix_timestamp would be: ALTER TABLE table1 PARTITION BY KEY myINT11timestamp PARTITIONS 1000; -- or ALTER TABLE table1 PARTITION BY HASH (myINT11timestamp/1000) PARTITIONS 10; Everything you wanted to know about partitions in MySQL 5.5: http://dev.mysql.com/tech-resources/articles/mysql_55_partitioning.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7552700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: facebook status I am trying to use the following code to post a message on facebook wall (Facebook C# SDK - https://github.com/facebook/csharp-sdk) Facebook.FacebookAPI api = new Facebook.FacebookAPI("my token"); JSONObject me = api.Get("/me"); var userId = me.Dictionary["id"].String; Dictionary<string, string> postArgs = new Dictionary<string, string>(); postArgs["message"] = "Hello, world!"; api.Post("/" + userId + "/feed", postArgs); I am able to pull the user profile information but while posting a message throwing an error message like below. The remote server returned an error: (403) Forbidden. Description: An unhanded exception occurred during the execution of the current web request. Exception Details: Facebook.FacebookAPIException: The remote server returned an error: (403) Forbidden. What could be the issue ? A: Make sure userId is the proper value and make sure you have publish_stream extended permissions granted from the user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: More comfortable way renaming a Class in Eclipse using CDT for C++? I'm wondering if there's an easier way using CDT for this refactoring task. Not only a simple renaming, also a rename of header and source files, correcting all #include statements, rename member-attributes in other classes and so on. Don't know if it's possible or if one has to fumble around in all project files, or is there an extern tool which is useful for this purpose? A: The Alt+Shift+R does everything except it doesn't change the filenames of .cpp and .h files. Everything else is done by this operation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7552707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ssl client authentication without ssl re-negotiation On client side I have Apache HTTP client on jdk5u22. On server side I have tomcat on jdk6u27. With this setup if I try SSL Client authentication (2 way SSL) then it cause "javax.net.ssl.SSLHandshakeException: Insecure renegotiation is not allowed" on the server and handshake fails. It succeeds if I set system properties sun.security.ssl.allowUnsafeRenegotiation=true and sun.security.ssl.allowLegacyHelloMessages=true on server. As per the link http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html this is coz JRE6u27 has the RFC 5746 implementation and JRE5u26 below doesnt have this and so both are incompatible. Unfortunately 5u22 is the latest freely available java 5 version. So I want to know if it is possible to have SSL client authentication without ssl re-negotiation. Regards, Litty Preeth A: As per the redhat site https://access.redhat.com/kb/docs/DOC-20491#Renegotiations_disabled_in_Apache_Tomcat : Tomcat may ask the client to renegotiate in certain configurations using client certificate authentication, for example, configurations where: A client certificate is not required on the initial connection, such as when: 1. The clientAuth attribute of the HTTPS connector using JSSE is set to false. Or The SSLVerifyClient attribute of the HTTPS connector using OpenSSL is set to none. AND 2. A web application specifies the CLIENT-CERT authentication method in the login-config section of the application's web.xml file. So to avoid re-negotiation in tomcat just make the whole site secure and not just a part of it by setting clientAuth="true" for ssl . Hope this helps someone. Regards, Litty
{ "language": "en", "url": "https://stackoverflow.com/questions/7552710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: iphone: how to detect last caller number programmatically? Is there any way to detect last caller number & call duration on iPhone, I am able to get all notification (Core Telephony) but don't know how to get caller number. A: You can't, the API will not allow you to do this. I think apple will never allow this due to privacy concerns. A: According to api you cant do it... but here something which might help you ... though I haven't tried it myself... http://iosstuff.wordpress.com/2011/08/19/accessing-iphone-call-history/ A: Apple officially don't allow.You cann't access the database of the other application then your one. A: You can use this if ([name isEqualToString:@"kCTCallIdentificationChangeNotification"]) { // CTCallCenter *center = [[CTCallCenter alloc] init]; // center.callEventHandler = ^(CTCall *call) { // NSLog(@”call:%@”, [call description]); // }; //NSDictionary *info = (NSDictionary *)userInfo; CTCall *call = (CTCall *)[info objectForKey:@"kCTCall"]; NSString *caller = CTCallCopyAddress(NULL, call); NSLog(@"caller:%@",caller); //CTCallDisconnect(call); /* or one of the following functions: CTCallAnswer CTCallAnswerEndingActive CTCallAnswerEndingAllOthers CTCallAnswerEndingHeld */ //if ([caller isEqualToString:@"+1555665753"]) if ([caller isEqualToString:@"+918740061911"]) { NSLog(@"disconnecting call"); //disconnect this call CTCallDisconnect(call); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Display an image in silverlight datagrid How would i display an image in my silverlight datagrid from the database using WCF please help. thanks in advance. A: like this: <data:DataGridTemplateColumn Width="25"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Width="20" Stretch="Fill" Source="../Images/img.png" /> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> A: XAML: <sdk:DataGridTemplateColumn Header="My Image"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Height="150" HorizontalAlignment="Left" Margin="3,12,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="200" Source="{Binding Image1}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> </sdk:DataGrid.Columns> </sdk:DataGrid> Code Behind public partial class MainPage: UserControl { public MainPage() { InitializeComponent(); ObservableCollection MyListItem = new ObservableCollection(); MyListItem.Add(new ListItems {Image1 = new BitmapImage(new Uri ("/SilverlightApplication2;component/Images/Capture.JPG",UriKind.Relative)) }); dataGrid1.ItemsSource = MyListItem; } } public class ListItems { public BitmapImage Image1 { get; set; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7552717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }