text
stringlengths
8
267k
meta
dict
Q: How to generate EJB from WSDL I know how to use @WebService and @Stateless annotation to write an EJB and expose it into a WebService. But because we're try to use other tools to generate WSDL first and then create Java code. I can use WebLogic's WSDLC to generate a service code from WSDL. But the problem is that the code generated by WSDLC is not EJB. Is there any suggestion to do WSDL -> EJB? If it's possible, I prefer not to use AXIS. A: I am working in EJB and Web Services for quite some time and did not come across any such tools. Logically it makes sense, * *Web services themselves are not components but as a a facade for some business component (EJB in this case). They are decoupled from each other. *WSDL base code generators will generate these facade or annotated Pojos. *Whether that POJO/Facade uses EJB or any other services to delegate further, entirely depend on the implementation. This is the reason I feel there wont be such tool to generate EJB directly from WSDL. But again I am limited by my experience. I would be curious to know if such tool exists. EDIT: Just FYI, there is WSDL EJB Extension. But it needs existing EJBs to bind its operation to WSDL. (It does not create EJB code) A: Well, not that the new EJB 3.1 isn't A LOT better than the old versions, but I still preffer to use Apache CXF for web-services implementation: http://cxf.apache.org/ It has a nice wsdl2java tool (which can be also used as a maven plugin): http://cxf.apache.org/docs/wsdl-to-java.html which takes your WSDL file, validates it, and then generates very clean Java template code for the implementation of your web-service: you have JAXB classes for marshalling the requests and responses, a very simple (coded to interface) webservice implementation class with methods for each ws operation (which methods you must ofcourse implement yourself with your business logic), and optionally a nice Java client stub that another Java app can use to access your service easily. Even without the client stub, you still get a nice clean and standard implementation which is basicaly just Java classes, no EJB container needed to start (or test) your web service. A: SAP NetWeaver Developer Studio supports to generate a EJB WebService from WSDL. I just try it. http://help.sap.com/saphelp_nw72/helpdata/en/46/7f2fef88190ad3e10000000a11466f/content.htm And I also check the code generated by Apache CXF, WebLogic wsdlc and SAP. They are similar. And if you use EJB 3, you can just add @Stateless annotation to the code generated by Apache CXF or WebLogic to let it be a EJB. But I think it's not a good idea to expose business EJB to a WebService directly. There should be a service layer. The benefit to use EJB as a service layer is that it can use injection to access other EJB easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to insert and retrieve image from SQL Server? I have written code to insert an Image in SQL server but it throws an exception: String or binary data would be truncated. The statement has been terminated. Here is my Code for insert image: FileStream imageStream = new FileStream(CvVariables.IMAGE_PATH, FileMode.Open, FileAccess.Read); int fileLangth = (int)imageStream.Length; byte[] imageInBytes = new byte[fileLangth]; imageStream.Read(imageInBytes, 0, (int)fileLangth); Cv_Customer_Information addNewCustomer = new Cv_Customer_Information { UserID = this.NewCustomerTextUserName.Text, UserImage =new System.Data.Linq.Binary(imageInBytes), Date = this.NewCustomerDate.SelectedDate.ToString(), Name = this.NewCustomerTextBoxName.Text, Phone = this.NewCustomerTextBoxPhone.Text, Email = this.NewCustomerTextBoxEmail.Text, NationalID = this.NewCustomerTextBoxNationalID.Text, Address = this.NewCustomerTextBoxAddress.Text }; singupDataContext.Cv_Customer_Informations.InsertOnSubmit(addNewCustomer); singupDataContext.SubmitChanges(); I also don`t understand how to retrieve images from SQL Server? update: I use image Data Type in UserImage field and I am working with WPF A: Well, this error means that the data of one of your fields (string or binary) is longer than the database definition of the column in which it will be stored. This can be for example your username. If the database is a varchar(8) and you try to assign a name of 10 characters, you will get this error. From the errormessage you cannot deduct what field is causing the error. It can be any string or your Binary data. Crosschek the input with the database definition to find the field/columns that is causing the error. Solution: provide smaller data or increase the length in the database. A: The problem here is that the column that is holding your image is not big enough to hold the image you are inserting. This means that you will have to increase its length in order to be able to insert the object you want to. A: I haven't checked the code but I remember that I used something similar. Image image; using (MemoryStream stream = new MemoryStream(imageByteArray,0,imageByteArray.Length)) { stream.Write(imageByteArray,0,imageByteArray.Length); image = Image.FromStream(stream,true); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Package-private class within a .java file - why is it accessible? Consider the following code, where the HelloWorld class has default or package-private access: class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } } And assume that the above code is saved in a file called HelloWorld.java. So my question is: since HelloWorld is now a package-private class, how does it work? The main() method should not be visible or accessible across packages, am I right? It makes perfect sense to me if the class HelloWorld is declared public. Confusion is only when it is declared with the default package-private access. A: JVM startup is described in §12.1 Virtual Machine Start-Up of the JLS. Note that this chapter says nothing about visibility checks with regards to the class. It only specifies that the main method must be public. This means that there simply is no check for visibility on the class level (which kind-of makes sense as there is no context yet against which to check the visibility: in which "package" is the "caller"?). A: Main method won't be visible to other classes which reside in different packages. But the JVM can see it all. It won't have any difficulty in finding your main method and running it for you. If you want to simulate the access restriction, write another class in a different package and try to call HelloWorld.main and see if the compiler keeps quiet. A: You have not made it very clear, but I assume that your question is why that main method can be run when you type java HelloWorld at the command line. The answer is that the Java Language Specification simply does not require the class that contains the main method to be public. Access modifiers are a language mechanism mainly intended to help maintainability via encapsulation. They're not really a security feature, and certainly not unshakable laws of physics. The JVM startup mechanism simply ignores them. In fact, you can even use a private inner class, and it will still run. A: Probably the designers of JLS decided there is no need to restrict access to main method if you know the class name, while at the first glance it looks counter-intuitive; from the other side - the access could be always got via reflection so it couldn't be treated as a security hole... Anyway e.g. by creating facade to a package-private class we access that one indirectly... So the protection is rather from incorrect usage and to allow further changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTML DOM w3schools clarification just reading the W3schools HTML DOM tutorial. There's a paragraph that makes no sense to me. The bit that doesn't make sense to me is: A common error in DOM processing is to expect an element node to contain text. However, the text of an element node is stored in a text node. In this example: <title>DOM Tutorial</title>, the element node <title>, holds a text node with the value "DOM Tutorial". "DOM Tutorial" is not the value of the <title> element! However, in the HTML DOM the value of the text node can be accessed by the innerHTML property. Ok, what? That sounds exactly the opposite of what I though. Thanks A: When a markup document is converted into a DOM, you end up with a tree of nodes. There are several types of nodes, including elements, text and comments. Nodes have properties. e.g. an HTMLInputNode will have a value property that maps on to its current value. Any HTMLElementNode will have a style property through which the CSS properties defined via the style attribute can be accessed. Likewise, it will also have a className property that maps onto the class attribute. When you have <title>DOM Tutorial</title> you have a HTMLTitleNode containing a TextNode. To get the text DOM Tutorial you should access the TextNode and then read its data property. myTitle.firstChild.data And then W3Schools muddies the water by mentioning innerHTML. innerHTML is a property (although not a standard DOM property (I think HTML 5 is in the process of defining it)) of HTMLElementNodes which gives you a serialisation of the HTML contents of an element (but not the element itself). Since there is only a TextNode inside a title element, you end up with plain text there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: segfault when using mmap I'm trying to use mmap for the first time to store a tree object with a lot of data in it. The tree class basically contains a pointer to the root of class Node, and each Node instance has an array of pointers to it's children. I think mmap is doing what it is supposed to, because I can access the tree's constant members, but when I try to access the pointer to the root I get a segfault. Here is how a create a tree with a root node: int main(int argc, char *argv[]) { Tree *map; ... map = (Tree*)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { close(fd); perror("Error mmapping the file"); exit(EXIT_FAILURE); } Node* root = new Node("data"); map->set_root(root); ... } Here is how I access the Tree: int main(int argc, char *argv[]) { int i; int fd; Tree *map; fd = open(FILEPATH, O_RDONLY); if (fd == -1) { perror("Error opening file for reading"); exit(EXIT_FAILURE); } map = (Tree*)mmap(0, FILESIZE, PROT_READ, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { close(fd); perror("Error mmapping the file"); exit(EXIT_FAILURE); } Node* root = map->root(); cout << root->data(); ... The output of root->data() provides a segfault. Can anyone give me a hint to where I'm wrong? Please say if I'm not making my problem clear. Thanks in advance. Mads A: This is a mess. You need to understand how new and delete work before attempting what you are trying to do. Where to start. * *map = (Tree*)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); This just says, treat that bit of memory as if it is a Tree, you've not constructed a tree in that bit of memory. *When you call new, it allocates a Node object, somewhere in memory and you hold a pointer to that in your tree, when it is re-opened elsewhere, the pointer is no longer valid. You need to store all the nodes in your mapped block too... There is no real easy answer to this, except try to understand custom memory allocators. A: When you call mmap(), you are basically just getting a block of raw memory. Thus you can't naively dereference the pointer map without invoking some type of undefined behavior ... simply casting the memory returned from mmap() to type Tree* like you've done does not actually construct a Tree object in the mapped memory. If you wish to construct, or even copy construct a Tree object in the memory returned from mmap, you may want to look into using placement new. For instance, you could do something like the following: void* map; map = mmap(0, FILESIZE, PROT_READ, MAP_SHARED, fd, 0); //...error checking Tree* tree = new(map) Tree(); //placement new syntax That will actually default-construct a Tree object in the memory returned from mmap, and at that point, you can properly use the tree pointer variable in order to further add nodes to the tree. For instance, the following code could now be invoked without creating undefined behavior: Node* root = new Node("data"); tree->set_root(root); With placement new, an actual Tree object is being pointed to by the variable tree, and you can now properly dereference that pointer, as well as any methods associated with that object. One major item to keep in mind though is that when using placement new, you will have to manually call the destructor for your Tree object, and you will have to manually free the memory that you've allocated via mmap() ... you can't call delete on the Tree*. A: This won't work. If root() is a virtual method, you are hosed, as the vtable pointers point to methods in the current process. It might work if you don't call any virtual methods, but it's probably undefined behavior. It's probably better to share data between processes, rather than objects. Let the objects have a handle to the data, and shield the user of the object from the details of decoding the data. Node* root = new Tree(memory_mapped_memory);
{ "language": "en", "url": "https://stackoverflow.com/questions/7634134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Eclipse doesn't recognize android SDK I set android SDK on centos(linux) but then I get when I'm trying to get to Android SDK and AVD Manager in Window menu. Why?? I have the latest ADT plugin, I've tried android_sdk revision 13 and 12, both didn't work. WHY? A: With Windows "X.X" OS, being any variant of the operating system, I had issues such as yours. My best solution short of using Virtual Box / VMWare to run a Linux OS would be to make a guest account with the Lowest Potential Privileges, (Non-Admin, read write only, etc.) and only the account for Development. It is the same basic rule of thumb I always use on Linux, or OS X because you can't screw the environment up. After that, I would try and download everything over. (I am sorry if you do not have a good download speed, but from experience, believe me even a 220/kbps Download speed is a minor inconvenience once you have a Dev. Account set up.) I hope this
{ "language": "en", "url": "https://stackoverflow.com/questions/7634136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Two-dimensional list inside Jquery Template Im having some trouble with Jquery Templates and can't seem to figure out what's wrong. It's probally the way I'm using an each inside an each (Couldn't find any good examples how to do this). The error appers when running the .tmpl function. $("#calendarListTemplate").tmpl(json) and says: Uncaught SyntaxError: Unexpected identifier at Line 1 of jquery.tmpl.min.js Here's the template: <script id="calendarListTemplate" type="text/x-jquery-tmpl"> ${{each eventDayGroups}} <li class="todaysEventDayListelement"> ${{each ${data.eventDayList}}} <div id="eventDay" class="eventDay ${$data.eventDayClass}"> <div class="day"> ${$data.dateDay} </div> <div class="monthYear"> ${$data.dateMonthYear} </div> <div id="eventCounter" class="eventCounter ${$data.counterClass}"> ${$data.count} </div> <div style="display:none" class="date"> ${$data.date} </div> </div> {{/each}} </li> {{/each}} </script> And here's the JSON { "eventDayGroups" : [ { "eventDayList" : [ { "count" : 1, "counterClass" : "eventCountSingle", "date" : "27.08.2011", "dateDay" : "27", "dateMonthYear" : "Aug 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "28.08.2011", "dateDay" : "28", "dateMonthYear" : "Aug 2011", "eventDayClass" : "" }, { "count" : 3, "counterClass" : "eventCountSingle", "date" : "29.08.2011", "dateDay" : "29", "dateMonthYear" : "Aug 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "30.08.2011", "dateDay" : "30", "dateMonthYear" : "Aug 2011", "eventDayClass" : "" }, { "count" : 2, "counterClass" : "eventCountSingle", "date" : "31.08.2011", "dateDay" : "31", "dateMonthYear" : "Aug 2011", "eventDayClass" : "" }, { "count" : 5, "counterClass" : "eventCountSingle", "date" : "01.09.2011", "dateDay" : "01", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 5, "counterClass" : "eventCountSingle", "date" : "02.09.2011", "dateDay" : "02", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 3, "counterClass" : "eventCountSingle", "date" : "03.09.2011", "dateDay" : "03", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 2, "counterClass" : "eventCountSingle", "date" : "04.09.2011", "dateDay" : "04", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" } ] }, { "eventDayList" : [ { "count" : 2, "counterClass" : "eventCountSingle", "date" : "05.09.2011", "dateDay" : "05", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "06.09.2011", "dateDay" : "06", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 3, "counterClass" : "eventCountSingle", "date" : "07.09.2011", "dateDay" : "07", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "08.09.2011", "dateDay" : "08", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 2, "counterClass" : "eventCountSingle", "date" : "09.09.2011", "dateDay" : "09", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 2, "counterClass" : "eventCountSingle", "date" : "10.09.2011", "dateDay" : "10", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "11.09.2011", "dateDay" : "11", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 2, "counterClass" : "eventCountSingle", "date" : "12.09.2011", "dateDay" : "12", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 2, "counterClass" : "eventCountSingle", "date" : "13.09.2011", "dateDay" : "13", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" } ] }, { "eventDayList" : [ { "count" : 2, "counterClass" : "eventCountSingle", "date" : "14.09.2011", "dateDay" : "14", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "15.09.2011", "dateDay" : "15", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 3, "counterClass" : "eventCountSingle", "date" : "16.09.2011", "dateDay" : "16", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "17.09.2011", "dateDay" : "17", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "18.09.2011", "dateDay" : "18", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 3, "counterClass" : "eventCountSingle", "date" : "19.09.2011", "dateDay" : "19", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 1, "counterClass" : "eventCountSingle", "date" : "20.09.2011", "dateDay" : "20", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 2, "counterClass" : "eventCountSingle", "date" : "21.09.2011", "dateDay" : "21", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" }, { "count" : 2, "counterClass" : "eventCountSingle", "date" : "22.09.2011", "dateDay" : "22", "dateMonthYear" : "Sep 2011", "eventDayClass" : "" } ] } ] } A: Fixed it myself. As I suspected I had written the template wrong. Here's the correct way: <script id="calendarListTemplate" type="text/x-jquery-tmpl"> {{each eventDayGroups}} <li class="todaysEventDayListelement"> {{each eventDayList}} <div id="eventDay" class="eventDay ${$value.eventDayClass}"> <div class="day"> ${$value.dateDay} </div> <div class="monthYear"> ${$value.dateMonthYear} </div> <div id="eventCounter" class="eventCounter ${$value.counterClass}"> ${$value.count} </div> <div style="display:none" class="date"> ${$value.date} </div> </div> {{/each}} </li> {{/each}} </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7634137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: web2py: how to download image with SQLTABLE I'd like to know if it's possible use SQLTABLE to build up a list of images. Images are in a database table, but I don't want just a link to download. A: You can do it in a number of ways: First: db.table.field.represent = lambda r, v: IMG(_src=URL('default', 'download', args=v.field)) # where field is the field where your picture lives. Second is using web2py virtual fields: class MyVirtual(object): def photo(self): return IMG(_src=URL('default', 'download', args=self.table.field)) db.table.virtualfields.append(MyVirtual()) table = SQLTABLE(db(db.table).select()) Third is using extracolumns: myextracolumns = [{'label': 'My Photo', 'content': lambda row, rc: IMG(_src=URL('default', 'download', args=row.field))}] table = SQLTABLE(rows, extracolumns=myextracolumns)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OSMdroid : How to load offline map from zip archive - MapTileFileArchiveProvider I really need some help with the OSMdroid library. It is useful to have maps stored in sdcard as zip files. Also, maps can be unzipped and the image files may be used directly for faster rendering. I managed to load tiles from my sdcard when the tiles are unziiped, have .tile extension and are stored in the folder /sdcard/osmdroid/tiles/Mapnik/... To create my map I used the Mobile Atlas Creator and OSMAND tile storage format. I read some tutorials on the web that claim storing zip files containing tiles are stored in /sdcard/osmdroid then the offline map will be loaded from the zip. But it does not work for me. * *Did anybody managed to make it work? If so how? *Do I need to instantiate my own MapTileFileArchiveProvider? If so, how can I do that? Any examples? A: The files in your ZIP need to be in the form of: Z/X/Y.png If you rename your Y.tile files to Y.png, zip them up and put the zip file in /sdcard/osmdroid/, that should work. A: Just a correction or addition to the answer of user976933, the zip should also contain the name of the tilesource as base directory, the needed structure inside the zip is: tilesourcename/Z/X/Y The code loading the tiles is in BitmapTileSourceBase: @Override public String getTileRelativeFilenameString(final MapTile tile) { final StringBuilder sb = new StringBuilder(); sb.append(pathBase()); sb.append('/'); sb.append(tile.getZoomLevel()); sb.append('/'); sb.append(tile.getX()); sb.append('/'); sb.append(tile.getY()); sb.append(imageFilenameEnding()); return sb.toString(); } public String pathBase() { return mName; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to efficiently fetch one column using CoreData I have a Table with 50,000 records (table has 8 columns). I need to display only 1st column on the Table. I need an array which contains all data from Table only from 1st column. How to use NSFetchRequest to get all record from 1st column of the Table using Core Data? A: You need to use setPropertiesToFetch: method like [request setPropertiesToFetch :[NSArray arrayWithObject:@"<#Attribute name#>"]]; e.g., [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"ColName", nil]]; Refer link
{ "language": "en", "url": "https://stackoverflow.com/questions/7634154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: css query for selenium css=table#playlistTable tr:nth(0) span[class='playlistNumDisplay smallFont'] I am getting an error in this css above. I want to basically go to the first 'tr' under 'PlaulistTable and then under the first 'tr' I want to select span[class='playlistNumDisplay smallFont'] what wrong am I doing here? thanks for the help A: You probably meant :nth-child(1) or :nth-of-type(1) rather than simply :nth(0) which is invalid CSS. If you're specifically looking for the first match, you can also use :first-child or :first-of-type rather than the nth-() variants. Quirksmode has a good list of the available selectors here http://www.quirksmode.org/css/contents.html (along with a browser compatibility chart, though I don't think that will be relevant to you in the context of a Selenium query) Hope that helps. A: Don;t try to play complex CSS with Selenium. You can try something you used to from jQuery, but it doesn't exist in CSS, or at least the current version of CSS supported by the browser you try it on. 'nth' might be on example of this. So, simplifying it to: css=table#playlistTable tr:first-child span.playlistNumDisplay.smallFont You might consider even simplifying it more, according to which parts of the selector you care about matching, and which are not overlapping with other elements. . Note that :first-child is CSS 2.1, while :nth-child() and attribute value selectors (as in [class='...']) are CSS 3, meaning more browser support for the first than the others. . One thing that helps as well is using a jQuery locator, which can be implemented as in: How do I add a JQuery locators to Selenium Remote Control Of course will be limited to pages supporting jQuery. BTW, we have been using this exact one in a very large e-commerce website pretty successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting truncateToFit on Label in Tree I have a tree component sitting in a divided box. I want to display '...' on the node labels if the divided box is resized. I have a custom itemrenderer and have been looking at the labelFunction property as well as trying various approaches in the custom itemrenderer. Not having any joy. Any pointers would be appreciated. heres some sample code fo how I set it up... I define a tree... <mx:Tree id="tree" dataProvider="myData" labelFunction="treeNodeLabel" width="100%" height="100%" click="handleClick(event)" mouseMove="handleMouseMove(event)" itemRollOver="handleItemOver(event)" itemRollOut="handleItemOut(event)" doubleClickEnabled="true" doubleClick="handleDoubleClick(event)" iconFunction="customIcon" dragEnabled="true" dropEnabled="true" dragMoveEnabled="true" dragOver="onDragOver(event)" dragStart="onDragStart(event)" dataDescriptor="{new DiagramTreeDataDescriptor()}" itemRenderer="myCustomeRenderer" borderStyle="none" > The Custom Renderer is an Actionscript class that extends TreeItemRenderer... public class myCustomRenderer extends TreeItemRenderer { public function myCustomRenderer() { super(); } /** * Create child objects of the component. */ override protected function createChildren():void { super.createChildren(); createIcon(); addListeners(); addChild(Icon1); addChild(Icon2); } private function createIcon() : void { ... } private function addListeners() : void { ... } private function Icon1Click(event: MouseEvent):void { ... } private function Icon2Click(event: MouseEvent): void { ... } private function onLabelMouseOver(event : MouseEvent):void { ... } private function onLabelMouseOut(event : MouseEvent):void { ... } private function getDescription(node : XML):String { ... } override protected function updateDisplayList(...) { ... } override public function set listData(value:BaseListData):void { ... } } A: You can set labelDisplay.maxDisplayedLines = 1 Also, to be able to truncate, the labelDisplay must have a specified width. I don't know what's the default behavior inside a renderer. You can try to first set a width on the renderer itself (absolute or in percentage). If it does not work, set it on the labelDisplay.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to use a namedtuple with SQLalchemy? I have been trying to get a namedtuple to work with SQLalchemy, but to no avail.. Web search hasn't been very illuminating and I'm new with Python and SQLalchemy so I'm not really sure if I'm chasing windmills :( The basic idea is that I have a namedtuple, ie: Point=namedtuple('Point',['x','y']) which basically creates a class Point(tuple) if I'm correct. This works fine at first and I can create objects like: p=Point(3,4) But after I create the engine etc and call mapper , I can't create any more objects without getting this error: Traceback (most recent call last): File "<pyshell#62>", line 1, in <module> f=Point(3,4) TypeError: __init__() takes exactly 1 argument (3 given) Any ideas why that happens? Does anyone know how to make a namedtuple work with sqlalchemy? Of course I can define my own Point class, but I'm obsessing over making namedtuple work now.. I'm using Python 2.7, SQLalchemy 0.6.6 (sqlite engine) EXAMPLE: I'm trying something like this: from sqlalchemy import * from sqlalchemy.orm import * from collections import namedtuple Point=namedtuple('Point',['x','y'],verbose=True) p=Point(3,4) db=create_engine('sqlite:///pointtest.db') metadata=MetaData() pointxy=Table('pointxy',metadata, Column('no',Integer,primary_key=True), Column('x',Integer), Column('y',Integer), sqlite_autoincrement=True) metadata.create_all(db) m=mapper(Point, pointxy) Session=sessionmaker(bind=db) session=Session() f=Point(3,4) The main idea is that I want a named collection of stuff that can be easily stored in a database. So this: class Bunch: __init__ = lambda self, **kw: setattr(self, '__dict__', kw) is not going to work with sqlalchemy (I think). I can create a Bunch class but I won't know beforehand how many ints I want to store in my collection.. I will set it before I create my database. I hope I'm making sense.. A: Namedtuples have a bunch of behaviors that make them unsuitable for mapping with sqlalchemy: Most importantly, namedtuples can't be changed after they are created. This means that you can't use a namedtuple to track the state of a row in the database after the say an insert operation. You would typically want do something like this: class MyDataHolder(namedtuple('MyDataHolder', ('id', 'my_value')): pass mapper(MyDataHolder, MyDataMeta) ... newRow = MyDataHolder(None, 'AAA') ... session.add(newRow) When the session code executes the SQL to add the new data to the database it's going to want to update newRow so that newRow.id corresponds to id that the database assigned to your row. But because newRow is an immutable tuple, id can't be changed to hold the primary key that came back from the database. This makes namedtuples largely unsuitable for mappers. The __init__ issues happen because namedtuple get initialized in __new__ and then aren't expected to change. __init__() gets called after the object has been created and so has no effect. Thus __init__ for a namedtuple defines only one argument: self. I'm guessing that The mapper assumes that __init__() is handling class initialization and doesn't know about __new__ and immutable types. It looks like they are calling classname.__init__() with the args that get passed at creation time. You could "fix" this by specifying your own initializer: __init__(self, *args) but then you end up at the weakref problem. The weakref error happens because namedtuples use __slots__ to store their values rather than mutable __dict__s. I know that the use of __slots__ is a memory optimization so that you can store lots namedtuples efficiently. I'm assuming that it's expected that a namedtuple isn't going to change after it's created. That includes adding attributes so using __slots__ is a worthwhile memory optimization. However, I don't claim to understand why they author of the namedtuple class didn't support weak references. It wouldn't have been particularly difficult but there is probably a really good reason that I'm missing. I ran into this issue this morning and got around it by defining my own class for data mapping that was initialized with a _fieldset attribute. This specifies the (sub)set of fields that I'm interested in seeing mapped. Then I had some time and read the documentation of how namedtuples are implemented along with a bunch of other python internals. I think that I get most of why this doesn't work but I'm sure that there are python experts out there that have a better grasp of this than I do. -- Chris A: The mapper seems to add a _init_method. So doing the following after the mapper statement makes it work again: del Point.__init__ I'm not sure that using a mapper for this type of thing is the right idea. The mapper will most likely need the primary key ('no') in order to work correctly, which your nametuple currently does not have space for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how debug the vc++ Dll How to debug the vc++ Dll in visual studio 08.I also include breckpoint and pass the exe but still not succeed.The error message that The breakpoint will not currently be hit.No symbols have been loaded for this document. A: The breakpoint will not currently be hit.No symbols have been loaded for this document. You get this message when the .pdb file was not found or is not compatible with your dll version. Try doing the following: 1) Check if the .pdb file exists in the same location as the .dll or in Visual Studio's pdb file directory. 2) If it exists, try manually loading it - right click on the module and select load symbols from. 3) If you get an error saying the pdb is not compatible with your dll... well... it means just that. You can either recompile or try to find the compatible version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The name of element in the #process callback (Drupal) I'm trying to create a new form element representing the bbcode editor, which is a compound object of the toolbar and native textarea element. So my hook_element_info() looks like: function bbeditor_element_info() { $type['bbeditor'] = array( '#input' => TRUE, '#cols' => 60, '#rows' => 5, '#resizable' => TRUE, '#process' => array('process_bbeditor'), '#theme_wrappers' => array('bbeditor', 'form_element'), ); return $type; } But how do I get the name of element in the process function to passthrough it into the nested textarea element? function process_bbeditor($element, &$form_state) { ... // Insert the textarea element as a child. $name = 'textarea'; // <------------- How do I get the name? $element[$name] = $textarea; return $element; } A: $form_state variable store the information of form's state (means you can use this variable to get the value of form element) Like : $form_state['element_name']['value']; This will give you the value for form element. i'm not very sure that $form_state['element_name'] will give you the name of the element or it may return array. Please check by using var_dump($form_state['element_name']); in your hook what it print function process_bbeditor($element, &$form_state) { ... var_dump($form_state['element_name']); } A: Ok, being aware that this may be a bit late for the OP, I just want to add an answer for the benefit of those that may stumble upon this :) Assuming you are on a drupal 7 installation: $element['#name'] contains the name of the element, provided it has a name. It will automatically receive a name if rendered via drupal_get_form, in which case it receives the name of the corresponding array element in the initial form array. It is also possible to set the #name attribute directly, e.g. $form['bbeditor_test'] = array( '#type' => 'bbeditor', '#name' => 'use-this-name', // some more stuff .... ); It often makes sense to re-use a _process callback for custom fields defined for Drupal's field API (i.e. when defining fields via hook_field_info and related hooks). In such scenarios note, that the name of the element is not contained in the #name attribute but in the #field_name attribute. So, assuming process_bbeditor is also used for the field API fields we would have something like: function process_bbeditor($element, &$form_state,$form) { // some stuff ... $element_name = ''; if (isset($element['#name'])) { $element_name = $element['#name']; } elseif (isset($element['#field_name'])) { $element_name = $element['#field_name']; } else { // to handle the rare case when drupal_render is called directly on the parent array and #name isn't set $element_name = 'undefined'; } // some more stuff using $element_name .... return $element; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery Anchor Button doesn't apply css in ASP .net all, I follow the example of Jquery ui button and translated the html code to asp.net as follows enter code here <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html> <head runat="server"> <title></title> <link rel="Stylesheet" type="text/css" href="CSS/jquery.ui.all.css" /> <script type="text/javascript" src="Script/jquery-1.6.2.js"></script> <script type="text/javascript" src="Script/jquery.ui.button.js"></script> <script type="text/javascript" src="Script/jquery.ui.core.js"></script> <script type="text/javascript" src="Script/jquery.ui.widget.js"></script> </head> <body> <form runat="server"> <div class="demo"> <a href="#" class="demo">An anchor</a> </div> </form> <script type="text/javascript"> $(function () { $("a", ".demo").button(); $("a", ".demo").click(function () { return false; }); }); </script> </body> </html> however the css of the anchor button doesn't show, which mean the anchor shows a link just as before, doesn't anyone know why this happens? A: Maybe it should be: $(function () { $("a.demo").button(); $("a.demo").click(function () { return false; }); }); A: First use Chrome or Firefox with Firebug. Save your page without your JavaScript, open up the console and put in $("a", ".demo") Just the ensure nothing's gone really wrong and that the selector is returning the proper element. If this doesn't work make sure your jQuery is properly referenced. After that put in $("a", ".demo").button(); Now check the link element in the inspector and check that the DOM has been changed (it should now be a span in an a in a div). At this point if it failed double check your references for jQueryUI. If that worked but it isn't showing properly your CSS isn't referenced correctly. Edit based on comment Your JS references are in the wrong order. Core needs to come first, then widget, then button. Otherwise each file is trying to use functions that don't yet exist. The best way would be to just reference jQueryUI from a CDN (larger but likely to be cached) or build a custom jQueryUI file from the site rather than including the individual files, this way you won't get these problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is correct JDBC URL syntax if Oracle wallets are used? There are 2 URL syntax, old syntax which will only work with SID and the new one with Oracle service name. Old syntax jdbc:oracle:thin:@[HOST][:PORT]:SID New syntax jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE What is correct JDBC URL syntax if Oracle wallets are used? According to this article following URL syntax should be used: jdbc:oracle:thin:/@db_alias But as I can see following URL works too: jdbc:oracle:thin:@db_alias Which of these syntaxes are correct? A: When you are using Oracle Wallet with a JDBC string, both syntax's are allowed, so long as your "db_alias" is setup in your Wallet store obviously. Now, as far as using SQL*Plus with Oracle Wallet, the only format allowed with Oracle Wallet is: /@db_alias By the way, that article you referenced (and others) specifies you can only connect using JDBC if you use the OCI drivers, and not the thin client. This is/was typically because Java had no knowledge of the Oracle TNS and SQLNET files. This is in fact not true; you can connect using the JDBC thin driver with the latest Oracle Client & JDBC Drivers, but it just requires some setup. See http://tech.shopzilla.com/2011/09/oracle-wallet-with-thin-driver-with-connection-pool-with-database-timeouts/ for info on that, and below for a short summary. Using Oracle Wallet with JDBC Thin Driver * *Configure Oracle Wallet as usual (which comes with the Oracle Database Client), creating the appropriate entries in your tnsnames.ora and sqlnet.ora files as well as the credential entry in your wallet *Add the following JARs to your Java classpath. You should get these from the Oracle 11g client, and they can be found in the "jdbc" and/or "jlib" directories of where the client install is * *Oracle JDBC Driver - ojdbc6.jar *Oracle Wallet - oraclepki.jar *Oracle Security Certs - osdt_cert.jar *Oracle Security Core - osdt_core.jar *Start your Java application with the following system properties, pointing at your respective TNS and wallet directories: * *-Doracle.net.tns_admin=C:\myTNSdir *-Doracle.net.wallet_location=C:\mywalletdir *Then you can use a thin JDBC connection string in your application like so: jdbc:oracle:thin:/@MY_WALLET_DB_ENTRY
{ "language": "en", "url": "https://stackoverflow.com/questions/7634196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: DocX with filestream doesn't save So for a project I am creating Résumé's and i need to save them into a docx file. It is a ASP.NET MVC application and for the docx generating I'm using the libray docx to create the document. I can create the file but the filestream doesn't add the content i put into it. Here is a the code i use public ActionResult CVToWord(int id) { var CV = CVDAO.CV.Single(cv => cv.id == id); var filename = "CV - " + CV.firstname + " " + CV.name + " - " + CV.creationdate.ToString("dd MM yyyy") + ".docx"; System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.OpenOrCreate); using (DocX doc = DocX.Create(stream)) { Paragraph title = doc.InsertParagraph(); title.Append(CV.firstname + " " + CV.name); doc.Save(); } return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename); } Like i said, this creates the file but the file doesn't have any content. Any one have a idea why? A: public ActionResult CVToWord(int id) { var CV = CVDAO.CV.Single(cv => cv.id == id); var filename = "CV - " + CV.firstname + " " + CV.name + " - " + CV.creationdate.ToString("dd MM yyyy") + ".docx"; using (DocX doc = DocX.Create(filename)) { Paragraph title = doc.InsertParagraph(); title.Append(CV.firstname + " " + CV.name); doc.Save(); } System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open); return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename); } This works A: I think you need to close your FileStream: stream.Close(); A: I'd write a custom ActionResult for this: public class CVResult: ActionResult { private readonly CV _cv; public CVResult(CV cv) { _cv = cv; } public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; var filename = "CV - " + _cv.firstname + " " + _cv.name + " - " + _cv.creationdate.ToString("dd MM yyyy") + ".docx"; var cd = new ContentDisposition { Inline = false, FileName = filename }; using (var doc = DocX.Create(response.OutputStream)) { Paragraph title = doc.InsertParagraph(); title.Append(_cv.firstname + " " + _cv.name); doc.Save(); } } } and now your action result is no longer cluttered with plumbing code: public ActionResult CVToWord(int id) { var cv = CVDAO.CV.Single(cv => cv.id == id); return new CVResult(cv); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hashmap crashing eclipse I'm trying to load a hashmap by parsing a plist file in Android, using the plist parser from here: https://github.com/ZhouWeikuan/cocos2d. This has been working fine in the past, but recently my program has been getting null-pointer exceptions when using this hashmap (after parsing). When I try to debug, eclipse starts acting weird. The parser returns the hashmap and I can look over it's value in the variables view. When I step over the line that's assigning to 'worldMap', eclipse hangs. When trying to see worldMap's value in debug mode, I can see an empty line but no value - eventually eclipse crashes. Map worlds = (Map)getWorlds().get("Worlds"); Map worldMap = (Map)worlds.get(String.valueOf(world)); Map levels = (Map)worldMap.get("Levels"); However, when running the program normally the null-pointer exception comes later on, past these lines. Also, when I'm trying to debug, It won't always crash at the same location so I'm having a really hard time finding the source of this bug... Does anyone know whats going on? A: Can't tell you for certain what is going on, but the NullPointerException is sure a big hint. Add in some null checks after each line of code in your above example and I bet you will be able to track down the error pretty fast: Map whatEverThisIs = (Map)getWorlds(); if (whatEverThisIs == null) { /* Do something here */ } Map worlds = (Map)whatEverThisIs.get("Worlds"); if (worlds == null) { /* Do something here */ } Map worldMap = (Map)worlds.get(String.valueOf(world)); if (worldMap == null) { /* Do something here */ } Map levels = (Map)worldMap.get("Levels"); if (levels == null) { /* Do something here */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cxf NullPointerException while deploying on glassfish I'm trying to deploy war on glassfish3 and i get exception: SEVERE|glassfish3.1.1|org.apache.catalina.core.ContainerBase|_ThreadID=10;_ThreadName=Thread-2;|ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [cxf.xml] Offending resource: class path resource [applicationContext-ws.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [cxf.xml]; nested exception is java.lang.NullPointerException at org.apache.catalina.core.StandardContext.start(StandardContext.java:5389) at com.sun.enterprise.web.WebModule.start(WebModule.java:498) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:901) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:733) at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2000) at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1651) at com.sun.enterprise.web.WebApplication.start(WebApplication.java:109) at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130) at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269) at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:294) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:462) at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:375) at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:219) at com.sun.hk2.component.AbstractCreatorImpl.inject(AbstractCreatorImpl.java:131) at com.sun.hk2.component.ConstructorCreator.initialize(ConstructorCreator.java:91) at com.sun.hk2.component.AbstractCreatorImpl.get(AbstractCreatorImpl.java:82) at com.sun.hk2.component.SingletonInhabitant.get(SingletonInhabitant.java:67) at com.sun.hk2.component.EventPublishingInhabitant.get(EventPublishingInhabitant.java:139) at com.sun.hk2.component.AbstractInhabitantImpl.get(AbstractInhabitantImpl.java:76) at com.sun.enterprise.v3.server.AppServerStartup.run(AppServerStartup.java:253) at com.sun.enterprise.v3.server.AppServerStartup.doStart(AppServerStartup.java:145) at com.sun.enterprise.v3.server.AppServerStartup.start(AppServerStartup.java:136) at com.sun.enterprise.glassfish.bootstrap.GlassFishImpl.start(GlassFishImpl.java:79) at com.sun.enterprise.glassfish.bootstrap.GlassFishDecorator.start(GlassFishDecorator.java:63) at com.sun.enterprise.glassfish.bootstrap.osgi.OSGiGlassFishImpl.start(OSGiGlassFishImpl.java:69) at com.sun.enterprise.glassfish.bootstrap.GlassFishMain$Launcher.launch(GlassFishMain.java:117) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.enterprise.glassfish.bootstrap.GlassFishMain.main(GlassFishMain.java:97) at com.sun.enterprise.glassfish.bootstrap.ASMain.main(ASMain.java:55) Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [cxf.xml] Offending resource: class path resource [applicationContext-ws.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [cxf.xml]; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85) at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:76) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:218) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseDefaultElement(DefaultBeanDefinitionDocumentReader.java:147) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:132) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:93) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:4750) at com.sun.enterprise.web.WebModule.contextListenerStart(WebModule.java:550) at org.apache.catalina.core.StandardContext.start(StandardContext.java:5366) ... 32 more Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [cxf.xml]; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.importBeanDefinitionResource(DefaultBeanDefinitionDocumentReader.java:202) ... 53 more Caused by: java.lang.NullPointerException at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.checkOverrideProperties(ClassBeanInfoImpl.java:205) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:186) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:509) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:528) at com.sun.xml.bind.v2.runtime.property.ArrayReferenceNodeProperty.<init>(ArrayReferenceNodeProperty.java:87) at sun.reflect.GeneratedConstructorAccessor91.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:128) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:181) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:509) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:168) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:509) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:528) at com.sun.xml.bind.v2.runtime.property.ArrayReferenceNodeProperty.<init>(ArrayReferenceNodeProperty.java:87) at sun.reflect.GeneratedConstructorAccessor91.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:128) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:181) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:509) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:528) at com.sun.xml.bind.v2.runtime.property.ArrayReferenceNodeProperty.<init>(ArrayReferenceNodeProperty.java:87) at sun.reflect.GeneratedConstructorAccessor91.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:128) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:181) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:509) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:168) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:509) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:528) at com.sun.xml.bind.v2.runtime.property.SingleElementNodeProperty.<init>(SingleElementNodeProperty.java:105) at sun.reflect.GeneratedConstructorAccessor90.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:128) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:181) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:509) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:528) at com.sun.xml.bind.v2.runtime.property.ArrayElementProperty.<init>(ArrayElementProperty.java:112) at com.sun.xml.bind.v2.runtime.property.ArrayElementNodeProperty.<init>(ArrayElementNodeProperty.java:62) at sun.reflect.GeneratedConstructorAccessor103.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:128) at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:181) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:509) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:326) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:141) at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1157) at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:145) at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:236) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:187) at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:147) at javax.xml.bind.ContextFinder.find(ContextFinder.java:349) at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:446) at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:409) at org.apache.camel.spring.handler.CamelNamespaceHandler.createJaxbContext(CamelNamespaceHandler.java:179) at org.apache.camel.spring.handler.CamelNamespaceHandler.getJaxbContext(CamelNamespaceHandler.java:166) at org.apache.camel.spring.handler.CamelNamespaceHandler$CamelContextBeanDefinitionParser.doParse(CamelNamespaceHandler.java:249) at org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser.parseInternal(AbstractSingleBeanDefinitionParser.java:85) at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse(AbstractBeanDefinitionParser.java:59) at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1335) at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1325) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135) at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:93) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390) ... 56 more here is this offending cxf.xml <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-camel.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <bean name="taskServiceBean" class="com.example.TaskServiceImpl" /> <camelContext id="context" trace="true" xmlns="http://camel.apache.org/schema/spring"> <route id="serverRoute"> <from uri="jms:queue:com.example.taskservice" /> <to uri="direct:TaskServiceServer" /> </route> </camelContext> <jaxws:endpoint id="taskServiceJMS" address="camel://direct:TaskServiceServer" implementor="#taskServiceBean"> </jaxws:endpoint> <cxf:bus> <cxf:features> <cxf:logging /> </cxf:features> </cxf:bus> <bean class="org.apache.camel.component.cxf.transport.CamelTransportFactory" p:camelContext-ref="context" p:bus-ref="cxf"> <property name="checkException" value="true" /> <property name="transportIds"> <list> <value>http://cxf.apache.org/transports/camel</value> </list> </property> </bean> <bean id="jms" class="org.apache.camel.component.jms.JmsComponent"> <property name="connectionFactory" ref="myConnectionFactory" /> </bean> myConnectionFactory is defined as follows in project that is on classpath: <jee:jndi-lookup id="myConnectionFactory" jndi-name="java:comp/env/amqConnectionFactory" /> However, the same file can be deployed, even on the same domain after any successfull deployment has been done. Anyone knows what is happening? A: I was having the same problem when upgrading my server from glassfish v3.0.1 to glassfish v3.1.1. Seems like there is a bug in the jaxb-osgi.jar in v3.1.1. http://java.net/jira/browse/JAXB-860 shows that the fix will be included in glassfish v3.1.2. But at the meantime, I replaced the jaxb-osgi.jar in glassfish v3.1.1 with the jar from glassfifh v3.0.1 and the problem is solved. You should be able to get a newer version of jaxb-osgi.jar that has the fix in as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: update model from database not working I'm trying to generate my model from the database as usual, creating the model from the database using entity framework. I go through the wizard, add the connection string, test it, I select the tables I want to import, everything as usual. However the model is not created, I tried to update, re-create, everything that has come to my mind, with no success. Do you know what might be happening? EDIT: Btw, in the Designer.cs nothing is created as well, so no model, but with a two table database. I don't know if the problem might be that I have too many columns on a table? ha! A: After wondering why the model was not being created from the database without showing any error, the problem was that my tables didn't have any primary key, and in conclusion the model cannot create entities without primary keys. I'm not bothered by this, but I think an error or warning would have been more useful than an info entry. Hope this will help another in the future. A: Try this way: - In models section, add ADO.NET Entity Data Model. In the wizard select all tables. - At this point you should have an edmx file, open it, right click on the diagram and choose ADO.NET DbContext Geneartor. If you do not have this generator, download it from the Online Templates Section. - Now follow the wizard. - Now you should have the DBContext. Inside this you'll find all the item of the db and the DBEntities class necessary to work with the db.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JBoss6 with RestEasy client I want to consume a REST service in my web app (.war with 6.0.0.Final), and recently switched from jersey to resteasy (because of JBoss6 with REST client (jersey-client)). My client code is this simple example (perfectly working when called from the console): ResteasyProviderFactory providerFactory = ResteasyProviderFactory.getInstance(); RegisterBuiltin.register(providerFactory); ClientRequest request = new ClientRequest(restUrl); request.accept(MediaType.APPLICATION_XML); ClientResponse<MyJaxbClass> response = request.get(MyJaxbClass.class); At the beginning I hoped that everything for RESTeasy is available in JBoss, but while accessing the method I get this error: Caused by: java.lang.NoClassDefFoundError: org/apache/commons/httpclient/HttpMethod at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.newInstance0(Class.java:326) at java.lang.Class.newInstance(Class.java:308) at org.jboss.resteasy.client.ClientRequest.createDefaultExecutorInstance(ClientRequest.java:115) at org.jboss.resteasy.client.ClientRequest.getDefaultExecutor(ClientRequest.java:94) at org.jboss.resteasy.client.ClientRequest.<init>(ClientRequest.java:125) at my.own.MyRestEasyClient.members(MyRestEasyClient.java:42) Well, not a big deal! Although I'm wondering why the deprecated commons-httpcomponents is used, I added commons-httpclient:commons-httpclient:3.1 to my .war. But the error did not disappeared. I double-checked that commons-httpclient-3.1.jar is in the war. Then I removed commons-httpcomponentsand addedorg.jboss.resteasy:resteasy-jaxrs:2.1.0.GAandorg.jboss.resteasy:resteasy-jaxb-provider:2.1.0.GA`. To avoid (maybe I'm already in) jar-hell I used the resteasy-version which is bundled with JBoss6, but now I'm getting this error: Caused by: java.lang.annotation.AnnotationTypeMismatchException: Incorrectly typed data found for annotation element public abstract javax.xml.bind.annotation.XmlNsForm org.jboss.xb.annotations.JBossXmlSchema.elementFormDefault() (Found data of type Ljavax/xml/bind/annotation/XmlNsForm;.QUALIFIED) This is not really specifict but I got similar errors if I bundle jars into my .war which are already available in JBoss. I've found ClassNotFound Exception when configuring RestEasy, but this seems not to be related to my issue. A: We had the same problem a few days ago, but found this bug report that helped us https://issues.jboss.org/browse/JBAS-8841 To fix (As mentioned in the bug report): I added commons-httpclient-3.1.jar in deployers/resteasy.deployer to correct the exception. Adding the jar to my webapp didn't worked And this worked for us.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to synchronously repaint custom console using threads? I have a JScrollPane(packed with text area) that acts as a custom console for my swing application. Here is the code for my console class InternalConsoleFrame{ static JTextArea outArea static JScrollPane consoleHolder static setUpStreams(){ outArea = new javax.swing.JTextArea(10,100) System.setErr(new PrintStream(new JTextAreaOutputStream(outArea))); System.setOut(new PrintStream(new JTextAreaOutputStream(outArea))); WriterAppender logAppender = new WriterAppender(new PatternLayout(), new JTextAreaOutputStream(outArea)); Logger.getRootLogger().addAppender(logAppender); } public InternalConsoleFrame(){ DefaultCaret caret = (DefaultCaret)outArea.getCaret(); caret.setUpdatePolicy(DefaultCaret.OUT_BOTTOM); outArea.setBackground(new Color(255,250,205)); outArea.setForeground(Color.BLACK); outArea.setLineWrap(true); outArea.setWrapStyleWord(true); outArea.setFont(new Font(null, Font.PLAIN, 13)); outArea.addMouseListener(new ConsolePopup()); consoleHolder = new JScrollPane(outArea); } } public class JTextAreaOutputStream extends OutputStream { JTextArea ta; JTextAreaOutputStream(javax.swing.JTextArea t) { super(); ta = t; } public synchronized void write(int i) { ta.append(Character.toString((char)i)); } public synchronized void write(char[] buf, int off, int len) { String s = new String(buf, off, len); ta.append(s); } } The API server at the back end is continuously printing status (using println/lo4j from backend) but my custom console is not able to synchronously capture the log4j/print statements and repaint itself. It drops the whole set of log4j statements from the backend only after the total completion of the API call. I want my console to capture the backend log4j/println statements During the API call and repaint itself. How can this be achieved? My guess is that the InternalConsoleFrame() object created is being blocked by the native swing awt thread until the complete execution of the API call. If this is the case, I think that I need to launch the above code snippet onto a new Thread. If so, in which portion of the above code should I implement threading. I am quite confused..Please help.. A: Agreed, it looks like you're blocking the event dispatch thread(EDT) by violating the base threading rule for Swing: all component access must happen on the EDT. Implement a SwingWorker to achieve that, its api doc has some examples, another recently discussed here
{ "language": "en", "url": "https://stackoverflow.com/questions/7634229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: issue with CustomView drawing in my application What is wrong in my code here.why it is not drawing my customview on screen. class CustActivty extends Activty{ private ShapeDrawable mDrawable;; Path path; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.imagelayout); CustomView view=new CustomView(getApplicationContext()); RelativeLayout rl=(RelativeLayout)findViewById(R.id.relativeLayout1); rl.addView(view); } class CustomView extends View{ CustomView(Context context){ super(context); path=new Path(); RectF rec=new RectF(10,10,400,400); path.addArc(rec,90,180); mDrawable = new ShapeDrawable(new PathShape(path,400,400)); mDrawable.setBounds(10, 10, 400,400); mDrawable.getPaint().setColor(0xff74AC23); } protected void onDraw(Canvas canvas){ mDrawable.draw(canvas); } } } Plz anybody having idea.Plz help. A: You should specify the LayoutParams that your view will use to be added to the RelativeLayout So instead of just rl.addView(view) RelativeLayout.LayoutParams params = //initialise them as you want rl.addView(view, params);
{ "language": "en", "url": "https://stackoverflow.com/questions/7634230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: OAuth "nested" params The problem with the Ruby library OAuth (0.4.5) when I use a "nested" params in the query. Example: That does not work that request current_user.myapp.client.post('/api/weights', {"weight[value]"=> 65}) I got ---! Ruby / object: Net:: HTTPUnauthorized body:! str str: Invalid OAuth Request "@ _rails_html_safe": false body_exist: true code: "401" And this is working current_user.myapp.client.post('/api/weights', {:weight => {:value => 65}) But the params do not come correct: Parameters: {"weight" => "value65"} A: Fixed this bug https://github.com/oauth/oauth-ruby/pull/35
{ "language": "en", "url": "https://stackoverflow.com/questions/7634240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Register RazorViewEngine only for C# (only for .cshtml files) I am only using RazorViewEngine on one of my ASP.NET MVC 3 applications and I cleared Web Forms view engine out with following code inside Application_Start method of my Global.asax.cs file ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); I decided to see something solid so that I could be satisfied with this two-line-code-effort and I try to render a partial view which does not exist and I got this result : The partial view '_ResortMapPartialView' was not found or no view engine supports the searched locations. The following locations were searched: ~/Areas/Accommodation/Views/resort/_ResortMapPartialView.cshtml ~/Areas/Accommodation/Views/resort/_ResortMapPartialView.vbhtml ~/Areas/Accommodation/Views/Shared/_ResortMapPartialView.cshtml ~/Areas/Accommodation/Views/Shared/_ResortMapPartialView.vbhtml ~/Views/resort/_ResortMapPartialView.cshtml ~/Views/resort/_ResortMapPartialView.vbhtml ~/Views/Shared/_ResortMapPartialView.cshtml ~/Views/Shared/_ResortMapPartialView.vbhtml It looks a little better. Now it looks for less items than before. But still the files with .vbhtml extensions are making me unconformable. The question is that : How can we get rid of them? A: My suggestion would be to override the RazorViewEngine definitions for the following to only include cshtml files. * *AreaViewLocationFormats *AreaMasterLocationFormats *AreaPartialViewLocationFormats *ViewLocationFormats *MasterLocationFormats *PartialViewLocationFormats *FileExtensions An brief example: public class CSHtmlViewEngine: RazorViewEngine { public CSHtmlViewEngine() { base.AreaViewLocationFormats= new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" }; base.AreaPartialViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml", }; // All the other LocationFormats listed above will also need to be amended // Don't forget the FileExtensions array } } See my answer which talks about overriding these values. The same principle applies. You will need to register this modified ViewEngine (CSHtmlViewEngine) in the ApplicationStart method ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new CSHtmlViewEngine()); A: Instead of subclassing the RazorViewEngine, or replacing it outright, you can just alter existing RazorViewEngine's PartialViewLocationFormats property. This code goes in Application_Start: System.Web.Mvc.RazorViewEngine rve = (RazorViewEngine)ViewEngines.Engines .Where(e=>e.GetType()==typeof(RazorViewEngine)) .FirstOrDefault(); string[] additionalPartialViewLocations = new[] { "~/Views/[YourCustomPathHere]" }; if(rve!=null) { rve.PartialViewLocationFormats = rve.PartialViewLocationFormats .Union( additionalPartialViewLocations ) .ToArray(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: For Loop with Google Geocoding - High Error Rate - iPhone I am using the below code to fetch location information via Geocoding and then add a map pin to a Google Map View. The code uses a For loop to cycle through each place in my database. The problem is that the code fails to return location info for about 50% of the places when run. These failed items are saved in the failedLoad array as per the code below. Can anyone suggest why this is ? Also since these failed items are saved in the "failedLoad" array, is there a way I could use this array to load any missing pins ? EDIT The failed items are due to a 620 error which means that I am submitting items too quickly. How can I add a delay into the code ? Thanks ! -(void)displayPlaces { for (PlaceObject *info in mapLocations) { // GET ANNOTATION INFOS NSString * addressOne = info.addressOne; NSString * name = info.name; NSString * postCode = info.postCode; NSString * addressTwo = [addressOne stringByAppendingString:@",London,"]; NSString * address = [addressTwo stringByAppendingString:postCode]; NSString* urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSURL* url = [NSURL URLWithString:urlString]; NSURLRequest* req = [NSURLRequest requestWithURL:url]; OHURLLoader* loader = [OHURLLoader URLLoaderWithRequest:req]; [loader startRequestWithCompletion:^(NSData* receivedData, NSInteger httpStatusCode) { NSString* locationString = loader.receivedString; NSArray *listItems = [locationString componentsSeparatedByString:@","]; double latitude = 0.0; double longitude = 0.0; if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) { latitude = [[listItems objectAtIndex:2] doubleValue]; longitude = [[listItems objectAtIndex:3] doubleValue]; } else { NSLog(@"Error %@",name); [failedLoad addObject : info]; } CLLocationCoordinate2D coordinate; coordinate.latitude = latitude; coordinate.longitude = longitude; MyLocation *annotation = [[[MyLocation alloc] initWithName:name address:address coordinate:coordinate] autorelease]; [mapViewLink addAnnotation:annotation]; } errorHandler:^(NSError *error) { NSLog(@"Error while downloading %@: %@",url,error); }]; } } A: Instead of using a for loop and send all your requests at the same time, you probably should send them one after the other (or 5 by 5?) Here is one way to do it (not tested in real code, just typed as I go so may have some typo): // In the instance variables, have: @property(retain) NSMutableSet* mapLocationsToGeocode; // When you want to decode, use: self.mapLocationsToGeocode = [NSMutableSet setWitharray:mapLocations]; // (Or add to the existing NSSet if you have one and add Places using multple passes) [self popLocationAndGeocode]; -(void)popLocationAndGeocode { // Pop any location from the set PlaceObject* onePlace = [mapLocationsToGeocode anyObject]; // Build the URL given the PlaceObject NSString* address = [NSString stringWithFormat:@"%@,London,%@",info.addressOne,info.postCode]; NSString* name = info.name; NSString* urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; // Remove it so it won't be poped again [mapLocationsToGeocode removeObject:onePlace]; // Send the request here to decode the PlaceObject OHURLLoader* loader = [OHURLLoader URLLoaderWithRequest:req]; [loader startRequestWithCompletion:^(NSData* receivedData, NSInteger httpStatusCode) { NSString* locationString = loader.receivedString; NSArray* listItems = [locationString componentsSeparatedByString:@","]; ... if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) { // Process with latitude and longitude, add your MKAnnotation, etc } else { NSLog(@"Error %@",name); [failedPlaces addObject:onePlace]; } ... // Schedule the next decoding request (1) if ([mapLocationsToGeocode count]) [self performSelector:@selector(popLocationAndGeocode) withObject:nil afterDelay:0.1]; } errorHandler:^(NSError *error) { NSLog(@"Error while downloading %@: %@",url,error); [failedPlaces addObject:onePlace]; // Schedule the next decoding request anyway (1) if ([mapLocationsToGeocode count]) [self performSelector:@selector(popLocationAndGeocode) withObject:nil afterDelay:0.1]; }]; // Schedule the next decoding request (2) -- solution 2 // if ([mapLocationsToGeocode count]) [self performSelector:@selector(popLocationAndGeocode) withObject:nil afterDelay:1.0]; // wait one sec before sending next request } Of course, dont forget to set the property back to nil when done (or in the dealloc) to release the memory. In case (1), I call performSelector:withObject:afterDelay in both the completion and error blocks, so that the next request/decoding process is called only once the first has finished. This way your requests are somewhat serialized. In case (2) (commented/disabled), I call performSelector:withObject:afterDelay right after the startRequestWithCompletion:... method, so it won't wait for the end of the first request to pop the next one. But you will wait (hopefully) long enough so that you won't reach the GoogleAPI rate limit Note that this is not the only solution, there are plenty other possibilities. One being to use NSOperationQueue to queue the requests one after the other on a queue and add dependencies to it, or schedule the sending process of the requests on a GCD serial queue (yeah, I know I told you not to use GCD to actually send your requests, but that still apply, still dont use GCD+synchronous requests, but you can use GCD to queue blocks that will call [OHURLLoader startRequestWithCompletion:...] on the main thread one after the other; the request itself still being executed on the main thread by the RunLoop)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: browser alert about open / popup new window I have a link that when clicked, the browser will open a new window. This the code for the click event on that link: var clickView = function(){ window.open('/client/item/show/' + itemID); return false; }; I also have another function that, read the url from a ajax call and open it in a new window. if (json.data && json.data.URL) { if (me.urlTarget==='_self'){ //use the self window to open the URL window.location.href =json.data.URL; } else{ //use new window to open the url. window.open(json.data.URL); } } For the first function (clickView), the browser (IE7/8 & Firefox) will open a new tab without any warning to user. For the second function (where the url is read from json.data.URL), both IE and Firefox will show an warning message and block the new window until the user agree on the warning. In both functions the opening URL is the same. I'm wondering why is there a difference, and is it possible to make them behave consistent? A: The answer appears to be here: open new window without the browser giving warning that is a popup Summary: calling window.open() at seemingly random times causes the browser to kick in with a warning/prompt. Calling window.open() as a result of a link click works fine. A: Possibly the second instance generates a warning because it is an absolute, rather than relative URL? (Either way, opening new browser windows is the devil's work).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: writing a compare point method im trying to write a compare point value eg does 1,0 equal 1,0 (true) this is what i have so far. any ideas? class Point attr_reader :x, :y def initialize x,y @x =x @y =y end def compare_point(x,y , a,b) # used to compare points if(x=a, y=b) puts correct else puts wrong end end end @current_location = Point.new 1,0 @start_location = Point.new 1,0 compare_point(@start_location,@current_location) A: class Point attr_reader :x, :y def initialize(x, y) @x = x @y = y end def ==(another) [x, y] == [another.x, another.y] end end Point.new(1, 1) == Point.new(1, 1) #=> true Point.new(1, 1) == Point.new(2, 1) #=> false Note that if you use Struct you get accessors and equality for free: class Point < Struct.new(:x, :y) # other methods here end
{ "language": "en", "url": "https://stackoverflow.com/questions/7634249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling SignalR hub clients from elsewhere in system I've set up a SignalR hub to communicate between the server and client. The hub server side code is stored in a class called Hooking.cs. What I want is to be able to call a method defined in Hooking.cs to allow me to broadcast messages to any connected clients from anywhere in my application. It seems that a new instance of Hooking.cs is created for every client/server call, so I had hoped that I would be able to use something like var hooking = new Hooking(); hooking.Test(); with the method Test() defined in Hooking.cs such as public static void Test() { Clients.test() } and with a the client side javascript var hooking = $.connection.hooking; hooking.test = function() { alert("test worked"); }; $.connection.hub.start() Unfortunately it isn't that simple, as Clients is not static, so not accessible from a static method. Looking through the SignalR source code I came across a method that looked promising, Hubs.Invoke(string hubName, string method, params object[] args), so I would hope I could use something such as Hubs.Invoke("Hooking", "Test") but I can't make it work. Any help with this would be hugely appreciated A: You can easily use a hub by following this 2 step- * *Instantiating by dependency injection like this- public class ClassName { ........ ........ private IHubContext _hub; public BulletinSenderController(IConnectionManager connectionManager) { _hub = connectionManager.GetHubContext<McpHub>(); ........ ........ } ............ ............ } 2.Using the hub object like this- _hub.Clients.All.onBulletinSent(bulletinToSend); More can be found here. Example code can be found in this git repo. A: Hub.GetClients has disappeared in version 0.4.0. From the wiki you can now use: IConnectionManager connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>(); dynamic clients = connectionManager.GetClients<MyHub>(); A: This is the correct way for SignalR 2.x: var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); context.Clients.All.addMessage(message); Basically, you can use the dependency resolver for the current host to resolve the IConnectionManager interface which allows you to get ahold of the context object for a hub. Further information can be found in the official documentation. A: Have a look at how it's done in Chat.cs in SignalR.Samples.Hubs.Chat from https://github.com/SignalR/SignalR. I can see in there that static Dictionary<TKey, TValue>'s are being instantiated at the top, so I imagine they are being maintained persistently too, either with the Chat class being a persisted instance (?) or that array being updated somehow. Check it out, David Fowler would probably be the best on this. A: This has changed in .NET Core 2, now you can use dependency injection like this: private readonly IHubContext<MyHub,IMyHubInterface> _hubContext; public MyController(MyHub,IMyHubInterface hubContext) { _hubContext = hubContext; } public bool SendViaSignalR() { _hubContext.Clients.All.MyClientSideSignalRMethod(new MyModel()); return true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "72" }
Q: Finding User ID from Sessions My question is similar to this question. Though I have not been able to figure it out yet. I want to be able to find the user id from the session. I understand that this can only be done within the controller, though I need this for a model method called Activity.log... In my controller, I have the following: @current_user = User.find(session[:user_id]) user_id = @current_user.id Activity.log(user_id) I hope that I am at least on the right track, and from the other SO question I have linked to, I have assumed that sessions is still the best way to achieve this, though I am open to suggestions. Thanks! A: As indicated by @Bohdan, you may want to shorten your code a bit like this: Activity.log( session[:user_id] ) In your case, you don't have to rely on ActiveRecord mechanisms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Push Notification iphone (my device not receive notification) I am facing the problem that my iOS device does not receive any push notification(s). Objective-C - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [[UIApplication sharedApplication] registerForRemoteNotificationTypes: ( UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound ) ]; [self.window makeKeyAndVisible]; return YES; } - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { NSString *str = [NSString stringWithFormat: @"Error: %@", err]; NSLog(str); } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { UIAlertView *dataAlert = [[UIAlertView alloc] initWithTitle:@"Device Token" message:@"data" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [dataAlert show]; } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSLog(@"APN device token: %@", deviceToken); NSString *deviceTokenString = [NSString stringWithFormat:@"%@",deviceToken]; UIAlertView *deviceTokenAlert = [[UIAlertView alloc] initWithTitle:@"Device Token" message:deviceTokenString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [deviceTokenAlert show]; } PHP <?php $deviceToken = "a448b8946a5de3801dc6a11862a5a0bf11f1adc16xxxxxxxxxxxx"; // masked for security reason // Passphrase for the private key $pass = 'molik'; // Get the parameters from http get or from command line $message = $_GET['message'] or $message = $argv[1] or $message = 'Test Message'; //$badge = (int)$_GET['badge'] or $badge = (int)$argv[2] or $badge = 1; $sound = $_GET['sound'] or $sound = $argv[3] or $sound = 'default'; // Construct the notification payload $body = array(); $body['aps'] = array('alert' => $message); if ($badge) $body['aps']['badge'] = $badge; if ($sound) $body['aps']['sound'] = $sound; /* End of Configurable Items */ $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); // assume the private key passphase was removed. stream_context_set_option($ctx, 'ssl', 'passphrase', $pass); // for production change the server to ssl://gateway.push.apple.com:219 $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); if (!$fp) { print "Failed to connect $err $errstr\n"; return; } else { print "Connection OK\n"; } $payload = json_encode($body); $msg = chr(0) . pack("n",32) . pack('H*', $deviceToken) . pack("n",strlen($payload)) . $payload; print "sending message :" . $payload . "\n"; $result=fwrite($fp, $msg); echo $result; fclose($fp); ?> When the PHP code is run it shows the output: Connection OK sending message :{"aps":{"alert":"Test Message","sound":"default"}} But on the device side, no notifications are received. A: I faced lot of problems related to public and private key. At last I had revoked all certificates and followed the below link and then I'm getting the push notification in device. You can also find the sample code of php in the below link. A: The problem with your certificates. Try to create the new app id and generate the development.cerandproduction.cer`. After that generate provisioning profiles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Exporting Drupal 6 to Wordpress latest (3.2.1?) I have inherited a website in Drupal. Cut a long painful story short: I want desperately to move to sanity. WP 3.2.1 (latest as of this writing) is the choice. Yet, it looks like the export process in Drupal requires a PhD in mechanical engineering. Googling for something results in a Java program (out of question for us) or a paid service. Really? Is there no humane way to move all my data from Drupal to WP? Thanks for any pointers! A: WP is still only properly effective as a blogging platform no matter what they want to tell you (trust me I have a lot of experience in this area). Various people have extended upon its core functionality so that it can do more than it originally did, but these extensions are strained at best. Drupal was built specifically to be extended, and thus we developers can extend it painlessly. That being said though (and with my mini-rant out of the way!), this bit of SQL will start you off...it will pull in the basic content from the node table to the wordpress wp_posts table. INSERT INTO wp23.wp_posts ( ID, post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_name, post_modified, post_modified_gmt, post_type) SELECT node.nid, node.uid, FROM_UNIXTIME(node.created), FROM_UNIXTIME(node.created), node_revisions.body, node.title, node_revisions.teaser, concat('node/', node.nid), FROM_UNIXTIME(node.changed), FROM_UNIXTIME(node.changed),'page' FROM drupal.node, drupal.node_revisions WHERE node.type = 'page' AND node.nid = node_revisions.nid Unfortunately there is no easy way to automatically pull in CCK (D6) or core (D7) fields because field storage is vastly different in Drupal/Wordpress; you'll have to examine the tables and write a custom script depending on the fields you have added. Hope that helps These links will probably help out too, the first one is where the above SQL came from: How To Migrate From Drupal To WordPress — Export And Import Mysql Script Migrating Drupal to Wordpress
{ "language": "en", "url": "https://stackoverflow.com/questions/7634264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Open swf file than works with socket Sorry for my bad English. I have the following problem: I have a .fla file, that works with Socket class. There is a server(written in Delphi XE, but it does not matter). I connect to it from my .fla. When i execute my .fla from within Flash Professional CS5 everything works fine. But when i tried to execute resulting .swf from Explorer(Win 7, Flash Player 10) i got an error: SecurityError: Error #2010: Local-with-filesystem SWF files are not permitted to use sockets. at flash.net::Socket/internalConnect() at flash.net::Socket/connect() at payterminal::TLogger() at payterminal::TMainTerminalClass() at testterminal_fla::MainTimeline/frame1() Socket connects to the server as follows: Sock.connect('127.0.0.1', 5243); I tried to change setting "Local playback security" in "File->Publish settings" to "Access network only. Ok. Flash player starts without errors, but it's send to server the following message: <policy-file-request/> After this socket connection closes. I also tried to use the method Security.AllowDomain(), but it did not made no positive results. There was another method i tried. The server has two listening sockets. The first listening on port 843. When this socket receive the message policy-file-request it send to .swf the crossdomain file, like this: <?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd"> <!-- Policy file for xmlsocket://socks.mysite.com --> <cross-domain-policy> <allow-access-from domain="*"/> </cross-domain-policy> After it the socket(843) closes. But the second listening socket gets the same message: . After all this, my .swf is still open in Flash Player with no errors, but the socket connection is not happening. I tried different crossdomain-files, but all my attempts led me to same result. That's the problem i have. I look forward to your help. Thanks. A: user976479 this is perfectly normal behavior. Flash player will first try to obtain the master xml policy file on port 843 and then try 5243 if it doesn't find a master. Once the server responds to the request for the crossdomain flash player will close the connection(always). I use the following crossdomain.xml for my socket server. Remember once the domain policy is recieved you have to have the flash player reconnect a second time. The second time you will not be disconnected. <?xml version="1.0" encoding="UTF-8" ?> <cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFileSocket.xsd"> <allow-access-from domain="*" to-ports="*" /> </cross-domain-policy> One last thing. use a port higher then 10k as the lower ports are usually reserved for other applications and there maybe be a conflict with that. A: There is no problem with your cross-domain file. Flash player's security features do not allow a local (file:// protocol) file to access the internet. To test your swf in a browser, you'll have to upload it to your server and then test it. Or, you could download a server to install on your local machine for testing. I use wampserver EDIT: Since you are already running a local server, try uploading to that. Then access your swf as http://127.0.0.1/mySwf.swf
{ "language": "en", "url": "https://stackoverflow.com/questions/7634266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: concurrent requests to Active Directory I am using python-ldap to connect to a remote Active Directory. Is there a way to find out/ tweak the number of concurrent connections supported by Active Directory? A: According to this KB article, the limits are specified in cn=Query-Policies,cn=Directory Service,cn=Windows NT,cn=Services of the configuration root. The property for concurrent connections is MaxConnections. However, the limit is per DC and, by default, is set to 5000. I'd be very suspicious that your application requires more connections than that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why Zend Lucene returns all hits if nothing is found? I have this query: +document_type:client name:something to search and if something to search is not found the Zend Lucene returns all documents containing +document_type:client and I would like to return empty set. I've tried to add AND operator between terms, but result is the same. What I'ma doing wrong? A: If you want to ensure both comparisons are matched, you can applied + to both comparisons +document_type:client +name:some_value OR +(document_type:client name:some_value) Take a look on <solrQueryParser defaultOperator="OR"/> <-- change it to AND
{ "language": "en", "url": "https://stackoverflow.com/questions/7634270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java web service client not decoding base64 I'm currently trying to implement a WS client in java but I have the following problem: The server is running in IIS 7.5 and was implemented with c#. It is sending a base64Binary string (which I believe it is supposed to since the original data was a byte array) but on the java side, all I get is an object of class B. How can I get a byte array back from that object? Thanks A: Do you mean Class [B? In that case all you need is to cast: byte[] bytes = (byte[]) obj; A: It sounds like you have a object of type array of byte (byte[]) System.out.println("class=" + byte[].getClass()); System.out.println("class=" + byte[].getClass().getName()); produces an output of class=class [B class=[B If this matches your output, then just cast the object into a byte[] (byte[]) array;
{ "language": "en", "url": "https://stackoverflow.com/questions/7634271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replacing ggplot2 legend key for geom_line with symbol I have a line plot of prices for three stocks, which I normalise by taking the percentage change from the beginning of the period I am looking at. This seems to work fine, but instead of the coloured lines on a grey background that currently make up the legend key, I would like squares or circles of colour next to the key label. Is this even possible in ggplot2? Any pointers, however brief, appreciated. Code to produce the chart follows below. Date <- c("2011-09-19","2011-09-20","2011-09-21","2011-09-22", "2011-09-23","2011-09-26","2011-09-27","2011-09-28","2011-09-29","2011-09-30") CoA <- c(100,100,95,93,88,91,98,109,115,106) CoB <- c(16.5,16.8,17.2,17,17.5,16.5,16,15.5,16.1,16.3) CoC <- c(3.2,3.18,3.15,3.12,3.15,3.1,3.08,3.11,3.35,3.42) prices <- data.frame(Date,CoA,CoB,CoC) changes <- as.data.frame(matrix(nrow=nrow(prices),ncol=ncol(prices))) changes[,1]=prices[,1] for(i in 2:ncol(prices)){ # calculate changes in price changes[,i]= (prices[,i]-prices[,i][1])/prices[,i][1] } colnames(changes) <- colnames(prices) changes <- melt(changes, id = "Date") changes$Date <- as.Date(as.character(changes$Date)) chart1 <- ggplot(data=changes,aes(x=changes$Date,y=changes$value,colour=changes$variable)) chart1 <- chart1 + geom_line(lwd=0.5) + ylab("Change in price (%)") + xlab("Date") + labs(colour="Company") print(chart1) A: You can define new geom like this: GeomLine2 <- proto(GeomLine, { objname <- "line2" guide_geom <- function(.) "polygon" default_aes <- function(.) aes(colour = "black", size=0.5, linetype=1, alpha = 1, fill = "grey20") }) geom_line2 <- GeomLine2$build_accessor() chart1 <- ggplot(data=changes,aes(x=Date, y=value, colour=variable, fill = variable)) chart1 <- chart1 + geom_line2(lwd=0.5) + ylab("Change in price (%)") + xlab("Date") + labs(colour="Company", fill = "Company") print(chart1) Not sure but note that this will not work in the next version of ggplot2. A: In ggplot the legend matches the plot itself. So, to get circles or squares in the legend you need to add circles or squares to the plot. This can be done with geom_point(shape=...). shape=1 generates circles, shape=7 generates squares. chart1 + geom_point(shape=7)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Preload ASP.NET MVC views in IIS warmup step I recently began playing around with the ability of IIS to apply a warmup step step to my web application through use of the IProcessHostPreloadClient interface (look here for for guidance on how to set this up). This worked out great, or at least I thought it did, because one of the 'clever' things I did was to try and preload my views by iterating over my controllers and rendering them. After a bit of trial and error, I got it to work and all was well. That is, until I noticed that all validation for my system no longer worked, neither client nor server validation. I assume that the validation is normally hooked up to the views when MVC retrieves a view for the first time and I failed to do so. Does anyone have an idea how this could be included in my solution or perhaps done in another way? The code: public class Warmup : IProcessHostPreloadClient { public void Preload(string[] parameters) { //Pre-render all views AutoPrimeViewCache("QASW.Web.Mvc.Controllers", @"Views\"); AutoPrimeViewCache("QASW.Web.Mvc.Areas.Api.Controllers", @"Areas\Api\Views\", "Api"); } private void AutoPrimeViewCache(string controllerNamespace, string relativeViewPath, string area = null) { var controllerTypes = typeof(Warmup).Assembly.GetTypes().Where(t => t.Namespace == controllerNamespace && (t == typeof(Controller) || t.IsSubclassOf(typeof(Controller)))); var controllers = controllerTypes.Select(t => new { Instance = (Controller)Activator.CreateInstance(t), Name = t.Name.Remove("Controller") }); foreach (var controller in controllers) { var viewPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, relativeViewPath + controller.Name); var viewDir = new DirectoryInfo(viewPath); if (viewDir.Exists) { var viewNames = viewDir.EnumerateFiles("*.cshtml").Select(f => f.Name.Remove(".cshtml")).ToArray(); PreloadController(controller.Instance, area, viewNames); } } } private void PreloadController(Controller controller, string area, params string[] views) { var viewEngine = new RazorViewEngine(); var controllerName = controller.GetType().Name.Remove("Controller"); var http = new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://a.b.com", null), new HttpResponse(TextWriter.Null))); var routeDescription = area == null ? "{controller}/{action}/{id}" : area + "/{controller}/{action}/{id}"; var route = new RouteCollection().MapRoute( "Default", // Route name routeDescription, // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); var routeData = new RouteData(route, route.RouteHandler); routeData.Values.Add("controller", controllerName); if (area != null) { routeData.Values.Add("area", area); routeData.DataTokens.Add("area", area); } routeData.DataTokens.Add("controller", controllerName); routeData.Values.Add("id", 1); routeData.DataTokens.Add("id", 1); var controllerContext = new ControllerContext(http, routeData, controller); var vDic = new ViewDataDictionary(); var vTemp = new TempDataDictionary(); foreach (var view in views) { var viewResult = viewEngine.FindView(controllerContext, view, null, false); if (viewResult.View == null) throw new ArgumentException("View not found: {0} (Controller: {1})".Args(view, controllerName)); var viewContext = new ViewContext(controllerContext, viewResult.View, vDic, vTemp, TextWriter.Null); try { viewResult.View.Render(viewContext, TextWriter.Null); } catch { } } } } A: Not direct answer to your question, but I think you should take a look at Precompiling MVC Razor views using RazorGenerator by David Ebbo One reason to do this is to avoid any runtime hit when your site starts, since there is nothing left to compile at runtime. This can be significant in sites with many views. A: The problem is not with the code in the question but the time at which it is executed. Moving the code into an action allows me to perform the warmup step without problems. In my case, I guess I'll just get the installation process to call the warmup action after the system has been configured. A: There is a new module from Microsoft that is part of IIS 8.0 that supercedes the previous warm-up module. This Application Initialization Module for IIS 7.5 is available a separate download. The module will create a warm-up phase where you can specify a number of requests that must complete before the server starts accepting requests. These requests will execute and compile all your views in a more robust manner than what you are trying to achieve. I have answered a similar question with more details at How to warm up an ASP.NET MVC application on IIS 7.5?.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Finding out what Javascript will run and when What's the best way of finding out what Javascript will run and when? I've outgrown placing functions inside setTimeouts to delay running code to when I think the dependencies have already loaded, etc. A: Assuming you're not interested in putting the code that needs those calls in the onload event handler (will be invoked when all resources have been loaded), probably because you've got too many resources to load, or have some user behavior dependant on those resources, which might be triggered before it is loaded. You might be interested in this resource: Dynamic resource management in JavaScript. There's an script through which you can load resources, and specify function callbacks to be invoked when the resource is loaded. A: Would jQuery's document ready method solve your problems?
{ "language": "en", "url": "https://stackoverflow.com/questions/7634280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SmartGWT: horizontally center an HTMLFlow I got an VLayout which occupies 100% of width on the screen. It contains some HTMLFlow elements, they all are centered. There is one Flow that has the same width as the screen and I want to "split" it in 2 e.g. from "Time remaining: 01:01:01" to "Time remaining: 01:01:01" So, I tried setting the flow width to 50%, which controls my HTMLFlow length perfectly, but then the align moves to the left, "Time remaining: 01:01:01" then I tried to include it inside an HLayout so it remains centered but the width gets override and is not 50% width but less. "Time remaining: 01:01:01" How I do this? A: Can't you just add <br />s to the HTML-string. There is no way to control linewrapping in SmartGWT's HTMLFlow itself. From HTMLFlow's JavaDoc: Use the HTMLFlow component to display HTML content that should expand to its natural size without scrolling. [..] NOTE: Since the size of an HTMLFlow component is determined by its HTML contents, this component will draw at varying sizes if given content of varying size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: R CMD roxygen - exec: 65: roxygen: not found Roxygen works fine from within R, but for some reason it craps out when I try to call it from the command line. Noticed a similar complaint from someone on windows (this thread: R CMD roxygen not recognized) but I'm on a nix box right now. Tried installing from source (install.packages("roxygen", type="source")) no dice there. Thoughts? A: This question doesn't have an answer as the package it is questioning is essentially deprecated. Use roxygen2 instead and write a shell script to roxygenize code from within R at the time of packaging.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: when to use Dependency Property in WP7 / Silverlight What is the speciality of Dependency property in Silverlight. I searched many sites but i won’t get a clear cut idea about this. Can any one let me know in what context this dependency property can be used in Silverlight. A: Here is the simple rule of thumb. If you are creating a control (either a UserControl or a Custom templated control) add new properties using Dependency Properties. Otherwise its rare to create model or view model classes that derived from DependencyObject you would just use standard properties perhaps with an implementation of INotifyPropertyChanged. Dependency properties are the basis for data binding. You can't use data binding on a property which isn't implemented as a DependencyProperty. For similar reasons a property needs to be implemented as DependencyPropertry if it is to be animated using Storyboard animations. A: When you create a UserControl. If your property is a normal public property like that : public Double MyProperty { get; set; } * *You won't be able to apply styling to the property. *You won't be able to apply an animation based on that property in Storyboards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pass the linq returned xml data to another function? var serviceLine = from ServiceLine in DataXML.Descendants("Serviceline") select new { ServiceLineName = ServiceLine.Attribute("Name").Value, EntityName = ServiceLine.Attribute("Entity").Value, SiteLevelName = ServiceLine.Attribute("SiteLevel").Value, FolderName = ServiceLine.Descendants("Folder"), ItemName = ServiceLine.Descendants("Item") }; i need to pass the serviceline as paramenter to another method, there i need to use the query returned result. so how can i pass the return. what type i need to use to pass the returned data. A: * *Create you own type. *Use Tuple *Return object, in calling method use dynamic to access properties.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Game window application with additional console window My previous demo was an XNA project that had a game window, as well as a console window for debugging information, however, the option is either not there or moved in a C++ project. Does anyone know how to enable a console window that will run alongside a game window in VS2010? A: You can use AllocConsole to create a console for you process. Once you do that, you can use std::cout or, perish the thought, printf to write to the console. A: You can view Console in WinForms app with the Visual Studio output window
{ "language": "en", "url": "https://stackoverflow.com/questions/7634292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add files to uploadify from code? I like uploadify but I need to incorporate a drag'n drop module for the browsers that support this feature. Right now the only way to select files is via the browser dialog window. I'd like to have something like: $("mySelector").uploadify("addFile",{src:...; name:...; etc:...}); This would allow me to get the paths of the files dropped into the browser add them to the upload queue. Is there any way I could achieve this? A: You need something like this http://aquantum-demo.appspot.com/file-upload Note: Uploading files are only possible from file-type-input (browser dialog window), for security reasons. You cannot read path from file-type-input. Not even using JS. Nor you can write the path to a file-type-input. The plugins like mentioned above, are the UX tricks but all are limited to this security constraint of using file-type-input for uploads. Else, you need something in the line of Flash, ActiveX uploaders, etc that provide queue uploads. A: Well after a few months of research it turns out that the file implementation of flash is incompatible with the file implementation of HTML5 that starts to be supported by more and more browsers. In other words, for security reasons, there is not bridge for sending file objects between the languages. One research idea would be to implement such a bridge, but that is a discussion for another time. Uploadify 2.x does not support this feature.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: custom templated listboxitem trigger bind to the listbox I have a class inherited from ListBox and a custom ControlTemplate for the ListBoxItems. I want to change the ListBoxItems background if a condition is true. I tried to use DataTrigger for this. I don't want to check the condition in the ListBoxItems context object, I want to check it in the inherited ListBox class. The question is how can I bind in the ControlTemplate the Trigger to a ListBox property, when it needs to decide the right value for each ListBoxItem in runtime? <Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <Border Name="bd"> <TextBlock Name="lbl" Text="{Binding Path=DataChar}" FontWeight="ExtraBold" FontSize="15" Margin="5"/> </Border> <ControlTemplate.Triggers> <DataTrigger Binding="{Binding RelativeSource={ RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}, Path=IsSymbolExists}" Value="True"> <Setter TargetName="bd" Property="Background" Value="Yellow" /> </DataTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> public class CustomListBox : ListBox { ... public bool IsSymbolExists { if(/*condition is true for the ListBoxItem*/) return true; return false; } } A: Ok firstly few suggestions... Does your custom listbox control have only new properties (IsSymbolExists etc.) and no real behavior. If so please declare them as Attached Properties Secondly when this value IsSymbolExists becomes true for a ListBox ALL its items will become highlighted individually by a yellow border. This doesnt look like a well thought UI behavior. Sorry if that comes to you as a bit harsh! Also from the binding perspective the DataChar property looks like a data context based property i.e.e coming from some model. If so then its binding has to be done through an ItemTemplate under ListBox and not in a TextBlock under ControlTemplate of a ListBoxItem. And for exactly the same reason, DataTrigger wont work correctly in ControlTemplate. They will work correctly in ItemTemplate. So to summarize, your code needs to be fixed this way... * *You can get rid of CustomListBox. Create a boolean attached property called MyListBoxBehavior.IsSymbolExists. Attach it to your ListBox. *You should get rid of ListBoxItem's ControlTemplate. In ListBox take helpm from this... (this code wont compile as it is) :-) <ListBox local:MyListBoxBehavior.IsSymbolExists="{Binding WhateverBoolean}" ItemsSource="{Binding WhateverCollection}"> <ListBox.ItemTemplate> <DataTemplate> <Border> <Border.Style> <Style TargetType="{x:Type Border}"> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}, Path=local:MyListBoxBehavior.IsSymbolExists}" Value="True"> <Setter Property="Background" Value="Yellow" /> </DataTrigger> </Style.Triggers> </Style> </Border.Style> <TextBlock Name="lbl" Text="{Binding Path=DataChar}" FontWeight="ExtraBold" FontSize="15" Margin="5"/> </Border> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best way to distribute a Python package that requires a minimal Python version I have a Python 2 project ('foo 0.1.7') that required Python 2.4 or later. Now I ported it to Python 3 ('foo 0.2.0') in a way that it still is compatible with Python 2, but the requirements are now lifted to Python 2.6 or later. * *I know that there is a --target-version=2.6 option for setup.py, that can be used with upload, but that seems not to be meant as '2.6 or higher' *The setup command has an install_requires option, but this is for required packages, .not Python interpreter. I could do something like this in setup.py of 'foo 0.2.0': if sys.hexversion < 0x02060000: raise RuntimeError('This package requires Python 2.6 or later, try foo 0.1.7') but I would prefer if easy_install foo would resolve this in some way. So, how should I deploy this on PyPI? A: I know that there is a --target-version=2.6 option for setup.py, that can be used with upload, but that seems not to be meant as '2.6 or higher' It is actually an option for bdist_wininst or bdist_msi, and indeed does not include “or higher”. The setup command has an install_requires option, but this is for required packages, .not Python interpreter. Maybe putting 'Python >= 2.6' in install_requires could work: Python 2.5 up to 3.2 create a Python-blahblah-pyXY.egg-info file, so if you’re lucky easy_install may find that the requirement is satisfied. If not it will probably try to download from PyPI, so uh... I could do something like this in setup.py of 'foo 0.2.0': if sys.hexversion < 0x02060000: raise RuntimeError('This package requires Python 2.6 or later, try foo 0.1.7') This is actually the current common idiom. In addition, using the “Programming Language :: Python :: X.Y” trove classifiers will give information for humans (I’m not aware of any tool using that info). In the short-term future, there is hope. The specification for Python distributions metadata has been updated, and the latest version does contain a field to require a specific Python version: http://www.python.org/dev/peps/pep-0345/#requires-python Regarding tool support: distutils is frozen and won’t support it, setuptools may or may not add support, its fork distribute will probably gain support, and distutils2/packaging already supports it. distutils2 includes a basic installer called pysetup, which should respect the Requires-Python field (if not, please report to bugs.python.org). Now, to address your problem right now, you can do one of these things: - declare that your project only supports 2.6+ - document that 2.4 users need to pin the version when downloading (e.g. pip install "foo==0.1.7") A: What it sounds like you're looking for is a way to upload both version 0.1.7 and 0.2.0 of your program, and have easy_install-2.5 automatically use 0.1.7, while easy_install-2.6 would use 0.2.0. If that's the case, I'm not sure if it's possible to do with the current system... the raise RuntimeError() check might be the best option currently available; people who install your project would then have to manually easy_install-2.5 -U "proj<0.2", or something similar. That said, there's a dedicated group currently working to replace distutils, setuptools, etc with an updated library named packaging. This new library combines the features of the existing distutils enhancement libraries, as well as a host of other improvements. It's slated for inclusion in Python 3.3, and then to be backported as distutils2. Of special relevance to your question, it contains many enhancements to the setup metadata; including a "requires_python" option, which seems tailor made to indicate exactly the information you want. However, I'm not sure how they plan to make use of this information, and if it will cause the new setup system to behave like you wanted. I'd recommended posting to the fellowship of the packaging, the google group dedicated to the development of the new system, they would be able to give details about how requires_python is supposed to work... and possibly get the installation behavior you want in on the ground floor of the new system if it seems feasable (and isn't already there).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: instead of ? I've inherited an existing website to maintain and upgrade. One of the site's quirks is how it does buttons. It has html like this: <div class="btn"> <a id="dv_remCont" runat="server" href="#" onclick="removeContact();">remove contact</a> </div> and css like this: div.btn a { font-weight:bold; display:inline-block; border-radius: 2px; padding: 0 1.2em 0 1.2em; color:#ffffff; background-color:black; box-shadow: 0px 0px 5px 1px #898986, inset -1px -1px 1px rgba(0,0,0,0.5), inset 1px 1px 1px rgba(255,255,255,0.8), 0px 0px 1px 1px #000000; } div.btn a:hover { box-shadow: 0px 0px 5px 1px #898986, inset 1px 1px 1px rgba(0,0,0,0.5), inset -1px -1px 1px rgba(255,255,255,0.8), 0px 0px 1px 1px #000000; } This creates a clickable button. It does cause some complications, though - not using a regular <button /> means default functionality for stuff like forms doesn't work. Also, there are some issues with alignment in IE8 and below. What are the advantages of doing buttons like this? Have you seen them done in this style before? A: I can think of no specific reason to do this - other than the developer not being able to quite reset the button style to nothing before creating the custom style. For example, even if you reset all padding, border, background, margin - the button still doesn't quite look unstyled in Firefox 3.6 or IE 7 or 8 - which if you've inherited the code are probably the target browsers when it was being written. This is an example you can use to play with - I have added a border reset to the style to make the button and fake button look closer, You would also have to add text-decoration: underline if you want it to look exactly the same, but I couldn't bring myself to have a button that already looks clickable include an underline! http://jsfiddle.net/Sohnee/7Eakq/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7634305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.net Script Manager Memory Leak I am using asp.net script manager and the code is as given below: <asp:ScriptReference Path="~/Scripts/jquery-1.5.1.min.js" /> <asp:ScriptReference Path="~/Scripts/Core.js" /> <asp:ScriptReference Path="~/Scripts/TomasCore.js" /> <asp:ScriptReference Path="~/Scripts/jquery-ui-1.8.13.custom.min.js" /> </Scripts> </asp:ScriptManager> When I run this application, the memory usage is creeping up by 5MB for every page refresh. Could anyone please throw light on this?? Thanks, Mahesh A: Chances are there is enough memory and the GC has no reason to kick in and free memory yet. You should test what happens if you loop like 200 calls. Also can you reproduce this if you remove the ScriptManager?
{ "language": "en", "url": "https://stackoverflow.com/questions/7634308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Host WCF in a Windows Service Using TCP I'm trying to host a wcf service (tcp) in a windows service on Windows 2008 x64. I first made a normal program as host and that works fine. I then made a windows service with the same config: http://msdn.microsoft.com/en-us/library/ff649818.aspx The server installed fine en starts without a problem, but I can't connect to it. I think the program isn't loading the config file (exename.config) because myServiceHost.BaseAddresses is empty. Any idea what could cause this or how I can find the error? Here is my config: <?xml version="1.0"?> <configuration> <system.web> <compilation debug="false" /> </system.web> <system.serviceModel> <services> <service behaviorConfiguration="SlmWcfServiceLibrary.Service1Behavior" name="SlmWcfServiceLibrary.SlmService"> <endpoint address="" binding="netTcpBinding" bindingConfiguration="" contract="SlmWcfServiceLibrary.ISlmService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:9999/Service1/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="SlmWcfServiceLibrary.Service1Behavior"> <serviceMetadata httpGetEnabled="False" /> <serviceDebug includeExceptionDetailInFaults="False" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <startup></startup> </configuration>
{ "language": "en", "url": "https://stackoverflow.com/questions/7634309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Better way to build XML string via Javascript I currently have the below to build up a XML string which will get sent via a socket and was wondering if there was a better way to build it in terms of readability. I thought I had read somewhere where you can have shortcut type ways of adding elements to the DOM but didn't know if this applied to strings/XML objects. var jqInputs = $('input', nRow); //Get all inputs var updatedValues = []; jqInputs.each(function (idx) { updatedValues.push($(this).val()); //Put values into array }); //Get table columns var cols = $('th').filter(function (index) { return $(this).text() != "" && $(this).text() != "Edit"; }); var colnames = []; //Get table column names and put into array $.each(cols, function () { colnames.push($(this).text()); }); //Build up XML and send to server if (updatedValues.length == colnames.length) { //****************************** //** IS THERE A BETTER WAY TO DO THIS?????** //****************************** var xmlvalue; for(var i = 0; i < updatedValues.length;i++) { xmlvalue = xmlvalue + '<' + colnames[i] + '>' + updatedValues[i] + '<\' + colnames[i] + '>' } socket.send('<Root>'+ xmlvalue +'<UserID>1</UserID></Root>'); } A: Can you use e4x? If so, xml is a piece of cake: var xmlv = <Root />; for(var i = 0; i < updatedValues.length;i++) xmlv.appendChild(<{colnames[i]}>{updatedValues[i]}</{colnames[i]}>); xmlv.appendChild(<UserID>1</UserID>); socket.send(xmlv.toXMLString());
{ "language": "en", "url": "https://stackoverflow.com/questions/7634312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to calculate time elapsed since an action without the danger of the user changes the time Hi i am developing an application and i want the user to be able to kill an enemy again after 12 hours have passed. How can i do this to avoid the possibility of the user changing the time in his phone and enabling again the option to kill an enemy? A: Use a sticky service. Every time you kill an enemy, run a CountdownTimer. However I think this is overkill, If it is a simple game that you are making, you should store the elapsed time since boot. Then regenerate the enemy if the time difference is > 12 hours.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Start camera activity in a thread and it runs twice I am using a thread, (tested Runnable, Asynch) to implement a delay and then start camera activity, but the problem is after taking a pic and returing back camera is launched again, so my camera activity is lunched twice, what could be the sol. I have used Runnable as well for implementing thread. Thanks. public void onCreate(Bundle savedInstanceState) { Thread_as obj=new Threads_as(); obj.execute(""); } ............ doInBackground(){ int timer=0; while(timer<2000) { Thread.sleep(100); timer+=100; }} onPostExecute(){ Intent it=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivity(it); } A: Do you run the AsyncTask every time the original activity is started?
{ "language": "en", "url": "https://stackoverflow.com/questions/7634321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python generators: correct code recursing a tree class Node(object): def __init__(self, lst): if type(lst) == list: self.value = lst[0] self.children = lst[1:] else: self.value = lst self.children = [] @property def ChildElements(self): return [Node(a) for a in self.children] @property def GetValue(self): return self.value def node_recurse_generator(node): yield node.value for n in node.ChildElements: node_recurse_generator(n) Node is a simple tree like data structure. The list's first element is always the value of the Node, further elements will be children. If the Node is initiated with something other than a list, that value will be that, and children will be [], an empty list. a = Node([1,[10,20,30],[100,200,300]]) >>> list(node_recurse_generator(a)) [1] Now, it would be great to have a recursive iterator over all the elements, but my generator only yields the first element. Why is this happening? A: As yak mentioned in the comment of the top answer, you can also use yield from after Python 3.3. def node_recurse_generator(node): yield node.value for n in node.ChildElements: yield from node_recurse_generator(n) A: Simply calling node_recurse_generator recursively isn't enough - you have to yield its results: def node_recurse_generator(node): yield node.value for n in node.ChildElements: for rn in node_recurse_generator(n): yield rn
{ "language": "en", "url": "https://stackoverflow.com/questions/7634323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: how to detect touch on rotated sprite in cocos2d I have rotated sprite to 90. I checked the touch location of the rotated sprite as follows: matchsprite.rotation=90; CGRect r=CGRectMake(matchstick.position.x, matchstick.position.y, matchstick.contentSize.height,matchstick.contentSize.width); if(CGRectContainsPoint(r, location)) NSLog(@"Hii"); What is the error in this code? I didnt get "Hii". How to detect whether we tap that rotated sprite or not? A: Here are the two CCNode extension (category) methods I've added to the Kobold2D game engine: -(BOOL) containsPoint:(CGPoint)point { CGRect bbox = CGRectMake(0, 0, contentSize_.width, contentSize_.height); CGPoint locationInNodeSpace = [self convertToNodeSpace:point]; return CGRectContainsPoint(bbox, locationInNodeSpace); } -(BOOL) containsTouch:(UITouch*)touch { CCDirector* director = [CCDirector sharedDirector]; CGPoint locationGL = [director convertToGL:[touch locationInView:director.openGLView]]; return [self containsPoint:locationGL]; } Testing if a point is on a sprite (or label or any other node) then is as simple as: UITouch* uiTouch = [touches anyObject]; if ([aSprite containsTouch:uiTouch]) { // do something } A: The position property of ccsprite gives you the centre coordinate and not the top left corner position. you can get the rect made like this CGRect r=CGRectMake(matchstick.position.x - matchstick.contentSize.width / 2, matchstick.position.y + matchstick.contentSize.height / 2, matchstick.contentSize.height, matchstick.contentSize.width); I am not sure if you need to subtract or add half of the width but i think you can do a little R&D on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do i pass an array function without using pointers I have been asked in an interview how do you pass an array to a function without using any pointers but it seems to be impossible or there is way to do this? A: Put the array into a structure: #include <stdio.h> typedef struct { int Array[10]; } ArrayStruct; void printArray(ArrayStruct a) { int i; for (i = 0; i < 10; i++) printf("%d\n", a.Array[i]); } int main(void) { ArrayStruct a; int i; for (i = 0; i < 10; i++) a.Array[i] = i * i; printArray(a); return 0; } A: How about varargs? See man stdarg. This is how printf() accepts multiple arguments. A: If i say directly then it is not possible...! but you can do this is by some other indirect way 1> pack all array in one structure & pass structure by pass by value 2> pass each element of array by variable argument in function A: You can put the array into a structure like this: struct int_array { int data[128]; }; This structure can be passed by value: void meanval(struct int_array ar); Of course you need to now the array size at compile time and it is not very wise to pass large structures by value. But that way it is at least possible. A: simply pass the location of base element and then accept it as 'int a[]'. Here's an example:- main() { int a[]={0,1,2,3,4,5,6,7,8,9}; display(a); } display(int a[]) { int i; for(i=0;i<10;i++) printf("%d ",a[i]); } A: void func(int a) { int* arr = (int*)a; cout<<arr[2]<<"...Voila" ; } int main() { int arr[] = {17,27,37,47,57}; int b = (int)arr; func(b); } A: There is one more way: by passing size of array along with name of array. int third(int[], int ); main() { int size, i; scanf("%d", &size); int a[size]; printf("\nArray elemts"); for(i = 0; i < size; i++) scanf("%d",&a[i]); third(a,size); } int third(int array[], int size) { /* Array elements can be accessed inside without using pointers */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: python regular expression exclude from match string I have 3 strings a ="keep the your pass ABCDEFG other text" b ="your pass: TESTVALUE other text" c ="no pass required other text" I want to get capital values after pass, like this re.match(r'.*\spass:?\s([a-zA-Z]+).*',a,re.I).group(1) re.match(r'.*\spass:?\s([a-zA-Z]+).*',b,re.I).group(1) but I want to exclude "no pass", which is I don't want re to match to c string, how do I do that? Solution: Thanks eyquem and ovgolovin I will take eyquem's suggestion of re.search('no\s+pass|pass:?\s+([A-Z]+)') A: import re for x in ("keep the your pass ABCDEFG other text", "your pass: TESTVALUE other text", "no pass required other text"): print re.search('no\s+pass|pass:?\s+([A-Z]+)',x).group(1) A-Z]+)' result ABCDEFG TESTVALUE None A: It's not OK to use match here. It's preferable to use search for such cases. re.search(r'(?<!no\s)pass:?\s+([A-Z]+)',a).group(1) It would be better to write it this way: re.search(r'(?<!no\s*)pass:?\s+([A-Z]+)',a).group(1) , but unfortunatelly the current version of regex engine doesn't support infinite lookbehinds. A: A solution would be to first , filter everything which doesn't contains 'no pass' and then search for pass. Doing two steps might seem a bit heavy but you will avoid lots of problems by doing it this way. You are trying to solve two problems at the same time (and apparently you are struggling to do it) so just separate the two problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Null is type object, so it's truthy? What's going on behind the scenes? I'm reading in my book, "Elegant JavaScript", that null == true evaluates as false. Using an interpreter, I have confirmed this to be TRUE. However, later in the chapter--in fact, on the same page--, it says that when null is given as the condition of an if, while, or for statement, it will be converted to a Boolean and return false. Can anybody with a deeper insight tell me why this is? I know where to find browser source code, but I'm not sure how to target the programming that is responsible for this peculiar and unintuive behavior. Because I know very little C++, I would also appreciate any tips on finding info like this, independently. Thank you. A: An important distinction to make is that the Type of null is Null. (ignore typeof it returns "object" for null because of bad design and backwards compatibility) 11.9.3 The Abstract Equality Comparison Algorithm # Ⓣ The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows: [... stripped] *Return false. The ES5 specification Says that the comparison with null and a Boolean should return false because the Type of Null and Boolean are not the same, and none of the other steps in 11.9.3 apply so the default action of return false happens The only case where the Type of x and y are different and either x or y is null but the == operation still returns true are If x is null and y is undefined, return true. If x is undefined and y is null, return true. That means undefined == null returns true Of special note: There is an ES6:harmony proposal to fix typeof null A: Actually I think he refers to the fact that typeof null == 'object', which is unfortunately the case. But that's a peculiarity of the typeof operator, not of null itself. Null is falsy value, but typeof returns "object" for it, according to the spec: http://bclary.com/2004/11/07/#a-11.4.3 A: When you compare null to true, it's evaluated as false, so it's not equal to true. Similarly, when used in any other context where it must be treated as a boolean — like an if or while expression — it's false. It's not really correct to say that "null is type object", because it is not. It is null. It doesn't really have any type, (Thanks @Roee Gavirel) It's got it's own type (the null type) because it isn't anything. In other words, if a variable has the value null, that means that it is referring to nothing; no object at all. edit — crap hold on a sec because my brain's still asleep. OK here's what's in the spec. If one of the operands of == is boolean, then the boolean is converted to a number (yes really) and the conversion proceeds that way. That's why null is == to neither true nor false. The "strangeness", therefore, is not so much about null as it is about the complicated rules for evaluating == comparisons. Section 11.9.3 of the ECMA-262 standard spells it all out in a more-or-less understandable way. Suffice to say that the semantics of == are not at all simple. A: I don't see what the problem... if (null == true) = false then (null == false) = true. if "why" is the question, then the answer is ease of use. (probably taken from C) but if you wish to know if a reference is valid or not you can just do: if (RefValue) { //bla bla bla } Rather then: if (RefValue == null) { //bla bla bla }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Keyboard hide event with BACK key I've noticed in the Android Market Application, when you click over the search button, it shows the keyboard, but when you click the back button, the search EditText becomes invisible and the keyboard is hidden. The problem is that I can't hide the EditText after the keyboard is hidden after pressing the back key because I can't find a listener for hiding the keyboard event. I found this sample How to capture the "virtual keyboard show/hide" event in Android? but it doesn't work on the soft keyboard. A: I think you should handle this using focus: final InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); edttext.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(!(hasFocus)) { mgr.hideSoftInputFromWindow(edttext.getWindowToken(), 0); } } }); A: You need to implement this to capture the BACK button before it is dispatched to the IME: http://developer.android.com/reference/android/view/View.html#onKeyPreIme(int, android.view.KeyEvent) A: Hey i think the market app is using the googleSearch dialog (check out Searcheable activity ). You can implement the editText in a popupWindow, and set the poupwindow as focusable. Show the keyboard when your popup is shown. in onDismiss hide the keyboard. popupWindow.setFocusable(true); popupWindow.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { // TODO Auto-generated method stub inputMethodManager.hideSoftInputFromWindow( edttxtSearchBar.getWindowToken(), 0); } This will ensure, you click anywhere outside popup or press back the popup disappears as well(along with keyboard). A: The google market application is using Fragments via the API Support Package. When you click back it is actually going back in the fragment stack. It's like going back an activity without the screen swipe. The fragment that they go back to does not contain the search box which is why it disappears. A: **perfect answer** REFER THIS **SIMPLE EXAMPLE**...ITS TOOOO GOOOODDDD KTBEditTextWithListener.java // Custom edittext import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; public class KTBEditTextWithListener extends android.widget.EditText { public KTBEditTextWithListener(Context context) { super(context); // TODO Auto-generated constructor stub } public KTBEditTextWithListener(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // createFont(context); } public KTBEditTextWithListener(Context context, AttributeSet attrs) { super(context, attrs); // createFont(context); } private BackPressedListener mOnImeBack; /* constructors */ @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { if (mOnImeBack != null) mOnImeBack.onImeBack(this); } return super.dispatchKeyEvent(event); } public void setBackPressedListener(BackPressedListener listener) { mOnImeBack = listener; } public interface BackPressedListener { void onImeBack(KTBEditTextWithListener editText); } } //my_layout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <com.ktb.gopharma.views.KTBEditTextWithListener android:id="@+id/edit_text" style="@style/match_width"> </com.ktb.gopharma.views.KTBEditTextWithListener> </LinearLayout> //MyActivity.java package com.ktb.gopharma; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import com.ktb.gopharma.views.KTBEditTextWithListener; import com.ktb.gopharma.views.KTBEditTextWithListener.BackPressedListener; import com.ktechbeans.gopharma.R; public class MyActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_layout); KTBEditTextWithListener editText = (KTBEditTextWithListener) findViewById(R.id.edit_text); editText.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { showToast("keypad opn"); } }); editText.setBackPressedListener(new BackPressedListener() { @Override public void onImeBack(KTBEditTextWithListener editText) { showToast("keypad close"); } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Why does my Timer come back null when I have inherited it? I have the interface: public interface IProcess { void Step_One(); void Step_Two(); Timer ProcessTimer{get; set;} } the base class.. public class ProcessBase { protected Timer processTimer; public Timer ProcessTimer{get{ return processTimer;}set{processTimer=value;}} //sets up all the common objects public ProcessBase() { } //This constructor will call the default constructor ^ protected ProcessBase(long intervalArg) : this() { processTimer = new Timer(intervalArg); processTimer.Enabled = true; } } the concrete class public class ReportedContentProcess : ProcessBase, IProcess { public ReportedContentProcess(): base(5000) { } public void Step_One() { } public void Step_Two() { } } but when I try and get it out in a factory... public static class ProcessFactory { public static List<IProcess> GetProcessors() { ReportedContentProcess.ReportedContentProcess reportedContentProcess = new ReportedContentProcess.ReportedContentProcess(); List<IProcess> retProcesses = new List<IProcess>(); retProcesses.Add(reportedContentProcess); return retProcesses; } } and then attach a handler to the timer... processorsForService = ProcessFactory.GetProcessors(); foreach(IProcess p in processorsForService) { p.ProcessTimer.Elapsed += new ElapsedEventHandler(IProcess_Timer_Elapsed); } I get a run-time error saying that the p.ProcessTimer is null. Why is this? I have inherited and instantiated in the base class cant understand why its null. Ive even included it in the interface... A: I see that you're initializing Timer in second constructor only. What if the default one is called (i.e. the constructor that is without params)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7634349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery issue in ie7 and ie8 I have a problem in jQuery in IE7 and IE8. In all other browsers the script is working fine. When I copy to clipword I found this error: Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) Timestamp: Mon, 3 Oct 2011 11:24:50 UTC Message: Could not get the position property. Invalid argument. Line: 16 Char: 79183 Code: 0 URI: http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js Message: Could not get the position property. Invalid argument. Line: 16 Char: 79183 Code: 0 URI: http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js If I try with the full, non-minified jQuery (1.5.1) it still produces the error. The website is located here. When you click on Collection then two images open when you click on one of images. Then, you will able to see the exact problem. A: When I viewed the link I go an error Could not get the position property. Invalid argument. I tracked it down through the stack trace and it appears that your problem comes from your jquery.template.js file in animateHeadingDesc function. In that function you make a call to paramHeading.position='absolute'; which is not the correct usage of .position(). jQuery Position doc It looks like you want to apply a CSS position property which can by applied by using something like paramHeading.css('position','absolute'); It also looks like you're trying to animate the element being set to position:absolute which I'm pretty sure jQuery can't do. It would be a good idea to set that first and then animate your element. A: I get alot of errors of missing images, for example when I click on a picture in the Collection. "NetworkError: 404 Not Found - http://indivar.info/AnimatedContentMenu/kitchen2/2.jpg" 2.jpg "NetworkError: 404 Not Found - http://indivar.info/AnimatedContentMenu/kitchen2/1.jpg" 1.jpg "NetworkError: 404 Not Found - http://indivar.info/AnimatedContentMenu/kitchen2/3.jpg" 3.jpg "NetworkError: 404 Not Found - http://indivar.info/AnimatedContentMenu/kitchen2/4.jpg" 4.jpg "NetworkError: 404 Not Found - http://indivar.info/AnimatedContentMenu/kitchen2/5.jpg" 5.jpg "NetworkError: 404 Not Found - http://indivar.info/AnimatedContentMenu/kitchen2/6.jpg" I even get an undefined error when some script is trying to fetch something from an url http://indivar.info/AnimatedContentMenu/undefined 404 (Not Found) Check which script is trying to get a value here, but returns undefined. If you think that the jquery declaration is the problem, download the jquery source instead of taking it from google. http://code.jquery.com/jquery-1.6.4.min.js Copy paste that into a file on your server and run it from there. Remember to declare the jquery before other scripts which depend on jquery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disjoint union-find analysis In disjoint union suppose we have to merge two trees whose heights are respectively h1 and h2. Using this technique, the height of the resulted merged tree will be max(h1, h2) if h1 not equal to h2, or h1+1 if h1 == h2. Using this technique after an arbitrary sequence of merge operations starting from initial situation, a tree containing 'k' nodes has a height at most (floor of logk). This is proved by induction as follows. Base: when k=1 height is 0. 0<= (floor(log 1)) Induction step: consider k >1 and by hypothesis therorm is true for all m such that 1<=m<k. A tree containing k nodes can be obtained by merging two smaller subtrees. suppose these two smaller trees contain respectively 'a' and 'b' nodes where we may assume with out loss of generality a<=b. Now a>=1, therefore there is no way of obtaining a tree with zero nodes starting from the initial situation, and k=a+b. It follows that a<=k/2 and b<=k+1, since k>1, both k/2 < k, and (k-1) < k and hence a<k, and b<k. My question on above is * *How we got "It follows that a<=k/2 and b<=k+1" statement above. Thanks! A: Let's assume a > k/2, then b > k/2, because b>=a. Then a + b > k/2 + k/2. Thus, a + b > k. But we have k = a + b! So the assumption that a > k/2 is leads to a contradiction, and is thus false. This 'proves' that a <= k/2. In english: if we split k in two parts a and b, where b is bigger half, than a must be less than half of k.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the simplest way to randomise the order of frames in AS3 without repeats? I have a scene in a flash project where I want the order of the frames to be randomised at run-time. I want each frame to be shown exactly once. I want the duration of each presentation to be constant. I've been playing around with a couple of David Stiller's suggestions: * *How to Jump to a Random Frame Label *How to Jump Randomly to Frame Labels without Repeats They're a bit outdated (Void rather than void, this._totalframes - 1 rather than MovieClip.totalFrames), but the principal seems sound. Still, the approach seems less than optimal. David's examples work really well for a small number of sequences of frames. But I have around 100 individual frames. What is the best way to do this? My wishlist: * *No need to label each frame individually *Ideally, no need to repeat code on each frame *Easy to change the duration of each frame presention I'm not experience in Flash, so I be asking for something obviously impossible, but I'd be interested to see suggestions about how best to proceed. A: Without much thought put into it, I would do something like this: (not tested) //On frame 1 on a clear layer present on all frames. First frame should probably be empty var frames:Array = []; for(var i:Number = 1; i<this.totalFrames, i++) { frames.push(i+1); } this.addEventListener(Event.ENTER_FRAME, frameFunc); function frameFunc(e:Event) { var frameNum:Number = Math.floor(Math.random()*frames.length); var frame:Number = frames[frameNum]; frames[frameNum] = frames.pop(); //You could also use splice. gotoAndStop(frame); } stop();
{ "language": "en", "url": "https://stackoverflow.com/questions/7634360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Assembler instructions bne and br (NIOS II). How is their offset calculated? I have this assembler code, which I'm supposed to translate into machine code in binary form: .text .align 2 .global main .equ val,0x4712 main: movi r16,val movi r17,0 loop: addi r17,r17,1 subi r16,r16,1 bne r16,r0,loop stop: br stop .end and I'm not sure how "bne r16,r0,loop" and "br stop" is interpreted. My instruction set reference says that the bne instruction does this: if(rA != rB) then PC ← PC + 4 + σ(IMM16) else PC ← PC +4 which, as I understand it, is the program counter being incremented by 4 + offset or simply by 4. But, in my case, what is the offset/IMM16 value? The instruction set reference says: "In the instruction encoding, the offset given by IMM16 is treated as a signed number of bytes relative to the instruction immediately following bne". My interpretation of this is that the IMM16 value is the "distance" to the next instruction address, but I have no idea if this is correct. The hex-address for bne is 0x40010 and 0x40014 for br, so this would mean that the IMM16 value is 4? (which would result in PC jumping past the 0x40014 address if rA != rB?) A: Disclaimer: I'm not completely sure what instruction set this is, so I'll try to stick to what is usually the case for assembly languages. if(rA != rB) then PC ← PC + 4 + σ(IMM16) else PC ← PC +4 which, as I understand it, is the program counter being incremented by 4 + offset or simply by 4. This is correct. It might be helpful to keep in mind that the CPU will basically always do PC ← PC + 4 after fetching an instruction to move the program counter to the following instruction for the next cycle. So even a NOP would have the effective result of PC +=4 (when instructions are 4 bytes in length). Wikipedia has more. Also since IMM16 can be negative you can jump backwards. But, in my case, what is the offset/IMM16 value? The instruction set reference says: "In the instruction encoding, the offset given by IMM16 is treated as a signed number of bytes relative to the instruction immediately following bne". My interpretation of this is that the IMM16 value is the "distance" to the next instruction address, but I have no idea if this is correct. The hex-address for bne is 0x40010 and 0x40014 for br, so this would mean that the IMM16 value is 4? (which would result in PC jumping past the 0x40014 address if rA != rB?) The IMM16 value is the distance, but it's the distance (in bytes) to the instruction you want to jump to in case rA != rB! So in this case you want the immediate to be the distance from the instruction following bne (because the distance is relative to the following instruction) to the place you want to jump to (loop). In this case (if my calculations are correct) address(jump-target) - (address(bne-instruction) + 4) = 0x40008 - (0x40010 + 4) = -12 = ~12 + 1 = 0xfff4 (16-bit). As you're worried about instruction encoding be careful to note the sigma function applied to the immediate. I'll take an educated guess and assume that it multiplies the immediate by 4, and the instruction encoding would then contain the number of instructions to jump minus one. That is -12 bytes would probably be encoded as the 16-bit signed value 0xfffc = -3, since we want to jump two instructions back with bne and thus 3 instructions back from the instruction following bne. If that's true, then I still don't understand what IMM16-value br has since there are no following instructions. Maybe it's zero when the label is "stop"? (or what bne would result in if rA != rB and PC ← PC + 4 + σ(IMM16)). Be aware that br might have a different encoding (it could be e.g. be an absolute offset or it could be a different size). I'm not familiar enough with the instruction set at hand to know, but I can give the general idea: You're not really using the address of the following instruction, rather you're using the address of the current instruction + 4 (which if an instruction follows would be the address of that instruction).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: get webmethods available in webservice url I am using c# vs 2008. I need to call a web service URL in c#. I need to list the methods in a check box in windows application, for eg. i am calling http://localhost:l222/Test.asmx It has three methods. GetUserDetails GetCompanyName GetCustomerDetails I need to list the webmethod in a check box. Is it possible in C# A: Pull the WSDL. It is a xml document. You can use XDocument class to parse it and list the methods. See Parse Complex WSDL Parameter Information A: Every asmx web service has what's called the Web Service Definition, accessed by appending ?wsdl to the web service URL. Once you have and understand this, you can use the code posted by Mike Hadlow: http://mikehadlow.blogspot.com/2006/06/simple-wsdl-object.html ..to get the methods and their parameters. He uses the built-in System.Web.Services.Description.ServiceDescription class to build another class called WebServiceInfo to get the information you require.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grouped UITableView shows weird square border I am having a weird issue with a grouped UITableView. It shows a square border only on one of the views in the app, and only on the terminal that has iOS 3.1.3. Here you have an screenshot of the thing: I am setting it up only through the Interface Builder, here are the settings: The rest of the table views that are similarly set up in the app work just fine. Does anyone have a clue about what might be causing this? EDIT: Setting the background color to clear color caused this: A: This problem troubled me too. I too asked this question on bStackOverflow. Check it out. It is the right solution. A: in viewwillAppear method of your class set the backgroundcolor of your tableview as clearcolor like this self.tableView.backgroundColor = [UIColor clearColor]; or in the xib file in view section of the table set the background property as clear color.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android.graphics.Matrix -> How does postScale work Good afternoon, Lets say I have a Matrix. I have 2 values, .9 for zooming out and 1.1 for zooming in. When I apply the matrix.postScale(0.9, 0.9); 3 times Then I apply the matrix.postScale(1.1, 1.1); 3 times I am not back where I started!! for example, here are the results I recorded: Current Scale postScale (x, x) Resulting Scale 1 .9 .9 .9 .9 .80999994 .80999994 .9 .7189999 .7189999 1.1 .8018999 .8018999 1.1 .8820899 .8820899 1.1 .97029895 As you can see I'm not back to 1. What is going on, am I getting the current scale incorrectly? For example, to get all the values on the right, I preformed this after the postScale was applied: matrix.getValues(tempArrayFloat); Number = tempArrayFloat[Matrix.MSCALE_X]; I just assumed that the MSCALE_X and MSCALE_Y would be the same? My question is, if I scale a matrix using 1 specific value 3 times, .9 -> .9 -> .9, what number do I need to scale it back to it's original position? -Kind Regards, Paul A: The numbers in the right hand side of your table give you your answer, a scaling matrix multiplies points by the scaling value. So applying matrix.postScale(0.9) three times scales by 0.9*0.9*0.9 = 0.729. Applying matrix.postScale(1.1) three times scales by 1.1*1.1*1.1=1.331. To get back where you started, you need to scale by 1.0/0.729=1.372 A: Scale it back by using 1.111111112 instead of 1.1, but if you are scaling a bitmap it may be easier to resize it to a round value. Basically you could state matrix.postScale(1.0/0.9, 1.0/0.9); this should round it to the nearest pixel
{ "language": "en", "url": "https://stackoverflow.com/questions/7634366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Encoding of tweets acquired through twitteR package I don't know how to tell searchTwitter() function to encode tweets like UTF-8. I want "šćčđž" or "шђжћч" characters in the list. Can anyone help? A: Try looking at Tony Breyal's answer regarding RJSONIO and see if it helps: encoding issue using twitteR R package for Cyrillic tweets
{ "language": "en", "url": "https://stackoverflow.com/questions/7634367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I reference a variable in a Perl substitution script? I am writing a Perl script to change all URLs within several files in one directory from camel case to lowercase. e.g. from <a href="FooBar.html"> to <a href="foobar.html"> This test substitution correctly renames all URLs to foobartest.html as expected: s/^<a href=\"(.*?)\"/<a href=\"foobartest.html\"/g But I am having difficulty in referencing the actual filename via the variable $1. An example of what I am trying: s/^<a href=\"(.*?)\"/<a href=\"\L$1\"/g This substitution merely changes the link to . What am I missing? You can probably tell I'm fairly new to Perl, and so any guidance would be much appreciated. Full script for reading files within a directory and substituting (writing it as a one-liner does not work either, despite other substitutions working via one line): #!/usr/bin/perl use strict; use warnings; chdir("/var/www/html/twiki_html") or die "$!"; opendir (DIR, ".") or die "$!"; my @files = grep {/.*?\.html/} readdir DIR; close DIR; { local @ARGV = @files; while(<>){ s/^<a href=\""(.*?)\"/<a href=\"\L$1\"/g; } } A: A simple one-liner: perl -pwe 's/(?<=<a href=")([^"]+)(?=")/\L$1/' *.html It will not change anything, just display the changes. So, when you are satisfied it works, you can add -i to the options to make changes to the files. Be aware that changes are irreversible. Use -i.bak to keep backups. E.g.: perl -i.bak -pwe 's/(?<=<a href=")([^"]+)(?=")/\L$1/' *.html A: Your code works for me. So I guess that any problems must be in the code that you're not showing us. #!/usr/bin/env perl use strict; use warnings; use 5.010; $_ = '<a href="FooBar.html">'; s/^<a href=\"(.*?)\"/<a href=\"\L$1\"/g; say; Running that gives: $ ./html_test <a href="foobar.html">
{ "language": "en", "url": "https://stackoverflow.com/questions/7634370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wp7 app version change I want to submit update for wp7 app. My current version is 1.0. I want to give 1.1 for the update. For submitting update should I change the version attribute of the WMAppManifest file manually or will it be updated automatically based on version no that we give in product form in the app hub.Also do we need to make any change in assemblyinfo.cs file in order to change the version no. A: It won't hurt to change both AssemblyInfo.cs and WMAppManifest.xml, but it's the value that you select during App submission/update that will be displayed to users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Listview clicking on name and then it displays an image Hi I have a created a listview of different countries and want to display and image once the country has been clicked on. I am using the following method: public void onItemClick(AdapterView<?> parent, View view, int position, long id) I am not sure what to put inside the method? A: You can try Toast ImageToast = new Toast(getBaseContext()); LinearLayout toastLayout = new LinearLayout(getBaseContext()); ImageView image = new ImageView() // get Item position; toastLayout.addView(image); ImageToast.setView(toastLayout); ImageToast.setDuration(Toast.LENGTH_LONG); ImageToast.show();
{ "language": "en", "url": "https://stackoverflow.com/questions/7634383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android - center imagebutton in runtime I've got an imagebutton defined in an xml-file. During runtime, I want to make it visible (possible with setVisibility(), so it was no problem) but I also want to center it horizontally, like the XML attribute android:layout_gravity="center_horizontal". How do you do that during runtime, in javacode, though? I couldn't find any methods to use to set the gravity of the imagebutton programmatically. EDIT: am using a RelativeLayout in the xml file EDIT2: the XML code <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal"> <TextView android:text="Unknown" android:layout_width="wrap_content" android:id="@+id/screen_p2pcall_status_text" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_centerHorizontal="true"></TextView> <ImageView android:layout_width="wrap_content" android:src="@drawable/android_avatar_big" android:id="@+id/screen_p2pcall_android" android:layout_height="wrap_content" android:layout_below="@+id/screen_p2pcall_status_icon" android:layout_centerHorizontal="true" android:layout_marginTop="36dp"></ImageView> <ImageView android:layout_width="wrap_content" android:src="@android:drawable/presence_invisible" android:id="@+id/screen_p2pcall_status_icon" android:layout_height="wrap_content" android:layout_below="@+id/screen_p2pcall_status_text" android:layout_centerHorizontal="true"></ImageView> <TextView android:text="Unknown" android:id="@+id/screen_p2pcall_peer" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_height="wrap_content" android:layout_below="@+id/screen_p2pcall_android" android:layout_centerHorizontal="true"></TextView> <ImageButton android:layout_width="120dp" android:id="@+id/screen_p2pcall_hangup" android:src="@drawable/phone_hang_up_48" android:layout_height="50dp" android:layout_below="@+id/screen_p2pcall_peer" android:layout_toRightOf="@+id/screen_p2pcall_status_icon" android:layout_marginTop="18dp"></ImageButton> <ImageButton android:layout_width="120dp" android:id="@+id/screen_p2pcall_answer" android:src="@android:drawable/sym_action_call" android:layout_height="50dp" android:layout_alignTop="@+id/screen_p2pcall_hangup" android:layout_toLeftOf="@+id/screen_p2pcall_hangup"></ImageButton> </RelativeLayout> The java code, where I want to change to center the @+id/screen_p2pcall_hangup horizontally in runtime: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.screen_p2pcall); final ImageButton hangup = (ImageButton)findViewById(R.id.screen_p2pcall_hangup); // ???? } Thanks A: When you use Relative Layout you should add rules to the layout params to center child views. To the relative layout params object you should add the the rule like this rlp.addRule(RelativeLayout.CENTER_HORIZONTAL,RelativeLayout.TRUE); Other rules can be added according to your requirement. Gravity is not possible on relative layout. I assume this is the whole layout xml for the activity. If so, this should work, ImageButton hangupButton = (ImageButton)findViewById(R.id.screen_p2pcall_hangup); int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 120, getResources().getDisplayMetrics()); int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 50, getResources().getDisplayMetrics()); RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(width,height); rlp.addRule(RelativeLayout.CENTER_HORIZONTAL,RelativeLayout.TRUE); hangupButton.setLayoutParams(rlp); hangupButton.setVisibility(RelativeLayout.VISIBLE); Edit:Solution with Code I've edited you xml code a bit to test in my project. There are attributes used that are not usable, such as 'orientation'. It only applies in a linearlayout. Next time when you post a question please break your xml into the next line so that we dont need to scroll left and right to read the whole thing. layout xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="Unknown" android:layout_width="wrap_content" android:id="@+id/screen_p2pcall_status_text" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_centerHorizontal="true"/> <ImageView android:layout_width="wrap_content" android:src="@drawable/icon" android:id="@+id/screen_p2pcall_android" android:layout_height="wrap_content" android:layout_below="@+id/screen_p2pcall_status_icon" android:layout_centerHorizontal="true" android:layout_marginTop="36dp"/> <ImageView android:layout_width="wrap_content" android:src="@android:drawable/presence_invisible" android:id="@+id/screen_p2pcall_status_icon" android:layout_height="wrap_content" android:layout_below="@+id/screen_p2pcall_status_text" android:layout_centerHorizontal="true"/> <TextView android:text="Unknown" android:id="@+id/screen_p2pcall_peer" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_height="wrap_content" android:layout_below="@+id/screen_p2pcall_android" android:layout_centerHorizontal="true"/> <ImageButton android:layout_width="120dp" android:id="@+id/screen_p2pcall_hangup" android:src="@android:drawable/sym_call_missed" android:layout_height="50dp" android:layout_below="@+id/screen_p2pcall_peer" android:layout_toRightOf="@+id/screen_p2pcall_status_icon" android:layout_marginTop="18dp"/> <ImageButton android:layout_width="120dp" android:id="@+id/screen_p2pcall_answer" android:src="@android:drawable/sym_action_call" android:layout_height="50dp" android:layout_alignTop="@+id/screen_p2pcall_hangup" android:layout_toLeftOf="@+id/screen_p2pcall_hangup"/> </RelativeLayout> Now I used this code in my onCreate method and it hides the left bottom button and horizontally centers the right bottom button ImageButton hangupButton = (ImageButton)findViewById(R.id.screen_p2pcall_hangup); int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 120, getResources().getDisplayMetrics()); int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 50, getResources().getDisplayMetrics()); int marginTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 18, getResources().getDisplayMetrics()); RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(width,height); rlp.addRule(RelativeLayout.CENTER_HORIZONTAL,RelativeLayout.TRUE); rlp.addRule(RelativeLayout.BELOW, R.id.screen_p2pcall_peer); rlp.topMargin = marginTop; hangupButton.setLayoutParams(rlp); ((ImageButton)findViewById(R.id.screen_p2pcall_answer)) .setVisibility(RelativeLayout.INVISIBLE); This should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access to MethodInfo in OperationInterceptor I created a couple of custom attributes that I attach to my methods in the handlers. The custom attributes are more than mere 'taggers' like e.g. 'RequiresAuthenticationAttribute'. A simplified example: [EnforceParam("Account")] In my interceptor, that gets called for methods annotated with EnforceParam, I'd like to get access to the value "Account". What I'm currently doing for that is this: public override bool BeforeExecute(IOperation operation) { ReflectionBasedMethod method = (ReflectionBasedMethod)((MethodBasedOperation)operation).Method; MethodInfo methodInfo = method.MethodInfo; For that to work, I had to add the 'Method' property to OpenRasta's ReflectionBasedMethod. Can the same be accomplished without hacking OpenRasta (I'm on 2.0 btw)? A: That's the wrong question. What you're looking for is simply: var attribute = operation.FindAttribute<EnforceParamAttribute>() Downcasting is not supported and the operation should only reflect an operation and its inputs, on purpose. Do not downcast, it will break and your code is not guaranteed to work beyond one version that happens to use the IMethod API, which is going at some point to be rewritten / removed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting recent selection in multiple select box I want to populate content depending upon the multiple select box selection. I can get all selected value of select box. Using $('select').change(function(){ console.info($(this).val()) // it gives me array }); But i want only the recent selection/deselection user makes. A: You could do: function arr_diff(a1, a2) { var a = [], diff = []; for (var i = 0; i < a1.length; i++) a[a1[i]] = true; for (var i = 0; i < a2.length; i++) if (a[a2[i]]) delete a[a2[i]]; else a[a2[i]] = true; for (var k in a) diff.push(k); return diff; } var oldSelect = []; $('select').change(function() { var changes = arr_diff(oldSelect, $(this).val()); console.info(changes); // it gives me array oldSelect = $(this).val(); }); changes contains only the selcted/deselected element fiddle here http://jsfiddle.net/j5rBS/ P.S. You should accept some answer because your acceptance rate is very low A: or, Simply just get the first index of array while select. $(function(){ $('select').change(function(){ var opt=$(this).val(); $("span").text(opt[0]); }); }) http://jsfiddle.net/jMw92/10/ A: Try this // this will set the last selected or deselected option element's value to the select element as a custom attribute "recent" $("#selectEl option").click(function(event) { $(this).parent().attr("recent", $(this).val()); }); $("#selectEl").attr("recent"); // returns the last selected/deselected option value or undefined if attribute recent is not present
{ "language": "en", "url": "https://stackoverflow.com/questions/7634391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: build vp8 on android I'm trying to build the vp8 codec for Android. I ran the configure.sh script and the makefile for armv6 with sourcery g++ which succesfully produced libvpx.so. After that I wrote a JNI wrapper and compiled it with ndk-build succesfully. When I run this on a Gingerbread smartphone I got a UnsatisfiedLinkError "libpthread.so.0 not found". How can I get rid of this error? A: From http://git.chromium.org/gitweb/?p=webm/bindings.git;a=blob_plain;f=JNI/README.Android with some adjustments for readability. * *Create {project}/jni folder. *Get JNI bindings. git clone https://chromium.googlesource.com/webm/bindings *Get libvpx. git clone https://chromium.googlesource.com/webm/libvpx *Configure libvpx for Android ./libvpx/configure --target=armv7-android-gcc --disable-examples --sdk-path={path to NDK} --sdk-path MUST be absolute. *Get libwebm. cd bindings/JNI git clone https://chromium.googlesource.com/webm/libwebm *Get libogg. Download ogg code from http://downloads.xiph.org/releases/ogg/libogg-1.3.0.tar.gz Extract to bindings/JNI. *We need to run configure to generate config_types.h. cd libogg-1.3.0 && ./configure && cd .. *Get libvorbis Download vorbis code from http://downloads.xiph.org/releases/vorbis/libvorbis-1.3.3.tar.gz Extract to bindings/JNI. *Get libyuv svn checkout http://libyuv.googlecode.com/svn/trunk/ libyuv-read-only *Create {project}/jni/Application.mk with the data below: APP_ABI := armeabi-v7a APP_OPTIM := release APP_STL := gnustl_static APP_CPPFLAGS := -frtti *Create {project}/jni/Android.mk with the data below: WORKING_DIR := $(call my-dir) BINDINGS_DIR := $(WORKING_DIR)/bindings/JNI include $(BINDINGS_DIR)/Android.mk *Build the JNI code. {path to NDK}/ndk-build *Copy the java code. cp -R bindings/JNI/com/google ../src/com/ *Add code to test the bindings. int[] major = new int[2]; int[] minor = new int[2]; int[] build = new int[2]; int[] revision = new int[2]; MkvMuxer.getVersion(major, minor, build, revision); String outStr = "libwebm:" + Integer.toString(major[0]) + "." + Integer.toString(minor[0]) + "." + Integer.toString(build[0]) + "." + Integer.toString(revision[0]); System.out.println(outStr); *Run the app. You should see libwebm version output. *Tweak as needed. VP8 wrappers are in the com.google.libvpx namespace. A: This can sometimes be a problem with the SONAME in a shared library, have a look at this article. http://groups.google.com/group/android-ndk/browse_thread/thread/fd484da512650359 You could disable pthreads if you don't really need them. Iv'e had problems with .so files in the past and have avoided all of these problems by using .a static libraries instead of .so shared libraries
{ "language": "en", "url": "https://stackoverflow.com/questions/7634392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: automatic sms sending in android I want to develop a sms application which send automatic sms to the "sms sender" when receive a sms, with a predefind text. First i created the broadcast receiver class public class MyBroadCastReceiver extends BroadcastReceiver { private final String MSG_BODY="Thank you for contact we will contact u later"; final int MAX_SMS_MESSAGE_LENGTH=160; @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) { Bundle bundle = intent.getExtras(); //---get the SMS message passed in--- SmsMessage[] msgs = null; String msg_from; if (bundle != null){ //---retrieve the SMS message received--- try { Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for(int i=0; i<msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); msg_from = msgs[i].getOriginatingAddress(); } Toast.makeText(context, "SMS sent", Toast.LENGTH_SHORT).show(); //String msgBody = msgs[i].getMessageBody(); msg_from = msgs[0].getOriginatingAddress(); sendSms(msg_from,MSG_BODY); } catch(Exception e){Log.d("Exception caught",e.getMessage());} } } } private void sendSms(String phonenumber,String message) { SmsManager manager = SmsManager.getDefault(); int length = message.length(); if(length > MAX_SMS_MESSAGE_LENGTH) { ArrayList<String> messagelist = manager.divideMessage(message); manager.sendMultipartTextMessage(phonenumber, null, messagelist, null, null); } else { manager.sendTextMessage(phonenumber, null, message, null, null); } } } And the manifest file is <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myapp" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="7" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <receiver android:enabled="true" android:name="com.myapp.MyBroadCastReceiver"> </receiver> <activity android:name=".MeraSms" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.SEND_SMS"> </uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"> </uses-permission> </manifest> It does nothing only display my main activity. Help me where i am going wrong. A: Try adding an intent-filter into the receiver. "android.provider.Telephony.SMS_RECEIVED" is an ordered broadcast intent, which means a receiver with a higher priority may block receivers with lower priority. <receiver android:enabled="true" android:name="com.myapp.MyBroadCastReceiver"> <intent-filter android:priority="10000"> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-fileter> </receiver>
{ "language": "en", "url": "https://stackoverflow.com/questions/7634393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: id confirms to a protocol, But where will be the implementation? It's probably a naive question, But I am feeling kinda lost. I read iOS developer guide about protocols at Apple Documentation, But didn't quite make sense. Let me explain my dilemma in a shortest possible way. Lets say I have protocol as below, @protocol MyProtocol<NSObject> - (void)someMessage; @end And than in my code I am declaring a variable like this, id<MyProtocol> someVar; So far so good, But someVar is an id type so where we will implement -(void) someMessage;? NOTE: I have knowledge such as, Implementation of defined functions of interface should be inside a Class which implements that interface. This understanding is from Java so, and in Java it is very apparent to know which object is from which class and what interface that class implements. But above Objective C way just confused me :(. A: When you write: id<MyProtocol> someVar you're simply stating that "someVar" will be an object of any class, but this class will respect the protocol MyProtocol. So there will be some point in your code that will instantiate someVar. At this point someVar will be associated to a class. This class must satisfy the MyObject protocol. Note that the compiler will do its best to warn you in case of issues, e.g. if you cast this object to some class that doesn't respect the protocol, e.g. suppose your protocol defines a method called "protocolMethod" then: [(NSArray *)someVar protocolMethod] will generate a compiler warning ("NSArray may not respond to protocolMethod"). Of course you will never be protected from runtime errors: so if at runtime you create someVar to be of a class that doesn't satisfy the protocol, then any calls to the protocol methods will raise an exception. A: Objective-C protocols are loosely similar to Java interfaces in terms of concepts and in code, to put it simply. If you declare a Java variable to be of an interface type, it means it can accept any object that implements that interface. In Objective-C, an id variable means any pointer type, so id<MyProtocol> means any pointer to an object that adopts MyProtocol, and is similar to a Java interface type declaration in that sense. In Java, you implement an interface method in a class, and declare that class to implement the interface. Similarly, in Objective-C, you implement a protocol method in a class, and have that class adopt the protocol. Here's a code comparison between Java and Objective-C (again it's just a loose comparison of two similar concepts): Java public interface MyInterface { void someMethod(); } public class MyClass implements MyInterface { public void someMethod() { System.out.println("Some method was called"); } } public class Main { public static void main(String[] args) { // Any class that implements MyInterface can be // assigned to this variable MyInterface someVar = new MyClass(); someVar.someMethod(); } } Objective-C @protocol MyProtocol <NSObject> - (void)someMessage; @end @interface MyClass : NSObject <MyProtocol> - (void)someMessage; @end @implementation MyClass - (void)someMessage { NSLog(@"Some message was sent"); } @end int main(int argc, const char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Any class that adopts MyProtocol can be // assigned to this variable id<MyProtocol> someVar = [[MyClass alloc] init]; [someVar someMessage]; [someVar release]; [pool drain]; return 0; } A: You need to implement a class that implements the methods in the Protocol e.g. @interface MyObject: NSObject <NyProtocol> - (void)someMessage; @end and @implementation MyObject -(void)someMessage() { printf(@"a message"); ... } @end And then use this as someVar = [MyObiect alloc]...... You could also implement the method as a category on NSObject so available to all classes. See Adopting a Protocol from Apples Objective C concept document A: I wrote a category on NSObject - called StrictProtocols - that solves this "problem". It implements the following methods... /* "non" doesn't implement ANY of the declared methods! */ [non implementsProtocol:proto]; -> NO; [non implementsFullProtocol:proto]; -> NO; /* "semi" doesn't implement the @optional methods */ [semi implementsProtocol:proto]; -> YES; [semi implementsFullProtocol:proto]; -> NO; /* "strict" implements ALL, ie the @optional, @required, and the "unspecified" methods */ [strict implementsProtocol:proto]; -> YES; [strict implementsFullProtocol:proto]; -> YES;
{ "language": "en", "url": "https://stackoverflow.com/questions/7634394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Implementing a binary counter using std::bitset I want to implement a binary counter in C++ using std::bitset. If I explicitly develop an addition function for bitset then the complexity of the algorithm would go up to O(n^2). Is there any way to do this O(n)? Also are there any good descriptions of Horowitz and Sahni's Subset Sum Problem Solution? Except for Wikipedia, I couldn't find any good source describing their algorithm. A: For your second question, "are there any good descriptions of Horowitz and Sahni's Subset Sum Problem Solution?", I found few articles: Original paper from Horowitz and Sahni: http://www.cise.ufl.edu/~sahni/papers/computingPartitions.pdf Stackoverflow discussion about Horowitz and Sahni's algorithm improvements: Generate all subset sums within a range faster than O((k+N) * 2^(N/2))? Source code: http://www.diku.dk/hjemmesider/ansatte/pisinger/subsum.c A: If the bitset is small enough that all the bits can fit in unsigned long, then you can use its conversion functions to perform integer arithmetic on it, for example bitset = std::bitset(bitset.to_ulong() + 1); In C++11, there is also a to_ullong() function, giving unsigned long long, which may be larger than unsigned long. If your bitsets are too large for that, you may be better off implementing your own, based around an array or vector of integers that your counter can access. Your algorithm will still be O(n2), but you can reduce the number of operations needed for each addition, compared to processing a single bit at a time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIImage with NSData without size I have this code: ... NSData * dimage = [[NSData alloc]initWithData:[datosImagen objectForKey:@"Image"]]; UIImage * imagenAMostrar = [[UIImage alloc] initWithData:dimage]; UIImageView * imAMostrar = [[UIImageView alloc] initWithImage:imagenAMostrar]; ... I need resize my UIImageView, similar to this dimensions: setFrame:CGRectMake(0,60,320,240). but for this i need UIImageView size.... NSLog(@" Image width:%d",imagenAMostrar.size.width); NSLog(@" Image height:%d",imagenAMostrar.size.height); The result is: 2011-10-03 13:32:28.993 Catalogo-V1[2679:207] Image width:0 2011-10-03 13:32:28.994 Catalogo-V1[2679:207] Image height:0 Why?? A: Didn't you get any warnings in NSLog statements? You should be getting a conversion type warnings. width and height are float-s. You are supposed to use %f as conversion specifier. You should be printing them like this, NSLog(@" Image width:%f", imagenAMostrar.size.width); NSLog(@" Image height:%f", imagenAMostrar.size.height); You can set the frame of image view like this, imAMostrar.frame = CGRectMake(0, 60, imagenAMostrar.size.width, imagenAMostrar.size.height);
{ "language": "en", "url": "https://stackoverflow.com/questions/7634398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Refreshing data without reloading I want to refresh data in ASP.NET without reloading page. If it is possible I don't want to use AJAX. I am interesting in clearly .NET A: Try PokeIn a Comet implementation for ASP.NET You can also use SignalR which is officially supported by Microsoft. A: If you don't want to use AJAX you can use JQuery to do an Async Http request and refresh only the portion of the page you are interested in (Partial Rendering). http://api.jquery.com/jQuery.get/ http://api.jquery.com/jQuery.post/ you can't refresh a portion of the page without using any client side framework (lots of years ago when JQuery was not out yet and JavaScript was not used we were using IFrame to achieve that but today would be really bad) A: You can use UpdatePanel to refresh your data. http://ajax.net-tutorials.com/controls/updatepanel-control/
{ "language": "en", "url": "https://stackoverflow.com/questions/7634400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a nice "LOADING..." animation Possible Duplicate: Pretty alternative to JProgressBar? I have a process which takes several seconds to load, and I want to create an animation in Java Swing until it finishes loading. I'd like to avoid using a typical ProgressBar and use a nice modern infinite progress like this one I'm aware of similar questions but this is strictly Java Swing related. Is there any library or example for this? A: Just use a ImageIcon for this task, it automatically animates gifs. The code below produced this screenshot (the ajax-loader.gif was downloaded from http://www.ajaxload.info/): Code: public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Test"); ImageIcon loading = new ImageIcon("ajax-loader.gif"); frame.add(new JLabel("loading... ", loading, JLabel.CENTER)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setVisible(true); } A: Sure it's possible. You can use the tool AjaxLoad to generate an animated image, which can be used in any image/html container. A: I'd recommend using the glasspane for this type of activity. The steps involved are: * *Create a JComponent with BorderLayout. Add a JLabel to the CENTER which includes the animated .gif icon of your choice. *(Optional) Override the paint(Graphics) method to make your GUI appear greyed out (or whited out). To achieve this you need to draw a filled rectangle the size of the component, filling the rectangle with a semi-transparent Color. *Add the component as the glasspane of your application's root frame.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How do i make a forever running service in asp.net? From my other question i learned that asp.net kills my threads because 'it feels like it'. These threads are my daemons that handle thumbnail generation, registration emails and other things. I was told to use a 'Windows Service' but what i know of, its an app you install on your machine that runs on bootup. There are several problems with using that if thats what he meant. The last time i attempted a service i remember it prove difficult and i just put the app in the startup files. anyways I AM NOT ON WINDOWS. I am on linux. The other problems having it in a separate app is i have much code in asp.net that would need to be copied over which i dont want to do. The other is i have asp.net poke the thread using ManualResetEvent whenever it needs it so i am not hammering the db and get immediate results. AFAIK i dont know of any way to poke another process. How might i run this code? with asp.net? I dont think checking if the threads exist every request is a good idea. What can i do? A: ASP.NET is designed to follow a request-response pattern. It has mechanisms specifically to prevent leaving threads running outside of a request, such as killing long-running threads (which it considers "broken"). What you are asking to do is not the intended function of ASP.NET. To do what you want in ASP.NET, you will be fighting the platform, not building on it. This is why you've been told to write another application which performs your long-running processes. If you're on Linux, that means writing a deamon that can host the threads you want to run continuously in the background, because that's specifically their purpose. You must use the right tool for the job. A: Take a look at this post: How to migrate a .NET Windows Service application to Linux using mono? I hope it gets you in the right direction :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP + cURL not working Trying to get the content of the a certain URL using cURL and PHP. The code is supposed to run on the sourceforge.net project web hosting server. code: <?php function get_data($url) { $ch = curl_init(); $timeout = 10; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } $url1 = urlencode("http://www.google.com"); $url2 = "http://www.google.com"; $output = get_data($url2); echo $output; ?> I've checked that cURL is supported. But the above code is not working, the page is loading till timeout with no output. I've tried the encoded url as well. Why? Error 503 Service Unavailable. PHP version 5.3.2 A: You might want to use file_get_contents $content = file_get_contents('http://www.google.com'); /some code here if needed/ return $content; You can also set files inside file_get_contents ex: $content = file_get_contents('textfile.txt'); More information about the function file_get_conents Some info which I noticed when working with cUrl: One thing I've also noticed when working with cUrl is that it works differently when the URL has http or https. You need to make sure that you code can handle this A: I replaced my curl code with yours and its not working. I tried with 'gmail.com' and it showed fine with my code and with yours it gave a '301 Moved' Error. My Code is as follows: function get_web_page($url) { //echo "curl:url<pre>".$url."</pre><BR>"; $options = array( CURLOPT_RETURNTRANSFER => true, // return web page CURLOPT_HEADER => false, // don't return headers CURLOPT_FOLLOWLOCATION => true, // follow redirects CURLOPT_ENCODING => "", // handle all encodings CURLOPT_USERAGENT => "spider", // who am i CURLOPT_AUTOREFERER => true, // set referer on redirect CURLOPT_CONNECTTIMEOUT => 15, // timeout on connect CURLOPT_TIMEOUT => 15, // timeout on response CURLOPT_MAXREDIRS => 10, // stop after 10 redirects ); $ch = curl_init($url); curl_setopt_array( $ch, $options ); $content = curl_exec( $ch ); $err = curl_errno( $ch ); $errmsg = curl_error( $ch ); $header = curl_getinfo( $ch,CURLINFO_EFFECTIVE_URL ); curl_close( $ch ); $header['errno'] = $err; $header['errmsg'] = $errmsg; //change errmsg here to errno if ($errmsg) { echo "CURL:".$errmsg."<BR>"; } return $content; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HttpURLConnection get uploaded path of server in android I am uploading a file to a server. Now I want to check whether the file is uploaded or not. So I want to get the path of the uploaded file on the server. Can anybody tell me how to do this?. If I get the path I will check in the browser. Thanks A: Actually it depends on where the server is storing that file.I don't think you can get the path from your application.You have to check the folder where server is saving the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get click event for Graphics in asp.net We are writing a text in an image using System.Drawing.Graphics.Drawstring. Below code is shown Bitmap bitMapImage = new System.Drawing.Bitmap(@"D:\ABC\Chart1.png"); Graphics graphicImage = Graphics.FromImage(bitMapImage); //Smooth graphics is nice. graphicImage.SmoothingMode = SmoothingMode.AntiAlias; String drawString = "250"; Font drawFont = new Font("Arial", 12,FontStyle.Bold); SolidBrush drawBrush = new SolidBrush(Color.White); PointF drawPoint= new PointF(169.0F, 85.0F); . graphicImage.DrawString(drawString, drawFont, drawBrush, drawPoint); //Set the content type Response.ContentType = "image/jpeg"; //Save the new image to the response output stream. bitMapImage.Save(Response.OutputStream, ImageFormat.Jpeg); //Clean house. graphicImage.Dispose(); bitMapImage.Dispose(); The code takes an imagefile and writes the string (here:250).Now when user clicks 250, the new window should get open. Not sure how to get the click event of 250? Please help! Thanks A: This is ASP.NET detecting a click on drawn text in an image is possible but far from ideal. You should instead render text using a div or other html element by positioning it over the image and detect clicks on the that instead using javascript. See Text Blocks Over Image A: It would be easier to render the image to a container like a DIV or SPAN, and add an onclick to container: <div onclick="doSomething();"> <!-- rendered image here --> </div> You might also look into using an Image Map, like this: function foo() { alert("Hello World!") } <img src="/images/someimage.png" usemap="#somemap" /> <map name="somemap"> <area coords="0,0,82,126" onclick="foo()" nohref="true" href="#" /> </map>
{ "language": "en", "url": "https://stackoverflow.com/questions/7634410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Not able to write to sys/class/uwb/scan file through JNI using android application define SCAN_FILE /sys/class/uwb_rc/uwb0/scan My aim is to write to a SCAN_FILE in android as in " echo 9 0 > /sys/class/uwb_rc/uwb0/scan " I want to implement this using android application and file operations with JNI integration My code is as shown below :- package com.samsung.w; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class write extends Activity { private static final String TAG = "test"; TextView tv_status; /** Called when the activity is first created. */ private Object myClickHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.e(TAG, "entered after main and waiting ..."); getAccessPerm("/sys/class/uwb_rc/uwb0/scan"); } private void getAccessPerm(String path) { try { String command = String.format("echo \"chmod 777 %s\" | su\nexit\n", path); Process sh_process = Runtime.getRuntime().exec("sh"); OutputStream writer = sh_process.getOutputStream(); writer.write(command.getBytes("ASCII")); BufferedReader stdError = new BufferedReader(new InputStreamReader( sh_process.getErrorStream())); String err_line = null; if((err_line = stdError.readLine()) != null) { Log.e(TAG, "getAccessPerm: chmod cmd failed"); System.out.println(err_line); while ((err_line = stdError.readLine()) != null) { System.out.println(err_line); } } } catch (Exception e) { Log.e(TAG, "getAccessPerm: exception"); e.printStackTrace(); } } public void myClickHandler(View view) { switch (view.getId()) { case R.id.scan_button: TextView textview = (TextView)findViewById(R.id.tv_title); textview.setText(scaninit()); break; } } public native String scaninit(); static { System.loadLibrary("write"); } } And the corresponding JNI file is jstring Java_com_samsung_w_write_scaninit(JNIEnv* env, jobject thiz) { FILE* file = fopen("/sys/class/uwb_rc/uwb0/scan", "rw"); char *mystring[20]; if (file != NULL) { fputs("9 0", file); fgets(mystring, 4, file); fclose(file); return (*env)->NewStringUTF(env, mystring); } return (*env)->NewStringUTF(env, "file opening failed!"); } And Android Manifest file is like this <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.samsung.w" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="7" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ** <uses-permission android:name="android.permission.FACTORY_TEST" /> ** <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".write" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> **-tried these two thinking is it related to permission issue but no use Default value in the SCAN_FILE on cat:- #cat /sys/class/uwb_rc/uwb0/scan 3 0 Result of typin in adb shell #echo 9 0 > | cat sys/class/uwb_rc/uwb0/scan 9 0 but when i use the android application i am not able to see this change #cat /sys/class/uwb_rc/uwb0/scan 3 0 (default value on booting) Someone Kindly help me please A: e could solve this thanks to Bhushan for helping me out The problem is in the kernel source code DEVICE attribute the permission has to be written to as DEVICE_ATTR(scan, 0777, uwb_rc_scan_show, uwb_rc_scan_store); instead of DEVICE_ATTR(scan, S_IRUGO | S_IWUSR, uwb_rc_scan_show, uwb_rc_scan_store); then in the C code fopen shoudl be in r+ mode as in FILE* file = fopen("/sys/class/uwb_rc/uwb0/scan", "r+"); This forum is awesome :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checking for existing row using a DateTime column fails I'm trying to find a row using a DateTime value. If the row exists, return it; otherwise create a new row. The problem I'm seeing is that the find sql uses a different datetime value to the insert. As there is a unique index on my datetime column I get a duplicate not allowed db error at the 2nd call. It seems to be related to the summer time saving 1 hour difference but then I'm stumped. I've got my timezone set to 'London' in environment.rb, and the mysql db is storing all dates as utc. Running the 'doit' method twice with the same parameter results in 2 rows in the database - it should only ever create one. I've put together a test class to demonstrate what I'm trying to do. And also the development log so that you can see the sql being generated. I'm sure I've missed some basic fact regarding the conversion of datetime to utc before / at hitting the database but I've researched and I can't pin down what I've done wrong. Rails: 2.3.10 mysql: 5.1.49 Thanks class TestDate < ActiveRecord::Base # create table test_dates (thedate datetime not null); def self.doit(for_date) r = find_by_thedate(for_date) if r.nil? r = TestDate.new(:thedate => for_date) r.save! end r end end >> TestDate.doit(DateTime.now.midnight) => #<TestDate thedate: "2011-10-02 23:00:00"> TestDate Load (0.3ms) SELECT * FROM `test_dates` WHERE (`test_dates`.`thedate` = '2011-10-03 00:00:00') LIMIT 1 SQL (0.1ms) BEGIN TestDate Create (0.2ms) INSERT INTO `test_dates` (`thedate`) VALUES('2011-10-02 23:00:00') SQL (0.1ms) COMMIT A: You could try the following: r.save(:validate => false) Because r.save! will run your validations, I think it rolls back your query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Doesn't std::piecewise_construct cause a ODR violation? std::piecewise_construct, defined in <utility>, has internal linkage since it is declared constexpr. I wonder if use of std::piecewise_construct in a header can violate ODR. For example: a.hpp #include <utility> #include <tuple> struct point { point(int x, int y) : x(x), y(y) {} int x, y; }; inline std::pair<point, point> f(int x1, int y1, int x2, int y2) { return { std::piecewise_construct, std::forward_as_tuple(x1, y1), std::forward_as_tuple(x2, y2) }; } translation unit 1 #include "a.hpp" translation unit 2 #include "a.hpp" The std::piecewise_construct in f in TU 1 refers to a different object than that in f in TU 2. I suspect f violates ODR. N3290 (probably ISO/IEC 14882:2011 also) says the following case is an exception of ODR, in 3.2/5: a name can refer to a const object with internal or no linkage if the object has the same literal type in all definitions of D, and the object is initialized with a constant expression (5.19), and the value (but not the address) of the object is used, and the object has the same value in all definitions of D; f satisfies almost all the requirements, but "the value (but not the address) of the object is used" seems ambiguous to me. It's true that std::piecewise_construct_t has no state, but a call of the piecewise constructor of std::pair involves a call of the implicit-declared copy constructor of std::piecewise_construct_t, whose argument is const std::piecewise_construct_t &. The address is "used", isn't it? I'm very puzzled. Reference: http://lists.boost.org/Archives/boost/2007/06/123353.php A: It appears that you already have your answer in that boost mailing list posting. Yes, in my opinion it is undefined behavior or at least not sufficiently clear defined behavior. See this usenet discussion for the same matter being discussed. A: IMHO there is no conflict under the ODR. An unnamed namespace has the same effect as marking things for internal linkage (static). This does indeed mean that every TU uses his own unique definitions for such types/functions. The way I look at them, how the placeholders (::::_1 and competing flavours) work, is not by instantiation so much as by compiletime type inference: _1, _2 etc. are merely placeholders, and they don't really need to be compatible (values don't need to be passed from one TU to another, they are passed as type inferred parameters only and as such their actual type is inferred to be have the identity from the current TU). IOW: You can easily define your own placeholders by specializing some traits, and they should still work like a charm. namespace boost { template<int I> struct is_placeholder< my_funny_own_placeholder_no_ODR_involved<I> > { enum _vt { value = I }; }; } I suppose the same logic could hold for piecewise_construction (but I haven't looked at that much).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: How to store data with Facebook.JsonObject or Facebook.JsonArray I use the FB C# sdk 5.2.from http://facebooksdk.codeplex.com/ and develop with .net 3.5, so i cannot use the dynamic, and the var type is able to get the data, but the format is so ugly and hard to get the data i want. I want to know how to store data with the Facebook.JSONObject or the JSonArray, it seems like there is no such a Dictionary["data"]function. Besides, i cannot find the document Any thoughts? Thanks a lot. A: If you need distionary try: var fc = new FacebookClient("someAccessToken"); var result = (IDictionary<string, object>)fc.Get("/me/feed"); or similar call. Optionally give an example of what are you trying to retrieve and/or post? Or you may use: [DataContract] public class PostCrate { [DataMember(Name = "data")] public List<Post> Data { get; set; } [DataMember(Name = "paging")] public Paging Paging { get; set; } } [DataContract] public class Paging { [DataMember(Name = "previous")] public string Previous { get; set; } [DataMember(Name = "next")] public string Next { get; set; } } [DataContract] public class Post { [DataMember(Name = "id")] public string ID { get; set; } [DataMember(Name = "from")] public BaseUser From { get; set; } [DataMember(Name = "type")] public string Type { get; set; } [DataMember(Name = "created_time")] public string CreatedTime { get; set; } [DataMember(Name = "updated_time")] public string UpdatedTime { get; set; } } [DataContract] public class BaseUser { [DataMember(Name = "id")] public string ID { get; set; } [DataMember(Name = "name")] public string Name { get; set; } } and var fc = new FacebookClient("someAccessToken"); var result = fc.Get<PostCrate>("/me/feed"); (any properties above can be omited) DataMember names are base on 'keys' from IDictionary above A: [DataContract] public sealed class Group { [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "privacy")] public string Privacy { get; set; } [DataMember(Name = "id")] public string Id { get; set; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to subtract consecutive columns in a crosstab report in iReport I have developed a crosstab report in iReport. I want to subtract values from consecutive column values. How can I do that?? For e.g. If the cross tab report shows the following: Jan Feb Salary 10000 20000 Basic 5000 10000 But I want to show it like: Jan Feb Salary 10000 10000 (Feb - Jan data) Basic 5000 5000 (Feb - Jan data)
{ "language": "en", "url": "https://stackoverflow.com/questions/7634436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error in template: Iterator was not declared in the scope trying to make a template, but I have an error in gcc4 but not in VS2008. This is the code that fails: #pragma once #ifndef _ZELESTE_ZEL_GPX_GENERALMANAGER_H_ #define _ZELESTE_ZEL_GPX_GENERALMANAGER_H_ #include "../internal/cuCoreLib.h" #include "boost/functional/hash.hpp" #include "boost/ptr_container/ptr_map.hpp" namespace z3d{ namespace core{ template<class Key, class Value> class cuManager { boost::ptr_map<Key, Value> m_ItemMap; public: /** * Default constructor */ cuManager(void){} /** * Get a vector that contain the keys of the elements contained in the manager. * @return an const std::vector of type Key */ const std::vector<Key> getKeys() { boost::ptr_map<Key,Value>::iterator itr = m_ItemMap.begin(); std::vector<Key> v; while(itr != m_ItemMap.end()) { v.push_back(itr->first); ++itr; } return v; } } }; }; This is one of the methods that fails to compile (all methods of the class fail in the same iterator). This code works fine into visual studio but compilation in GCC return this error: /home/dev001/desarrollo/code/lpgameengine/LPGameEngine/src/core/datatypes/cuManager.h: In member function ‘const std::vector<_Tp, std::allocator<_CharT> > z3d::core::cuManager<Key, Value>::getKeys()’: /home/dev001/desarrollo/code/lpgameengine/LPGameEngine/src/core/datatypes/cuManager.h:28: error: expected ‘;’ before ‘itr’ /home/dev001/desarrollo/code/lpgameengine/LPGameEngine/src/core/datatypes/cuManager.h:30: error: ‘itr’ was not declared in this scope Any help will be welcome A: Declare it like this: typename boost::ptr_map<Key,Value>::iterator itr = m_ItemMap.begin(); ^^^^^^^^ The point is that boost::ptr_map<Key,Value>::iterator is a dependent name, so you have to specify that it's a type name (and not a variable name or a template name).
{ "language": "en", "url": "https://stackoverflow.com/questions/7634445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Listview Pagination - Index Out of range error? I am having trouble implementing pagination onto a list of products held within a List View. Currently my pagination set up works fine if I do not call the ItemDataBound method but once I do, I repeatedly get the error that an Index was out of range when I try to navigate using my pagination. This line seems to be causing the error, even though debug seems to show that it is finding the ID int key = int.Parse(LV_Images.DataKeys[e.Item.DataItemIndex].Value.ToString()); Does anyone have a workaround this or can explain why this is happening??? Many thanks! A: Use the following: int key = int.Parse(LV_Images.DataKeys[e.Item.DisplayIndex].Value.ToString()); I was having same error also, I was able to resolve it with this. Hope this helps someone else A: The only container you are using in this line is DataKeys. The possible cause of this is because e.Item.DataItemIndex is not in range. Can you please check what is the value of DataItemIndex when it throws this exception? Also, check whether the value exist for such index value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change in website layout when reducing browser size When I reduce the browser window size, the top and bottom footers start to shrink, pushing the content that is inside the footers (navigation bar on the top and the bottom) off the footer and it starts to overlap with the main text body. Does anyone know why this problem occurs? Apologies if this question is unclear or has been already answered, I'm still learning. Many thanks for your help. A: Most content on a web page will be resized like that when the window is made smaller. What you can do is set the min-width CSS property to define a minimum width at which point the browser will add scroll bars rather than resize the elements on the page. SO something like: .someClass { min-width: 800px: } A: I think you can customize all your CSS rules using the % ,So in case of the parent element's width is reduced by 400px for ex , you can set childs width,height,margine,etc by % values like this : .parent{ width:100%; } .child{ width:60%; } Let's assume that the parent 100% represents 1024 px ,So Child will take 614 px and when the page is re-sized and takes 600 px ,So child will be 360 px automatically
{ "language": "en", "url": "https://stackoverflow.com/questions/7634450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Tools to view partial data that arrived at the browser I'm using flushing technique to flush of my page from server to improve performance. Are there any tools available which let me look in to the partial data that has arrived at the browser end? A: fiddler has an option to do it
{ "language": "en", "url": "https://stackoverflow.com/questions/7634452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Comments Plugin styling I added the facebook comments plugin in my site, I wanted to add styling to the plugin according to my site style. The below code which I added in mysite. <fb:comments href="<url>" num_posts="2" width="500"></fb:comments> Please suggest me how to do this. A: This is not possible to style in a custom form. This is because the comments are loaded within an iframe. Facebook offers two color schemes for the plugins, a light and dark theme, but other than these that is all that is possible using fb:comments <fb:comments href="<url>" num_posts="2" width="500" colorscheme="dark"></fb:comments> or <fb:comments href="<url>" num_posts="2" width="500" colorscheme="light"></fb:comments> A: Not enough styling but if you are conscious about the responsiveness then you can use data-width="100%" instead of data-width="500" or '600'
{ "language": "en", "url": "https://stackoverflow.com/questions/7634455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Conditionally evaluated debug statements in Python Python has a few ways of printing "trace" output. print, import logging, stdout.write can be used to print debugging info, but they all have one drawback: even if the logger's threshold is too high or the stream is closed, Python will still evaluate the arguments to the print statement. (Strict Evaluation) This could cost a string format or more. The obvious fix is to put the string-creating code into a lambda, and use our own logging function to call the lambda conditionally (this one checks the __debug__ builtin variable, which is set to False whenever python is started with -O for optimizations) : def debug(f): if __debug__: print f() #stdout.write(f()) #logging.debug(f()) for currentItem in allItems: debug(lambda:"Working on {0}".format(currentItem)) The advantage is not calling str(currentItem) and string.format in release builds, and the disadvantage is having to type in lambda: on every logging statement. Python's assert statement is treated specially by the Python compiler. If python is run with -O, then any assert statements are discarded without any evaluation. You can exploit this to make another conditionally-evaluated logging statement: assert(logging.debug("Working on {0}".format(currentItem)) or True) This line will not be evaluated when Python is started with -O. The short-circuit operators 'and' and 'or' can even be used: __debug__ and logging.debug("Working on {0}".format(currentItem)); But now we're up to 28 characters plus the code for the output string. The question I'm getting to: Are there any standard python statements or functions that have the same conditional-evaluation properties as the assert statement? Or, does anyone have any alternatives to the methods presented here? A: if all your debug function will take is a string, why not change it to take a format string and the arguments: debug(lambda:"Working on {0}".format(currentItem)) becomes debug("Working on {0}", currentItem) and if __debug__: def debug(format, *values): print format.format(*values) else: def debug(format, *values): pass this has all the advantages of your first option without the need for a lambda and if the if __debug__: is moved out the of function so that it is only tested once when the containing module is loaded the overhead of the statement is just one function call. A: I wonder how much a call to logging.debug impacts the performance when there are no handlers. However the if __debug__: statement is evaluated only once, even in the body of a function $ python -O Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import dis >>> import logging >>> def debug(*a, **kw): ... if __debug__: ... logging.debug(*a, **kw) ... >>> dis.dis(debug) 2 0 LOAD_CONST 0 (None) 3 RETURN_VALUE >>> and the logger can format the message for you using the string formatting operator. Here a slightly modified example taken from the logging.debug documentation FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' } debug('Protocol problem: %s', 'connection reset', extra=d) In this case the message string is never evaluated if the optimizations are turned off. A: any standard python statements or function with the same conditional behavior as assert -> no, as far as I know. Note that no string interpolation is performed by logging functions if the threshold is too high (but you still pay for the method call and some of the checks inside). You can expand on Dan D.'s suggestion by monkeypatching logging.logger when you code starts: import logging if __debug__: for methname in ('debug', 'info', 'warning', 'error', 'exception'): logging.logger.setattr(methname, lambda self, *a, **kwa: None) and then use logging as usual. You can even change the initial test to allow the replacement of the logging methods even in non optimized mode A: You could use the eval method: import inspect def debug(source): if __debug__: callers_locals = inspect.currentframe().f_back.f_locals print eval(source, globals(), callers_locals) for currentItem in ('a', 'b'): debug('"Working on {0}".format(currentItem)')
{ "language": "en", "url": "https://stackoverflow.com/questions/7634457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Is it possible to browse tasks in MyLyn same way as in Outlook? I'm trying to configure MyLyn and was hit by very strange problem. All issue control system I know use Outlook-like approach: filters to the left, issues at top right and issue description at bottom-right. Typical workflow while browsing issues is to click filter to the left so issues list is displayed at top right and then click issues at top right to see descriptions at bottom right. But mylyn interface is user-friendly and behaves like nothing i have seen before. First, issues list is integrated with filter list O_O. This works fine if you have like 20-30 issues total and a few filters, but if you have dozens of filters each selecting dozens of issues this effectively doubles amount of clicking: To browse issues you can't just click through filters. You need to expand each filter, see issues list, then close the filter (because issues list is long and other filters are scrolled out by it) and open next one. But ok, this is the thing i can handle. But the second thing stands out - if i click the issues in tasks list MyLyn is not displaying issues! Instead i need to double click the issue and MyLyn opens it in a new tab O_O. Ok, this will work if i know exactly what issue i need and click it. But regular issue browsing is a hell: instead of just clicking through issues and look for relevant information i neet to double click issue, look at new tab, close the tab and only after that i can double cick second issue (and i need to close tabs since Eclipse have only one editor areas and i have some other tabs open while browsing for issues). So is it any way in MyLyn to prevent a new tab being opened for each task and just display them in one place like all other desktop issue control systems (outlook, jira client, devtrack, ontime) do? A: Thank you for your feedback! Let me suggest a few things that might help: First, you can change Eclipse to open on a single-click instead of a double-click by going to Preferences->General, then changing the radio button on "Open Mode" from double-click to single-click. Second, you can see all your issues in one list if you switch from the Categorized View to the Scheduled view. Then you would not need to switch back and forth between queries. Third, you can use the search box in the Task List to help limit the tasks that you see. If you know that it's a crash, for example, you could type "crash" in the search box to help limit the number of queries you need to look at. Fourth, focusing your view (by clicking on the Mylyn focus button, which looks like three purple balls) will restrict the list of tasks to ones that are probably more interesting. Finally, if you want to look at a whole bunch of tasks in rapid succession but don't want to clutter your current task context with those tasks, consider making a Local task just for exploring tasks. Switch to that before you start looking, and the new tabs will show up in that context, not the one you were just working in. That means that you can click on a task, it will open in a tab, and you can ignore the tab. Keep clicking until you find the task you want, and then you can close all the other task tabs. (Or not. They aren't bothering anything where they are.) Then, when you switch back to your main task context, all those tabs will disappear and your main task's tabs will reappear. If you have any other questions, by all means, feel free to ask.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running AJAX code in Objective C I am developing a native application for iPhone. I would like to know if I can able to execute AJAX code in Objective C. Thanks! Nilesh A: As from word AJAX the meaning is Asynchronous JavaScript and XML So you need asynchronous HTTP library to fetch JSON/XML from remote server. Take a look at these * *ASIHTTPRequest http://allseeing-i.com/ASIHTTPRequest/ *RestKit http://restkit.org/
{ "language": "en", "url": "https://stackoverflow.com/questions/7634461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fluentvalidation inject business object to validator I am using fluentvalidation and use structuremap to inject validators for actions in asp.net mvc3. I have problems to inject my business objects to validator objects. I get an error like this: {"StructureMap Exception Code: 202\nNo Default Instance defined for PluginFamily Suggestion.Biz.BO.ISubjectBO, Suggestion.Biz, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"} How can i inject SubjectBO to SubjectValidator? SubjectValidator: public class SubjectValidator : AbstractValidator<SUBJECT> { private ISubjectBO _subjectBO; public SubjectValidator(ISubjectBO subjectBO) { _subjectBO = subjectBO; Custom(x=>{ if(!_subjectBO.CanUpdate(x)) return new ValidationFailure(null, "error msg"); return null; }); } } SuggestionValidationRegistry: public class SuggestionValidationRegistry : Registry { public SuggestionValidationRegistry() { For<IValidator<SUBJECT>>().Singleton().Use<SubjectValidator>(); ValidatorOptions.ResourceProviderType = typeof(ValidationResources); } } StructureMapValidatorFactory: public class StructureMapValidatorFactory : ValidatorFactoryBase { public override IValidator CreateInstance(Type validatorType) { return ObjectFactory.TryGetInstance(validatorType) as IValidator; } } App_start: ObjectFactory.Configure(cfg => cfg.AddRegistry(new SuggestionValidationRegistry())); FluentValidationModelValidatorProvider.Configure(provider => provider.ValidatorFactory = new StructureMapValidatorFactory()); DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; Yes i configure at app_start SuggestionBizRegistry : public class BizRegistry : Registry { public BizRegistry() { For<IAwardTypeBO>().Use<AwardTypeBO>(); For<IQuoteBO>().Use<QuoteBO>(); For<ISubjectBO>().Use<SubjectBO>(); For<IContestBO>().Use<ContestBO>(); For<IApplicationBO>().Use<ApplicationBO>(); For<IScreenBO>().Use<ScreenBO>(); } } App_start: protected void Application_Start() { ConfigureStructureMap(); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); EFUnitOfWorkFactory.SetObjectContext(() => new SuggestionModel()); UnitOfWork.UnitOfWorkFactory = new EFUnitOfWorkFactory(); } private static void ConfigureStructureMap() { IContainer container = new Container(x => { x.For<IControllerActivator>().Use<StructureMapControllerActivator>(); x.AddRegistry(new BizRegistry()); }); DependencyResolver.SetResolver(new StructureMapDependencyResolver(container)); ObjectFactory.Configure(cfg => cfg.AddRegistry(new SuggestionValidationRegistry())); FluentValidationModelValidatorProvider.Configure(provider => provider.ValidatorFactory = new StructureMapValidatorFactory(container)); DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; } A: You could write a custom validator factory as explained in this thread. A: You have not configured constructor parameter ISubjectBO subjectBO when configuring SubjectValidator injection
{ "language": "en", "url": "https://stackoverflow.com/questions/7634464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }