text
stringlengths
8
267k
meta
dict
Q: Appwidget with square layout not showing properly in landscape mode I have built an appwidget with an square layout, and so it doesn't fit exactly in the standard widget sizes as recommended in http://developer.android.com/guide/practices/ui_guidelines/widget_design.html#sizes. I chose a 3x2 size (android:minWidth="220dip" android:minHeight="146dip") as it is the smalllest that covers the widget's layout. In http://developer.android.com/guide/practices/ui_guidelines/widget_design.html#design Google recommends: "All widgets must fit within the bounding box of one of the six supported widget sizes, or better yet, within a pair of portrait and landscape orientation sizes, so your widget looks good when the user switches screen orientations" My widget looks good in portrait mode. When switched to landscape mode (in the emulator) the layout is clipped. I tried inverting the minWidth and minHeight values in the provider's XML and then it looked perfect in landscape mode but clipped in portrait mode. Setting the size to 3x3 solves the problem, but then the widgets takes a lot of unnecessary space. I know I can define different layouts in res/layout and res/layout-land, but in this case the layouts are not different at all, in both modes I want the widget to look square. What I would need is something like 'xml' and 'xml-land', AFAIK this is not supported in Android. Ideas? A: What I would need is something like 'xml' and 'xml-land', AFAIK this is not supported in Android. It is supported. All resource set qualifiers (e.g., -land) are supported for all resource types. Whether it will help you is another matter entirely, as I am not aware that you can change actual app widget size on the fly this way. Setting the size to 3x3 solves the problem, but then the widgets takes a lot of unnecessary space. You are the one who is trying to force a particular pixel size (or, at least, aspect ratio). This will be fragile, as you are discovering. Furthermore, app widget cells are not guaranteed to be the same size on all devices and home screen implementations. Hence, you are either going to need to choose an app widget size that gives you tons of extra space (your 3x3 scenario), or design a fluid app widget layout that adapts to the actual size that you are given (and therefore will not be square). Personally, I recommend the latter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i FTP upload directory in Powershell I came across this post: Upload files with FTP using PowerShell But I'm looking how i can upload a directory with files in it to a FTP server. Thanks in Advance A: You should write a script that loop into directory and then upload files one by one. I don't remember that ftp command on windows can upload an entire directory. You should find example here : http://www.dostips.com/DtTipsFtpBatchScript.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7597842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dealing with Listeners I know the listeners are supposed to make life easier, especially in a multi-tasking environment like android, but sometimes (to me) it just makes things harder. Right now I have an ExpandableList activity which presents a list of events, and I want the user to select the group & child of interest and select a notification sound that will play when that event happens. So the list is set up and I have a setOnChildClickListener set up which runs my SetRingtone method: protected void SetRingtone(int groupPosition, int childPosition) { Intent intent = new Intent( RingtoneManager.ACTION_RINGTONE_PICKER); intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALL); intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone"); startActivityForResult( intent, PICK_NOTIFICATION_SOUND); } So that method has access to the selected group and child positions. The problem is that to get the ringtone selected from the ringtone selector, you have to set up another lister, onActivityResult: protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); if (uri != null) { String ringTonePath = uri.toString(); ExpandableListView variableView = (ExpandableListView)findViewById(android.R.id.list); int p = variableView.getSelectedItemPosition(); Log.d("phca", "The selected item number was: " + p + "; The sound selected is: " + uri ); } } } And now I don't have access to the selected group and child. As you can see, I tried to get the position from the getSelectedItemPosition, but it always returns -1 here. I know I am probably making this harder than it really is. A: You could just store the group and child in instance variables before the call to startActivityForResult and then use these instance variables in onActivityResult. A: Did you try to use variableView.getSelectedItem()? If this return null so it mean that something wrong with your list
{ "language": "en", "url": "https://stackoverflow.com/questions/7597844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Color change on hover does not work when the background image is changed If the menu.gif here is replaced by a different image then the hover option does not work. Can anybody help me identify the problem #menus li { display:inline; list-style:none; } #menus li a { background:transparent url(img/**menu.gif**) no-repeat; display:block; color:#382E1F; height:31px; line-height:31px; padding:0 20px; margin-left:-10px; text-decoration:none; font-size:12px; font-weight: bolder; float:left; z-index:1; } #menus li a:hover{ display:block; color: #382E1F; font-size:15px; background-color: green; font-weight: bold; } #menus li a.current { background-position:0 -31px; } #menus li.current_page_item a, #menus li.current-cat a { background-position:0 -62px; } #menus li a.home { background-position:0 -93px; width:45px; padding:0; margin-left:0; text-indent:-999em; } #menus li a.home:hover { background-position:0 -124px; } #menus li.current_page_item a.home { background-position:0 -155px; } #menus li a.lastmenu:hover { background-position:0 0; cursor:default; } A: Can you show the CSS for when you have changed the background-image? Alternatively, if it is this CSS you are having issues with, background-color layers behind background-image Therefore on hover, you need to specify no background-image: #menus li a:hover{ display:block; color: #382E1F; font-size:15px; background-image:none; background-color: green; font-weight: bold; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to scroll listbox in wpf datagrid row details when IsDeferredScrollingEnabled is set to true I have a wpf datagrid with IsDeferredScrollingEnabled set to true. I have a listbox inside row details template. When I try to scroll the listbox by dragging its scrollbar, its not scrolling because of IsDeferredScrollingEnabled. Any thoughts would help?? A: Got the answer. http://social.msdn.microsoft.com/Forums/en/wpf/thread/f95f4727-5e84-48da-b153-973128292172
{ "language": "en", "url": "https://stackoverflow.com/questions/7597848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: security-role-mapping not working with file descriptor Using glassfish 3.1.1 for a Java EE6 project the security role mapping as defined in glassfish-web.xml has no influence on the 'user - role' mapping. Calling request.isUserInRole("USER") as well as request.isUserInRole("ADMIN") always returns false. glassfish-web.xml <glassfish-web-app> <security-role-mapping> <role-name>ADMIN</role-name> <group-name>ADMIN</group-name> </security-role-mapping> <security-role-mapping> <role-name>USER</role-name> <group-name>USER</group-name> </security-role-mapping> </glassfish-web-app> Annotating LoginBean.java with @DeclareRoles as shown below, the roles are assigned as expected. LoginBean.java ... @DeclareRoles({"ADMIN", "USERS"}) @Named(value = "loginBean") @RequestScoped public class LoginBean implements Serializable { ... Why do I need the @DeclareRoles in LoginBean.java in order to get a working 'user - role' mapping for request.isUserInRole? A: A similar question on Coderanch cites 17.2.5.3 Declaration of Security Roles Referenced from the Bean’s Code of the EJB 3.1 specification: The Bean Provider is responsible for using the DeclareRoles annotation or the security-role-ref elements of the deployment descriptor to declare all the security role names used in the enterprise bean code. The DeclareRoles annotation is specified on a bean class, where it serves to declare roles that may be tested by calling isCallerInRole from within the methods of the annotated class. Declaring the security roles allows the Bean Provider, Application Assembler, or Deployer to link these security role names used in the code to the security roles defined for an assembled application. [...] If the DeclareRoles annotation is not used, the Bean Provider must use the security-role-ref elements of the deployment descriptor to declare the security roles referenced in the code. (Emphasis mine) So it's just a simple hint to the Deployer and they don't have to interpret the code to get the list of the used roles. It could be really hard if a developer calls the isUserInRole() method with a role name which comes from an other method or from a very complex logic. This also could be useful (from 17.3 Responsibilities of the Bean Provider and/or Application Assembler): The main reason for providing the security view of the enterprise beans is to simplify the Deployer’s job. In the absence of a security view of an application, the Deployer needs detailed knowledge of the application in order to deploy the application securely. For example, the Deployer would have to know what each business method does to determine which users can call it. The security view defined by the Bean Provider or Application Assembler presents a more consolidated view to the Deployer, allowing the Deployer to be less familiar with the application. (I see that the question is about a web application but I think the reasoning behind is the same and servlet spec isn't so detailed.) From Deployer’s Responsibilities: Assignment of Security Roles (17.4.2): The Deployer assigns principals and/or groups of principals (such as individual users or user groups) used for managing security in the operational environment to the security roles defined by means of the DeclareRoles and RolesAllowed metadata annotations and/or security-role elements of the deployment descriptor. So, according to the spec the glassfish-web.xml is created by the Deployer (not the Bean Provider or Application Assembler) and for the Deployer's work he needs the role names from "DeclareRoles and RolesAllowed metadata annotations and/or security-role elements of the deployment descriptor." A: The role-mapping in the glassfish-web.xml translates a Java EE application's security role names into a deployment environments user/group mechanism. The roles are abstract... and until your application uses a role, the mapping is unnecessary and not consulted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to handle exception due to expired authentication ticket using UpdatePanel? I am pretty sure the reason of the error is because the forms authentication "ticket" has expired. When the users have not done any pagerequest for the last 20 minutes and click on any of GridView links (to edit, delete, sort...) the exception is raised: Sys.WebForms.PageRequestManagerServerErrorException 12031. The exception is only raised when the GridView is inside an UpdatePanel. If I delete the UpdatePanel, the application redirects the user to the login page, which should be the expected behaviour. How can I catch this exception, in order to redirect the user to the login page? Note: there is already a question about the same error: Sys.WebForms.PageRequestManagerServerErrorException 12031. However, the reason is different since it is related to the size of the objects stored in the ViewState, which is not my case. A: Add a Global.asax (if you don't have one). protected void Application_Error(object sender, EventArgs e) { // Get the last exception Exception ex = Server.GetLastError(); ... and if the exception is a PageRequestManagerServerErrorException Server.ClearError(); Response.Redirect("~/login"); A: Server-side you can handle this exception from the AsyncPostBackError event of your UpdatePanel. This will allow you for example to log the error. To redirect you need to handle the exception client-side to customize the error handling (and redirect to login in your case). Both are documented here: http://msdn.microsoft.com/en-us/library/bb398934.aspx A: If you are getting a response to the browser with the exception then you can catch it by wiring up the endRequest event of the ScriptManager and checking for the presence of an error and the proper httpStatusCode. Just be sure to add the javascript below the asp:ScriptManager tag so the browser will recognize the namespace. If you need to extend this further check out the MSDN documentation <script type="text/javascript" language="javascript"> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function EndRequestHandler(sender, args) { // Verify the httpStatusCode you are receiving if (args.get_error() != undefined && args.get_error().httpStatusCode == '302') { args.set_errorHandled(true); alert('Authentication expired, redirecting to login page'); location.href='login.aspx'; // Whatever your login page is } } </script> A: I don't know why it happens, but when it does, I just mark the error as handled and nothing blows up. Just add the following JavaScript and you're troubles will disappear. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <script type="text/javascript" > (function() { var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm) { prm.add_endRequest( function (sender, args) { // Any code you want here if(args.get_error() && args.get_error().name === 'Sys.WebForms.PageRequestManagerServerErrorException') { args.set_errorHandled(args._error.httpStatusCode == 0); } }); } })(); </script> </form> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7597854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change ImageView source in Activity onCreate I am working on a android app and I have 3 diff images in my res/drawable and I would like to change which images gets displayed from writing code in my OnCreate in the Acitvity. can this be done? A: Its very easy to set the change the image of an imageview at runtime: imgView.setImageResource(R.drawable.newImage);
{ "language": "en", "url": "https://stackoverflow.com/questions/7597855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to only expose a certain web method in a .Net Web Service to a particular user/group? I have a web service that has multiple web methods. Is there a way to expose only one of these web methods to a certain group or person? As of right now, I use Windows authentication and user groups for authorization. This just allows complete access to the web service. <authentication mode="Windows"/> <authorization> <allow users="*" roles="domain\groupName"/> <deny users="*"/> </authorization> Is there a way to add another group in the roles attribute that would allow access to only "MyMethod" and not the other web methods that exist in the web service? Any help is greatly appreciated! A: Have a look at the Role-based Authorization Options in WCF section in the article Authentication, Authorization, and Identities in WCF. The Declarative Authorization section seems to be what you are looking for. A: I don't think you can define authentication by method, but you can define it by directory or page. So perhaps if you rearrange your methods into discrete services. Here is an example of how to authenticate by page/directory <configuration> <location path="Logon.aspx"> <system.web> <authorization> <allow users="*" roles="domain\groupName"/> <deny users="*"/> </authorization> </system.web> </location> </configuration> And here is a link to the source article which might help you. http://msdn.microsoft.com/en-us/library/b6x6shw7.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7597861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing object in RedirectToAction I want to pass object in RedirectToAction. This is my code: RouteValueDictionary dict = new RouteValueDictionary(); dict.Add("searchJob", searchJob); return RedirectToAction("SearchJob", "SearchJob", dict); where searchJob is instance of SearchJob. But I don't get data on SearchJob action method. Instead I get querystring of searchJob = Entity.SearchJob. Please help me. What am I doing wrong? A: You can not pass classes to the redirected actions like that. Redirection is done by means of URL. Url is a string, so it can not contain classes (serializing objects to url is really out of logic here) Instead, you could use TempData TempData["searchJob"] = searchJob; return RedirectToAction ...; and in Action redirected Entity.SearchJob = (Entity.SearchJob)TempData["searchJob"] ; After executing of the code above, TempData will not contain searchJob anymore. TempData is generally used for single time reading. But I do not like the way above. If I were in your place and wanted to search jobs by name, I would add route parameters like RouteValueDictionary dict = new RouteValueDictionary(); dict.Add("searchJobName", searchJob.JobName); and receive it to action via parameter public ActionResult SearchJob(string searchJobName) { ... do something with the name } This way, you get better user and HTTP friendly URL and from the Action point of view, it would get all the parameters it needs from outside. This is better for testing, maintenance, etc. A: You might try: return RedirectToAction("SearchJob", "SearchJob", new RouteValueDictionary(searchJob)) Passing the searchJob object into the RouteValueDictionary constructor will decompose the searchJob object and pass each property of the SearchJob class as a top-level route value. With the default model binder, an action defined as: public ActionResult SearchJob(SearchJob searchJob) Will receive a fully re-hydrated SearchJob object. A: You can not pass classes to RedirectToAction method, if you want to pass an entire object in a querystring or via POST you can serialize the object using XML or JSON and deserialize the object in the receiver controller. If you use this approach to be careful on the size of the object serialized. A: Try to use Cross-Page Posting you can determin Prevoiuse page type, and use it object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Threads vs Processes in .NET I have a long-running process that reads large files and writes summary files. To speed things up, I'm processing multiple files simultaneously using regular old threads: ThreadStart ts = new ThreadStart(Work); Thread t = new Thread(ts); t.Start(); What I've found is that even with separate threads reading separate files and no locking between them and using 4 threads on a 24-core box, I can't even get up to 10% on the CPU or 10% on disk I/O. If I use more threads in my app, it seems to run even more slowly. I'd guess I'm doing something wrong, but where it gets curious is that if I start the whole exe a second and third time, then it actually processes files two and three times faster. My question is, why can't I get 12 threads in my one app to process data and tax the machine as well as 4 threads in 3 instances of my app? I've profiled the app and the most time-intensive and frequently called functions are all string processing calls. A: It's possible that your computing problem is not CPU bound, but I/O bound. It doesn't help to state that your disk I/O is "only at 10%". I'm not sure such performance counter even exists. The reason why it gets slower while using more threads is because those threads are all trying to get to their respective files at the same time, while the disk subsystem is having a hard time trying to accomodate all of the different threads. You see, even with a modern technology like SSDs where the seek time is several orders of magnitude smaller than with traditional hard drives, there's still a penalty involved. Rather, you should conclude that your problem is disk bound and a single thread will probably be the fastest way to solve your problem. One could argue that you could use asynchronous techniques to process a bit that's been read, while on the background the next bit is being read in, but I think you'll see very little performance improvement there. I've had a similar problem not too long ago in a small tool where I wanted to calculate MD5 signatures of all the files on my harddrive and I found that the CPU is way too fast compared to the storage system and I got similar results trying to get more performance by using more threads. Using the Task Parallel Library didn't alleviate this problem. A: First of all on a 24 core box if you are using only 4 threads the most cpu it could ever use is 16.7% so really you are getting 60% utilization, which is fairly good. It is hard to tell if your program is I/O bound at this point, my guess is that is is. You need to run a profiler on your project and see what sections of code your project is spending the most of it's time. If it is sitting on a read/write operation it is I/O bound. It is possable you have some form of inter-thread locking being used. That would cause the program to slow down as you add more threads, and yes running a second process would fix that but fixing your locking would too. What it all boils down to is without profiling information we can not say if using a second process will speed things up or make things slower, we need to know if the program is hanging on a I/O operation, a locking operation, or just taking a long time in a function that can be parallelized better. A: I think you find out what file cache is not ideal in case when one proccess write data in many file concurrently. File cache should sync to disk when the number of dirty page cache exceeds a threshold. It seems concurrent writers in one proccess hit threshold faster than the single thread writer. You can read read about file system cache here File Cache Performance and Tuning A: Try using Task library from .net 4 (System.Threading.Task). This library have built-in optimizations for different number of processors. Have no clue what is you problem, maybe because your code snippet is not really informative
{ "language": "en", "url": "https://stackoverflow.com/questions/7597869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: valgrind multiple type suppression I'm writing a suppression file for valgrind and I have one like this (taken from the core manual) { libX11.so.6.2/libX11.so.6.2/libXaw.so.7.0 Memcheck:Value4 obj:/usr/X11R6/lib/libX11.so.6.2 obj:/usr/X11R6/lib/libX11.so.6.2 obj:/usr/X11R6/lib/libXaw.so.7.0 } I want to also suppress this { libX11.so.6.2/libX11.so.6.2/libXaw.so.7.0 Memcheck:Cond obj:/usr/X11R6/lib/libX11.so.6.2 obj:/usr/X11R6/lib/libX11.so.6.2 obj:/usr/X11R6/lib/libXaw.so.7.0 } Do I really need to write two suppressions to achieve this? I've searched the manual and online doc and I didn't find an answer. I also tried MemCheck:* but valgrind exited with code 1. So, the question is, can't I combine multiple types of errors in a single suppresion for memcheck? A: No. For multiple suppression types it is necessary to write different suppression blocks even if the calling contexts are the same. Also as can be seen in Valgrind's documentation: http://valgrind.org/docs/manual/mc-manual.html#mc-manual.suppfiles there can only be a single suppression-type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP.Net web form and MySQL with SSH In my project I am supposed to access MySQL database from asp.net web form. The MySQL database is protected by SSH. How can I access the MySQL data from web form using the SSH credentials ..??? Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/7597877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error stray '\302' in program on UIButton setAnimationDuration: I am getting this error "stray '\302' in program ", while I am using this following line of code: [UIButton setAnimationDuration:1.0]; Can anyone tell how can I resolve this error. A: \302 is an unprintable character which is somewhere in the your code near or on the line that you receive the error. Just delete al empty, tabs and spaces it should solve your problem. A: Its right here: ` ` Just a joke. If the above suggestion fails you, perhaps opening the file in another editor that allows you to show all non-pritable characters. Perhaps even Xcode has this feature. TextWrangler does if you have no other available. A: Things like this happen when you copy/paste code from the internet. Delete the affected line and retype it by hand in XCode and the problem should disappear. In the future, be aware of things like this slipping in to your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Removing parts from HTML page in UIWebVIew I'm trying to remove text from html page, and I'm using this code: NSRange *r; while ((r = [commentsOnly rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound) { commentsOnly = [commentsOnly stringByReplacingCharactersInRange:r withString:@""]; NSLog(@"clearing"); } It removes html tags perfect, but how can I remove only one tag? For example, title or p. I don't want to remove only my tag. I want to remove start tag (<p>), info between two tags and close tag (<\p>). A: If I understand your question, may be this will help you: NSString *string = @"</body>", *htmlString = @"ddsfsdf_<body>_sdfsfd_<body>ffff</body></body>"; NSRange range = [htmlString rangeOfString:string]; if (range.location != NSNotFound) { range.length += range.location; range.location = 0; string = @"<body>"; NSRange rangeOpen = [htmlString rangeOfString:string options:NSBackwardsSearch range:range]; if (rangeOpen.location != NSNotFound) { range.length -= rangeOpen.location; range.location = rangeOpen.location; htmlString = [htmlString stringByReplacingCharactersInRange:range withString:@""]; NSLog(@"%@", htmlString); } } A: Use stringByEvaluatingJavaScriptFromString: to execute JavaScript within the UIWebView to do this. This is much less work and is also much more reliable, as it will use WebKit's HTML parser instead of naïve string replacement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best technology for client-server Android App I need to make for school an app that runs on Android. Actually there are two apps, a client and a server. Ther server runs on a PC while the clients run on Android devices. I want to know what is the best technology for this. I know RMI and WebServices are not implemented in Android so what are the alternatives (besides actually communicating with sockets in the traditional way). One alternative that I did not look into is REST, but I will need to be able to notify a client once another client has done something, similar to turn base games where Player A notifies Player B that he made his move. Like I said, sockets do the trick, but are little low-level compared to RMI and WebServices and only want to use those as a last resort. A: Keep it simple. Use REST and have the clients poll for updates. Also, if you get to a point down the road where you need to scale, this solution is actually fairly easy to scale because your servers do not need to maintain connections. Since there is no shared state between a particular server and the client (there is shared server between the application and the client), you can easily add more servers to handle the polling and put them behind a load balancer. You can also add in caching so that the polling just gets the exact same response without causing a re-compute of the response. You would then be able to have the back-end game-state servers update the caches when the game state changes. This would let you poll much more frequently and still have a very flexible, scalable architecture. A: For a turn-based game you can take a look at XMPP (e.g. Smack) that is traditionally used for instant messaging. It would also be interesting to create a game using C2DM that is used for push notifications. You can also look into HTTP streaming which is essentially an unending HTTP response in which player moves are fed into. Alternatively you can look into binary messaging systems that are more suited for real-time games but still applicable such as RabbitMQ (what's wrong with a smooth turn-based game?).
{ "language": "en", "url": "https://stackoverflow.com/questions/7597881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best practice for Broadcasts, ContentProviders, and ContentRecievers Okay so up front I will say that I am new to Android. I have made a few small projects and played with a few things and done tons and tons of reading. So here is the task I am trying to accomplish: I have a remote service that runs in the foreground of my phone that can send and receive information with other android devices over a wifi network. APK's on the phone that are built to use this service contain multiple SQLite DB's. I want these APK's to register there content providers with the service so the service always know where to put data that it recieves (I have accomplished this task). When data comes in I will identify where it belongs and place it in the right DB (no problem here). So what would be the best way to notify the correct activity that new data has been received. Do I register Broadcast Receivers for my service to call? Will Broadcast Receivers work if the APK has been killed by the OS? Once the correct activity is loaded would I use a content observer to show the new data? Why would I use IntentServices? I'm sorry for so many questions. Like I said I am learning fast but Android's SKD is massive and there are so many cool things. I want to make sure I am thinking things through right with best practices and making this very easily maintainable and expandable. Thanks for any help or advice I can get. A: If you are asking what the best way is for a current Activity to know data has changed in the ContentProvider it is reading from, than the answer is a ContentObserver. Lets say, for examples sake, you have a set of Activities and ContentProviders. Activity A is a list view of items from Content Provider A, and that list view is populated via a CursorAdapter of some kind. Whenever you have a query on a ContentProviders CONTENT_URI, the cursor should automatically monitor the CONTENT_URI for changes via a ContentObserver. The reason this works is because in the ContentProvider: * *Your query method calls setNotificationUri on your cursor to the URI that was queried. *Whenever a change happens in an insert/update/delete method, you are calling notifyChange on the URI. If there is additional data that can change in your service that is not tied to a ContentProvider, than you have a few choices on how to pass data. If the Activity is in the same APK as your service, than you could use some sort of static variable, or the application context, or some other custom form of communication. The methods are rather liberal here because you are running in the same VM, so you have a lot of things available to you. In your situation, it sounds like most activities will be in separate APKs. If that is the case, you will probably want to send out broadcast Intents to let the entire system knwo about the changes. If these changes only matter when an activity is running, you can register a BroadcastReceiver for the life of the Activity that cares about the change. Alternatively, you could put a BroadcastReceiver in the applications manifest, and always receive that change. That brings us to IntentServices. IntentServices are the "easiest" way to handle long running tasks in Android. All they do, is create a background thread that will handle intents being sent into the service. A common use case is as follows: * *You receive a broadcast intent that you need to react to (and it will take a while) *Send a directed intent (intent with a set component name) to an IntentService with some info from the broadcast intent. *IntentService either spawns a new BG thread, or adds the intent to the processing queue on the existing BG thread *The onHandleIntent function is called in the IntentService so that you can now process that change using as much processing time as you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can enctype="multipart/form-data" be used for non file inputs as well? Is this allowed? <form enctype="multipart/form-data" action="__URL__" method="POST"> <input type="text" name="text_input" /> <input type="other_types" name="other_types_input" /> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> <input name="userfile" type="file" /> <input type="submit" value="Submit" /> </form> It will be used with PHP... A: Yes, it's absolutely correct. No issues. A: This is perfectly fine. It's how forms with file elements in them are normally structured. A: Though the question is old, the answers already posted has no explanation, so I am adding this, so that it will be helpful for future readers. The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header. The content type is selected by putting the adequate string in the enctype attribute of the element or the formenctype attribute of the or elements. HTML forms provide three methods of encoding. * *application/x-www-form-urlencoded (the default) *multipart/form-data *text/plain for multipart/form-data, each value is sent as a block of data ("body part"), with a user agent-defined delimiter ("boundary") separating each part. The keys are given in the Content-Disposition header of each part. It does not matter if you are sending file or not. so it should be fine. Refer mozila doc
{ "language": "en", "url": "https://stackoverflow.com/questions/7597888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC3 & JSON.stringify() ModelBinding returns null model I am trying to get model binding with MVC3 and JSON working but I have had no luck... No matter what I do I seem to be getting a null model on the server. Method Signature: public ActionResult FilterReports(DealSummaryComparisonViewModel model) Javascript UPDATED: <script type="text/javascript" language="javascript"> $(document).ready(function () { $('#filter-reports').click(filterReports); }); function filterReports() { var filters = { SelectedRtoId: $('#SelectedRtoId').val(), SelectedPricingPointId: $('#SelectedPricingPointId').val(), SelectedLoadTypeId: $('#SelectedLoadTypeId').val(), SelectedBlockId: $('#SelectedBlockId').val(), SelectedRevisionStatusId: $('#SelectedRevisionStatusId').val() } var dealSummaries = { SelectedItemIds: $('#SelectedItemIds').val() } var model = { ReportingFilters: filters, DealSummaries: dealSummaries } $('#selected-items select option').attr("selected", "selected"); $.ajax({ url: '@Url.Action("FilterReports")', data: model, contentType: 'application/json', dataType: 'json', success: function (data) { alert(data); } }); } </script> Models: public class DealSummaryComparisonViewModel { public ReportingFiltersViewModel ReportingFilters { get; set; } public LadderListViewModel DealSummaries { get; set; } } public class LadderListViewModel { public MultiSelectList AvailableItems { get; set; } public int[] SelectedItemIds { get; set; } public MultiSelectList SelectedItems { get; set; } } public class ReportingFiltersViewModel { public int? SelectedRtoId { get; set; } public ICollection<Rto> Rtos { get; set; } public int? SelectedPricingPointId { get; set; } public ICollection<PricingPoint> PricingPoints { get; set; } public int? SelectedLoadTypeId { get; set; } public ICollection<LoadType> LoadTypes { get; set; } public int? SelectedBlockId { get; set; } public ICollection<Block> Blocks { get; set; } public int? SelectedRevisionStatusId { get; set; } public ICollection<RevisionStatus> RevisionStatuses { get; set; } public bool? DealStatus { get; set; } } The model looks fine on the client side: {"ReportingFilters":{ "SelectedRtoId":"5", "SelectedPricingPointId":"20", "SelectedLoadTypeId":"55", "SelectedBlockId":"21", "SelectedRevisionStatusId":"11" },"DealSummaries":{ "SelectedItemIds":["21","22","23","24","25"] }} So why am I getting nothing back on the controller? This has been giving me trouble for the past two days so please help! Thanks!! UPDATE I've updated my javascript section to what I am currently using. This section now returns the model to the controller with the ReportingFilers and DealSummaries objects, but all values within are null. Does it possibly have something to do with the values being strings? If so, how can I fix this? A: Change your $.getJSON line to: $.ajax({ url: '@Url.Action("FilterReports")', data: JSON.stringify(viewModel), contentType: 'application/json', dataType: 'json', success: function (data) { alert(data); } }); This way MVC knows that it is receiving JSON and will bind it to your model correctly. A: Here's a few different things you could try: * *Apparently you shouldn't use nullable properties in your objects if you want to use the DefaultModelBinder: ASP.NET MVC3 JSON Model-binding with nested class. So you could try making your ints not nullable or if that's not an option, implement IModelBinder yourself? *Have you marked your classes with the SerializableAttribute? *Try setting the type parameter in the ajax method to 'POST' - it will be using 'GET' by default.. type: 'POST' *Try explicitly setting the contentType parameter in the ajax method to this instead... contentType: 'application/json; charset=utf-8' *And finally, are you definitely using MVC 3, not MVC 2? I ask because MVC 3 has the JsonValueProviderFactory baked into the framework where as MVC 2 didn't so if you were using MVC 2 that might explain the problem you're having... A: Ok, replace: { model: JSON.stringify(viewModel) } with { model: viewModel } You're mixing objects with JSON strings, so jQuery will JSON.stringify the entire object. Which will double encode viewModel. A: here is what I would suggest, in your controllers action method should look as follows: public JsonResult FilterAction(string model) { var viewModel=new JavaScriptSerializer().Deserialize<DealSummaryComparisonViewModel>(model); } Also make sure your request is reaching the right action and look at Firebug for the same. A: Try this: var filters = new Object(); filters.SelectedRtoId = $('#SelectedRtoId').val(); filters.SelectedPricingPointId = $('#SelectedPricingPointId').val(); filters.SelectedLoadTypeId = $('#SelectedLoadTypeId').val(); filters.SelectedBlockId = $('#SelectedBlockId').val(); filters.SelectedRevisionStatusId = $('#SelectedRevisionStatusId').val(); var dealSummaries = new Object(); dealSummarties.SelectedItemIds = $('#SelectedItemIds').val(); var viewModel = new Object(); viewModel.ReportingFilters = filters; viewModel.DealSummaries = dealSummaries; $('#selected-items select option').attr("selected", "selected"); $.getJSON('@Url.Action("FilterReports")', { model: JSON.stringify(viewModel) }, function (data) { alert(data); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7597892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: I would like to fill a jqmodal with data coming from a jquery post() I have this code which is functional: jQuery("#Zone__" + row + "__documents").find("td:eq(3)").mouseover(function(){ var text = jQuery("#Zone__" + row + "__documents").find("td:eq(3)").html(); if(text.indexOf("...") > 0){ jQuery.post("/_common/cfc/act_get.cfc?method=getNcas&returnFormat=json", {document_id:doc_id,maxnum:100}, function(res,code){ alert(res); }, "json" ); } }); Now, instead of an alert, I would like to open the jquery plugin 'jqmodal' with the data coming from the post inside it (res). Could someone help me to achieve this ? Thank you in advance, Michel A: Not familiar with that plugin but by a quick read of the documentation I would expect this to work (assuming you have included the required .js/.css resources: <div class="jqmWindow" id="dialog"></div> $(document).ready(function() { $('#dialog').jqm(); jQuery("#Zone__" + row + "__documents").find("td:eq(3)").mouseover(function(){ var text = jQuery("#Zone__" + row + "__documents").find("td:eq(3)").html(); if(text.indexOf("...") > 0){ jQuery.post("/_common/cfc/act_get.cfc?method=getNcas&returnFormat=json", {document_id:doc_id,maxnum:100}, function(res,code){ $('#dialog').html(res); $('#dialog').jqmShow(); }, "json"); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7597895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 32bit TIFF to another format in Python I need to convert a 32 bit TIFF file (or the corresponding int32 array) to another format that Tkinter can display (like gif fe) How do I do that? Converting the array to int16 or so completely blurs the picture... A: PIL is your best friend. A: You can use PIL, Image Magick, or GraphicsMagick GraphicsMagic and ImageMagick are command-line programs and have python versions. I use Graphics Magic because it is simple. ImageMagick is almost a command-line version of photoshop...
{ "language": "en", "url": "https://stackoverflow.com/questions/7597899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading newly created entity from object context I have ObjectContext and entity, let's call it Device. Entity key of entity is not autogenerated, and is specified during adding to context. After adding of new entity with following code Context.Devices.Add(new Device{Id = someVal, /*initialization*/}); I am trying to read that entity var dev = Context.Devices.SingleOrDefault(d => d.Id == someVal); and getting null. Of course, after calling of SaveChanges() I can read that device from DB. Why I can't read entity from context? A: Because until you call SaveChanges it does not actually exist in the database. Your call to Context.Devices.SingleOrDefault(d => d.Id == someVal); is making a call back to the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ODBC Call Syntax for multiple return values So first off, sorry for the length of the question... So basically I'm having issues calling a stored proc from an Informix database where the stored proc has multiple return value, while using ODBC in .NET (aka an ODBCCommand), and I haven't seen anything on the internet where someone has done this before... so is it even possible? So to begin with using an ODBCCommand (or ODBC in general) to call an SP your supposed to use the ODBC Call Syntax. Rough Stored Procedure: create procedure informix.proc_ins ( n_company char(10), n_message_body lvarchar(4096), n_time int, n_time_dt datetime year to second, n_processed smallint) returning int, int; begin define row_count int; define new_serial int; INSERT into my_table ( company, message_body, time, time_dt, processed, create_user, create_dt, recmod_user, recmod_dt) VALUES ( n_company, n_message_body, n_time, n_time_dt, n_processed, USER, CURRENT YEAR TO SECOND, USER, CURRENT YEAR TO SECOND); let new_serial = DBINFO('sqlca.sqlerrd1'); let row_count = DBINFO('sqlca.sqlerrd2'); return new_serial, row_count; end end procedure; So given this SP the ODBC Call Syntax would look something like: {XXXX = call informix.proc_ins(?,?,?,?,?)} where 'XXXX' somehow has 2 '?'s... ? Any help with this would be really appreciated. Also before someone says "use the IBM.Data.Informix drivers" (either of them), it's not possible in this case because the 'old' one doesn't work with VS2010, and the new one can't be installed on the same PCs as the old one at the same time, but that's a totally different rant for another day. A: The way I'd do it in ESQL/C is to treat the EXECUTE PROCEDURE informix.proc_ins(...) statement as if it was a SELECT statement - that is, declare a cursor (possibly after preparing the statement), and then using OPEN (chance to pass in parameters) and FETCH and CLOSE to get the data. I'd expect to use the same technique in ODBC - probably bypassing the general ODBC Call Syntax. If you need the official answer using the official ODBC notation/method, you'll have to get someone else to provide the answer. A: I don't believe there is a "official" ODBC answer. Its down to the driver. There is nothing stopping you from using SQL_PARAM_RETURN as the type for more than one parameter, but as to how you would call that, ODBC doesn't say.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Defining maximum variance of an UITextView If you have a normal UITextView with loads of text in it you can swipe up and down: * *if you swipe left or right in a very horizontal line, nothing will happen *if you swipe left or right with a very slight angle, you will swipe up or down So there is obviously some kind of class definition which tells the UITextView when to react to a swipe and when not to. Something like a maximumVariance constant, I guess. My problem is that I'm trying to subclass an UITextView to enable left/right swipe. However, you will need to swipe in a pretty straight line, otherwise, you'll get an up or down swipe. So my question is if there is someway to re-define the standard variance variable of an UITextView? Here is my subclass .m file. Note that the kMaximumVariance doesn't really have any effect as this is overwritten by whatever variance the standard UITextView class provides: // // SwipeTextView.m // Swipes // #import "SwipeTextView.h" #import "PageView.h" #define kMinimumGestureLength 15 #define kMaximumVariance 100 @implementation SwipeTextView @synthesize delegate, gestureStartPoint; - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; UITouch *touch =[touches anyObject]; gestureStartPoint = [touch locationInView:self]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; [self resignFirstResponder]; // this hides keyboard if horizonal swipe UITouch *touch = [touches anyObject]; CGPoint currentPosition = [touch locationInView:self]; CGFloat deltaXX = (gestureStartPoint.x - currentPosition.x); // positive = left, negative = right CGFloat deltaYY = (gestureStartPoint.y - currentPosition.y); // positive = up, negative = down CGFloat deltaX = fabsf(gestureStartPoint.x - currentPosition.x); // will always be positive CGFloat deltaY = fabsf(gestureStartPoint.y - currentPosition.y); // will always be positive NSLog(@"deltaXX (%.1f) deltaYY (%.1f) deltaX (%.1f) deltaY (%.1f)",deltaXX, deltaYY, deltaX, deltaY); if (deltaX >= kMinimumGestureLength && deltaY <= kMaximumVariance) { if (deltaXX > 0) { NSLog(@"Horizontal Left swipe - FINISHED detected"); } else { NSLog(@"Horizontal Right swipe - FINISHED detected"); } } } @end EDIT: Suggestion to cancel touches reaching UITextView (see below): // Prevent recognizing touches - (BOOL)gestureRecognizer:(UISwipeGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { if ([gestureRecognizer direction] == UISwipeGestureRecognizerDirectionLeft) { // Left swipe: I want to handle this return YES; } if ([gestureRecognizer direction] == UISwipeGestureRecognizerDirectionRight) { // Right swipe: I want to handle this return YES; } if ([gestureRecognizer direction] == UISwipeGestureRecognizerDirectionUp) { // Up swipe: textView needs to handle this return NO; } if ([gestureRecognizer direction] == UISwipeGestureRecognizerDirectionDown) { // Down swipe: textView needs to handle this return NO; } else return YES; } -(void)viewDidLoad { UITapGestureRecognizer *GesRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSomething:)]; [GesRec setCancelsTouchesInView:NO]; [self addGestureRecognizer:GesRec]; [GesRec release]; } -(void)doSomething { NSLog(@"doSomething"); } A: Try adding an UISwipeGestureRecognizer to the view and set cancelsTouchesInView to false so the swipe gesture is not passed through. This should let you detect left and right motion more accurately. If this doesn't do the trick, implement your own subclass of UIGestureRecognizer and add that instead. Edit You add the gesture recognizer to the UITextView in your controller's viewDidLoad method. In your delegate methods, you can't return NO in gestureRecognizer:shouldReceiveTouch: because it means the gesture recognizer won't examine the incoming touch object. In your case you want to return YES when the swipe is horizontal and NO otherwise, so vertical swipes are passed through while horizontal swipe is completed handled by you. A: No subclass needed. set textView.userInteractionEnabled to NO and than put a transparent UIView over your textView. handle touches and gestures anyway you want on that UIView and make the textView respond to these programatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i inject dependencies to Symfony Console commands? I'm writing an open source application uses some Symfony components, and using Symfony Console component for interacting with shell. But, i need to inject dependencies (used in all commands) something like Logger, Config object, Yaml parsers.. I solved this problem with extending Symfony\Component\Console\Command\Command class. But this makes unit testing harder and not looks correct way. How can i solve this ? A: Since Symfony 4.2 the ContainerAwareCommand is deprecated. Use the DI instead. namespace App\Command; use Symfony\Component\Console\Command\Command; use Doctrine\ORM\EntityManagerInterface; final class YourCommand extends Command { /** * @var EntityManagerInterface */ private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; parent::__construct(); } protected function execute(InputInterface $input, OutputInterface $output) { // YOUR CODE $this->entityManager->persist($object1); } } A: You can use ContainerCommandLoader in order to provide a PSR-11 container as follow: require 'vendor/autoload.php'; $application = new Application('my-app', '1.0'); $container = require 'config/container.php'; // Lazy load command with container $commandLoader = new ContainerCommandLoader($container, [ 'app:change-mode' => ChangeMode::class, 'app:generate-logs' => GenerateLogos::class, ]); $application->setCommandLoader($commandLoader); $application->run(); ChangeMode class could be defined as follow: class ChangeMode extends Command { protected static $defaultName = 'app:change-mode'; protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; parent::__construct(static::$defaultName); } ... NB.: ChangeMode should be provided in the Container configuration. A: It is best not to inject the container itself but to inject services from the container into your object. If you're using Symfony2's container, then you can do something like this: MyBundle/Resources/config/services (or wherever you decide to put this file): ... <services> <service id="mybundle.command.somecommand" class="MyBundle\Command\SomeCommand"> <call method="setSomeService"> <argument type="service" id="some_service_id" /> </call> </service> </services> ... Then your command class should look like this: <?php namespace MyBundle\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use The\Class\Of\The\Service\I\Wanted\Injected; class SomeCommand extends Command { protected $someService; public function setSomeService(Injected $someService) { $this->someService = $someService; } ... I know you said you're not using the dependency injection container, but in order to implement the above answer from @ramon, you have to use it. At least this way your command can be properly unit tested. A: use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; Extends your Command class from ContainerAwareCommand and get the service with $this->getContainer()->get('my_service_id'); A: I'm speaking for symfony2.8. You cannot add a constructor to the class that extends the ContainerAwareCommand because the extended class has a $this->getContainer() which got you covered in getting your services instead of injecting them via the constructor. You can do $this->getContainer()->get('service-name'); A: Go to services.yaml Add This to the file(I used 2 existing services as an example): App\Command\MyCommand: arguments: [ '@request_stack', '@doctrine.orm.entity_manager' ] To see a list of all services type in terminal at the root project folder: php bin/console debug:autowiring --all You will get a long list of services you can use, an example of one line would look like this: Stores CSRF tokens. Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface (security.csrf.token_storage) So if CSRF token services is what you are looking for(for example) you will use as a service the part in the parenthesis: (security.csrf.token_storage) So your services.yaml will look somewhat like this: parameters: services: _defaults: autowire: true autoconfigure: true # Here might be some other services... App\Command\MyCommand: arguments: [ '@security.csrf.token_storage' ] Then in your command class use the service in the constructor: class MyCommand extends Command { private $csrfToken; public function __construct(CsrfToken $csrfToken) { parent::__construct(); $this->csrfToken = $csrfToken; } } A: In Symfony 3.4, if autowire is configured correctly, services can be injected into the constructor of the command. public function __construct( \AppBundle\Handler\Service\AwsS3Handler $s3Handler ) { parent::__construct(); $this->s3Handler = $s3Handler; } A: php 8.1 Symfony 6.1 public function __construct(private EntityManagerInterface $em, string $name = null) { parent::__construct($name); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "46" }
Q: CheckBoxList AJAX async postback issue I have 2 CheckBoxList controls - chk1 and chk2. I need to use an async postback to clear the selections of a CheckBoxList if the other one is selected. The following will not clear chk1 if it had selections, and an item chk2 was checked: <asp:ScriptManager ID="sm1" runat="server" ></asp:ScriptManager> <asp:UpdatePanel ID="upd" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="chk1" /> <asp:AsyncPostBackTrigger ControlID="chk2" /> </Triggers> <ContentTemplate> <asp:Label ID="result" runat="server" /> </ContentTemplate> </asp:UpdatePanel> <div style="overflow: auto; height: 150px;"> <asp:CheckBoxList runat="server" ID="chk1" OnDataBound="assignClickBehaviours" AutoPostBack="true"> <asp:ListItem Value="1" Text="One"></asp:ListItem> <asp:ListItem Value="2" Text="Two"></asp:ListItem> <asp:ListItem Value="3" Text="Three"></asp:ListItem> <asp:ListItem Value="100" Text="..."></asp:ListItem> <asp:ListItem Value="150" Text="One hundred and Fifty"></asp:ListItem> </asp:CheckBoxList> </div> <div style="overflow: auto;"> <asp:CheckBoxList runat="server" ID="chk2" AutoPostBack="true"> <asp:ListItem Value="1" Text="One"></asp:ListItem> <asp:ListItem Value="2" Text="Two"></asp:ListItem> <asp:ListItem Value="3" Text="Three"></asp:ListItem> </asp:CheckBoxList> </div> code behind: protected void Page_Load(object sender, EventArgs e) { processChecks(); } private void processChecks() { if(chk2.SelectedIndex>-1) chk1.ClearSelection(); } If the whole thing was put in the update panel, it would work... but because there can be 150 items in the checkbox, the scrolling on the overflow:auto would flick back to the top if an item at the bottom was selected. I need the scroll state to stay put (hence the need for async postback). Any ideas or alternatives? A: You can try this code .. <body> <form id="form1" runat="server"> <asp:ScriptManager ID="sm1" runat="server" ></asp:ScriptManager> <asp:UpdatePanel ID="upd" runat="server"> <ContentTemplate> <br /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="chk1"> </asp:AsyncPostBackTrigger> <asp:AsyncPostBackTrigger ControlID="chk1"> </asp:AsyncPostBackTrigger> </Triggers> </asp:UpdatePanel> <div style="overflow: auto; height: 150px;"> <asp:CheckBoxList runat="server" ID="chk1" AutoPostBack="true"> <asp:ListItem Value="1" Text="One"></asp:ListItem> <asp:ListItem Value="2" Text="Two"></asp:ListItem> <asp:ListItem Value="3" Text="Three"></asp:ListItem> <asp:ListItem Value="100" Text="..."></asp:ListItem> <asp:ListItem Value="150" Text="One hundred and Fifty"></asp:ListItem> </asp:CheckBoxList> </div> <div style="overflow: auto;"> <asp:CheckBoxList runat="server" ID="chk2" AutoPostBack="true"> <asp:ListItem Value="1" Text="One"></asp:ListItem> <asp:ListItem Value="2" Text="Two"></asp:ListItem> <asp:ListItem Value="3" Text="Three"></asp:ListItem> </asp:CheckBoxList> </div> </form></body> A: Please try with this code, * *Enable Auto post back on both the checkbox lists. *Then embed both the checkbox lists inside an update panel. *Include the C# code inside selected Index changed event of each checkboxes, In this case it is your processChecks(); Please make the following changes, Notice the EventName 'SelectedIndexChanged' <asp:ScriptManager ID="sm1" runat="server" ></asp:ScriptManager> <asp:UpdatePanel ID="upd" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="chk1" EventName="SelectedIndexChanged"/> <asp:AsyncPostBackTrigger ControlID="chk2" EventName="SelectedIndexChanged"/> </Triggers> <ContentTemplate> <asp:Label ID="result" runat="server" /> <div style="overflow: auto; height: 150px;"> <asp:CheckBoxList runat="server" ID="chk1" AutoPostBack="true"> <asp:ListItem Value="1" Text="One"></asp:ListItem> <asp:ListItem Value="2" Text="Two"></asp:ListItem> <asp:ListItem Value="3" Text="Three"></asp:ListItem> <asp:ListItem Value="100" Text="..."></asp:ListItem> <asp:ListItem Value="150" Text="One hundred and Fifty"></asp:ListItem> </asp:CheckBoxList> </div> <div style="overflow: auto;"> <asp:CheckBoxList runat="server" ID="chk2" AutoPostBack="true"> <asp:ListItem Value="1" Text="One"></asp:ListItem> <asp:ListItem Value="2" Text="Two"></asp:ListItem> <asp:ListItem Value="3" Text="Three"></asp:ListItem> </asp:CheckBoxList> </div> </ContentTemplate> </asp:UpdatePanel>
{ "language": "en", "url": "https://stackoverflow.com/questions/7597914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to show a shell only once all the modules have been loaded? I'm currently working on an application which uses PRISM 4 to divide its functionalities in different modules. I noticed that my application's Shell, which holds the modules' views in its regions, is loaded and displayed before the modules are loaded. This means that the Shell is displayed first, and a considerable amount of time later (about half a second), the modules are loaded and the views inserted into the Shell's regions. It's rather annoying, as the user is greeted with an empty shell at start-up, which isn't very professional. Is there any way to detect when all the modules have been loaded ? Any method I can override in the bootstrapper ? If I could, I would like to hide the Shell (or display a loading adorner) until all the modules have been loaded. A: You can show your Shell view after Modules are initialized: protected override void InitializeShell() { Application.Current.MainWindow = (Window)Container.Resolve<ShellView>(); } protected override void InitializeModules() { base.InitializeModules(); Application.Current.MainWindow.Show(); } A: I found a relatively simple solution. My application has a class named ShellHandler, which is instanciated in the bootstrapper and registered in the Unity Container as a singleton: Container.RegisterType<IShellHandler, ShellHandler>(new ContainerControlledLifetimeManager()); I created in my ShellHandler a method which can be used by modules to flag themselves as loaded: /// <summary> /// Method used to increment the number of modules loaded. /// Once the number of modules loaded equals the number of modules registered in the catalog, /// the shell displays the Login shell. /// This prevents the scenario where the Shell is displayed at start-up with empty regions, /// and then the regions are populated as the modules are loaded. /// </summary> public void FlagModuleAsLoaded() { NumberOfLoadedModules++; if (NumberOfLoadedModules != ModuleCatalog.Modules.Count()) return; // Display the Login shell. DisplayShell(typeof(LoginShell), true); } Finally, in my ModuleBase class, which all modules implement, I created an abstract method which is called during the initialization process: /// <summary> /// Method automatically called and used to register the module's views, types, /// as well as initialize the module itself. /// </summary> public void Initialize() { // Views and types must be registered first. RegisterViewsAndTypes(); // Now initialize the module. InitializeModule(); // Flag the module as loaded. FlagModuleAsLoaded(); } public abstract void FlagModuleAsLoaded(); Each module now resolves the instance of the ShellHandler singleton through their constructor: public LoginModule(IUnityContainer container, IRegionManager regionManager, IShellHandler shellHandler) : base(container, regionManager) { this.ShellHandler = shellHandler; } And finally they implement the Abstract method from ModuleBase: /// <summary> /// Method used to alert the Shell Handler that a new module has been loaded. /// Used by the Shell Handler to determine when all modules have been loaded /// and the Login shell can be displayed. /// </summary> public override void FlagModuleAsLoaded() { ShellHandler.FlagModuleAsLoaded(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Scope of System.setProperty in Tomcat This question is "cousin" of this one involving Android. But here we are in Tomcat environment. If in my webapp I set a property with System.setProperty("property_name", "property_value");, which scope will it be applied to? * *all JVM in this machine *all Tomcat webapps *only the webapp that executes the instruction *only the thread that executes the instruction *something else... Many thanks! A: A system property has a JVM scope. The property will thus be modified (and available) in the whole tomcat JVM, for all the webapps and for Tomcat itself. Note that the system property is stored in memory, and will thus not persist if you stop and restart Tomcat. A: In Java System.setProperty() always applies to the entire JVM. So yes, it will affect the whole Tomcat instance, including all webapps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Send accelerator with mouse to perform selection of text I need to make selection of text using mouse instead of ctrl+A I tried: sendAcceleratorKey(MouseEvent.BUTTON1, ""); but I don't know which argument could I set to say make a click with mouse and let the mouse enforced to select the text. A: If the text is in a JTextComponent, selectAll() may be a suitable choice in your MouseListener. Addendum: You may also be able to leverage the select-all Action, which is bound to control-A or meta-A by default on various platforms. Your sscce may be helpful in deciding. There's a related example here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I use subqueries in a 'containable' condition? In my CakePHP I have ModelA which hasMany ModelB. ModelB has an int value Q. Can I query ModelA and use containable to ensure that only those ModelB records with the maximum value for Q? I've tried this: $this->ModelA->contain(array( 'ModelB.Q =(SELECT MAX(ModelB.Q) FROM modelb ModelB WHERE ModelA_id = ' . $id . ')' )); But it throws a MySQL error because CakePHP interprets the right hand side of that equality operator as a field (at least I think that's why) and so dots it. ... WHERE `Draw`.`round` =.(SELECT MAX.(`Draw`.`round`) ... Is there a way to do this? I'd prefer not to have to drop down into $query() mode, if at all possible. EDIT OK, after trying to follow the advice on the page that api55 suggested, I have this code: $dbo = $this->Tournament->getDataSource(); $conditionsSubQuery['"Draw"."tournament_id"'] = $id; $maxRounds = $dbo->buildStatement(array( 'fields' => array('MAX(Draw.round) AS prevRound'), 'table' => $dbo->fullTableName($this->Tournament->Draw), 'alias' => 'Draw', 'limit' => null, 'offset' => null, 'joins' => array(), 'conditions' => $conditionsSubQuery, 'order' => null, 'group' => null ), $this->Tournament ); $maxSubQuery = ' "Draw"."round" = (' . $maxRounds . ') '; $maxSubQueryExpression = $dbo->expression($maxSubQuery); $this->Tournament->contain(array( 'Entrant.selected = 1', $maxSubQueryExpression )); $tournament = $this->Tournament->read(null, $id); But when it runs, it gives me 7 notice/warnings. The first 6 are to do with an object being passed instead of a string: preg_match() expects parameter 2 to be string, object given And 6 variations on this: Object of class stdClass to string conversion The last is less clear: Model "Tournament" is not associated with model "" I suspect I'm being colossally stupid, but there we go. A: The contain uses conditions as a normal find, a subquery can be generated and put in conditions. So you should be able to do this as well. Try the subquery part in here and tell me how did it go ;) This way of generating subqueries for conditions shouldn't fail :D since is the cakephp way. If you got an error or something comment the answer to see if i can help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET 4.0 Page.Response.Write vs <%= %> I have some UserControls in a webpage. When I use it in the ASPX code of my UserControl as such <div><% Page.Response.Write("<a href='http://www.microsoft.com'>test</a>") %></div>, my anchor is rendered at the start of the page: <a href='http://www.microsoft.com'>test</a><html><head> instead of the expected: <html><head /><body> <a href='http://www.microsoft.com'>test</a></body></html> But if i use <div><%="<a href='http://www.microsoft.com'>test</a>" %></div> then the response is written inline as expected. We used this technique of Page.Response.Write() a lot in .NET 3.5, and now migrating to .NET 4.0, we are experiencing this problem with it. Why does it happen in .NET 4.0? A: I would move to using the Literal control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ArgumentError: assertion message must be String or Proc using assert_select I'm writing a controller test for a rails 3.1 app using testunit 2.4.0. I want to assert that a certain heading does not appear on the page. I'm using assert_select like this: assert_select 'h1', {:text => /Key Dates/, :count => 0} and getting the following error: ArgumentError: assertion message must be String or Proc: <</Key Dates/> expected but was <"Planner Maternity leave">.>(<Test::Unit::Assertions::AssertionMessage>) I've tracked this down to the fact that assert_select calls build_message which creates an instance of AssertionMessage and passes it through to test-unit's assert. However in version 2.2 of testunit (Feb 2011) checks were added which check the type of the message passed in. These checks trigger the ArgumentError seen above. I'm not sure whether the mistake lies with test-unit being over-strict or assert_select passing the wrong object type. Can you advise how best to follow this up? Any work-arounds? A: So, the assert_select documentation shows the following example, passing a block in: assert_select "ol" do |elements| elements.each do |element| assert_select element, "li", 4 end end So what if you did something like... assert_select 'h1' do |elements| elements.length == 0 ? fail elements.each do |element| element.text ~= /Key Dates/ ? fail end end Which basically fails if it finds the pattern OR if the number of h1 elements is zero. Obviously you would change the conditions to match what it is you're trying to test for, but does that get you any closer to what you need? A: If you cannot upgrade to a bug-free version, you can just pass a third argument (the message), so you do not force the message be built: assert_select 'h1', {:text => /Key Dates/, :count => 0}, "Unexpected Key Dates found."
{ "language": "en", "url": "https://stackoverflow.com/questions/7597931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: (De)Serializing "Object"s I have to XML (de)serialize the following class: this gives the following output: <ArrayOfPropertyFilter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <PropertyFilter> <AndOr>And</AndOr> <LeftBracket>None</LeftBracket> <Property>17</Property> <Operator>Equal</Operator> <Value xsi:type="xsd:string">lll</Value> <RightBracket>None</RightBracket> </PropertyFilter> </ArrayOfPropertyFilter> and, after deserialization it gives How can I "tell" to Serializer to keep the Value "as is", without any XML node....(in the concrete case the Value should be "lll" and not XMLNode containing Text "lll") ? EDIT Bellow is a full working sample in C#. The output is Value is = 'System.Xml.XmlNode[]' using System; using System.IO; using System.Text; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; namespace WindowsFormsApplication13 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { PropertyFilter filter = new PropertyFilter(); filter.AndOr = "Jora"; filter.Value = "haha"; filter.Property = 15; var xml = filter.SerializeToString(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); PropertyFilter cloneFilter = xmlDoc.Deserialize<PropertyFilter>(); Console.WriteLine("Value is = '{0}'", cloneFilter.Value); } } public class PropertyFilter { public string AndOr { get; set; } public string LeftBracket { get; set; } public int Property { get; set; } public string Operator { get; set; } public object Value { get; set; } public string RightBracket { get; set; } } public static class Utils { public static string SerializeToString(this object instance) { if (instance == null) throw new ArgumentNullException("instance"); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); XmlSerializer serializer = new XmlSerializer( instance.GetType(), null, new Type[0], null, null); serializer.Serialize(sw, instance); return sb.ToString(); } public static T Deserialize<T>(this XmlDocument xmlDoc) { XmlNodeReader reader = new XmlNodeReader(xmlDoc.DocumentElement); XmlSerializer serializer = new XmlSerializer(typeof(T)); object obj = serializer.Deserialize(reader); T myT = (T)obj; return myT; } } } EDIT 2 To stress the Anton answer, the second example (updated with the Groo's remarks): using System; using System.IO; using System.Text; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; namespace WindowsFormsApplication13 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { PropertyFilter filter = new PropertyFilter(); filter.AndOr = "Jora"; var obj = new Hehe(); obj.Behehe = 4526; filter.Value = obj; filter.Property = 15; var xml = filter.SerializeToString(); PropertyFilter cloneFilter = xml.Deserialize<PropertyFilter>(); Console.WriteLine("Value is = '{0}'", cloneFilter.Value); } } public class Hehe { public int Behehe { get; set; } public override string ToString() { return string.Format("behehe is '{0}'", Behehe); } } public class PropertyFilter { public string AndOr { get; set; } public string LeftBracket { get; set; } public int Property { get; set; } public string Operator { get; set; } //[XmlElement(typeof(Hehe))] public object Value { get; set; } public string RightBracket { get; set; } } public static class Utils { public static string SerializeToString(this object instance) { if (instance == null) throw new ArgumentNullException("instance"); StringBuilder sb = new StringBuilder(); XmlSerializer serializer = new XmlSerializer(instance.GetType(), null, new Type[0], null, null); using (StringWriter sw = new StringWriter(sb)) { serializer.Serialize(sw, instance); } return sb.ToString(); } public static T Deserialize<T>(this string xmlString) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader sr = new StringReader(xmlString)) { return (T)serializer.Deserialize(sr); } } } } A: Ok, that makes sense, you were using a XmlDocument for deserialization. Simply use a String (or any stream reader, like @Seb already pointed out), and it will work: public static class Utils { public static string SerializeToString(this object instance) { if (instance == null) throw new ArgumentNullException("instance"); StringBuilder sb = new StringBuilder(); XmlSerializer serializer = new XmlSerializer(instance.GetType()); using (StringWriter sw = new StringWriter(sb)) { serializer.Serialize(sw, instance); } return sb.ToString(); } public static T Deserialize<T>(this string xmlString) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader sr = new StringReader(xmlString)) { return (T)serializer.Deserialize(sr); } } } Usage: // serialize var xml = filter.SerializeToString(); // deserialize var cloneFilter = xml.Deserialize<PropertyFilter>(); [Edit] Also, as a side note: never forget to dispose objects implementing IDisposable. That's why the using constructs are added for any instantiated Stream. [Edit2] As Anton said, in this case you need to specify extra types explicitly, because XmlSerializer doesn't search for all possible types to find a matching class. A slightly better solution might be to use a XmlSerializer overload which accepts these types (so that you don't need to manually add attributes): public static T Deserialize<T>(this string xmlString) { Type[] typesToInclude = GetAllPossibleTypes(); XmlSerializer serializer = new XmlSerializer(typeof(T), typesToInclude); using (StringReader sr = new StringReader(xmlString)) { return (T)serializer.Deserialize(sr); } } This can be done once, at application startup, but you do need to provide the appropriate assembly (or several assemblies) to make sure that all possible types are covered: public static class Utils { private static readonly Type[] _typesToInclude = GetPossibleUserTypes(); private static Type[] GetPossibleUserTypes() { // this part should be changed to load types from the assembly // that contains your potential Value candidates Assembly assembly = Assembly.GetAssembly(typeof(PropertyFilter)); // get public classes only return assembly.GetTypes().Where(t => t.IsPublic && !t.IsAbstract).ToArray(); } public static string SerializeToString(this object instance) { if (instance == null) throw new ArgumentNullException("instance"); var sb = new StringBuilder(); var serializer = new XmlSerializer(instance.GetType(), _typesToInclude); using (StringWriter sw = new StringWriter(sb)) { serializer.Serialize(sw, instance); } return sb.ToString(); } public static T Deserialize<T>(this string xmlString) { var serializer = new XmlSerializer(typeof(T), _typesToInclude); using (StringReader sr = new StringReader(xmlString)) { return (T)serializer.Deserialize(sr); } } } A: Gree's solution will work as long as Value takes values of primitive, XSD-defined types like string and int, or user-defined types mentioned somewhere in T's definition (T itself, the types of its properties etc.) As soon as you need to deserialize a value of a type different from these, you must declare all possible types of Value with XmlElementAttribute, e.g. [XmlElement (typeof (string))] [XmlElement (typeof (int))] [XmlElement (typeof (MyType), Namespace = "http://example.com/schemas/my")] public object Value { get ; set ; } A: Ok, try this but I'm not sure of what you're trying to achieve. public class PropertyFilter { public string AndOr {get; set;} public string LeftBracket {get; set;} public int Property {get; set;} public string Operator {get; set;} public object Value {get; set;} public string RightBracket {get; set;} } public void MyMethod() { using (System.IO.StreamReader reader = new System.IO.StreamReader(@"Input.xml")) { System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(PropertyFilter[])); PropertyFilter[] deserialized = (PropertyFilter[])serializer.Deserialize(reader); } } I just put your sample XML in Input.xml file. I hope this will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return substring up to first digit I am trying to group rows by a field that either has the pattern [:alpha:][:digit:].* or [:alpha:][:alpha:][:digit:].* by the substring up to but excluding the digit. i.e. the returned substring will either have one letter, or two. I am thinking something along the lines of: SELECT LEFT(postcode,IF(ISDIGIT(postcode,2),1,2)) AS area, COUNT(*) AS num FROM addresses GROUP BY LEFT(postcode,IF(ISDIGIT(postcode,2),1,2)) Except of course there is no ISDIGIT() function. I was also thinking of something similar to LEFT(postcode,POSITION_REGEX("\d" IN postcode)) but obviously that doesn't exist either :-/ Database server is running MySQL 4.1.24 Upgrading to 5.0 is possible but would require downtime and hasn't been done yet as it hasn't been necessary so far. A: SELECT LEFT(postcode, IF(postcode REGEXP '^.[[:digit:]]', 1, 2)) AS area, COUNT(*) AS num FROM addresses GROUP BY area
{ "language": "en", "url": "https://stackoverflow.com/questions/7597935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: loading and handling settings in a php we bsite How would I load and handle a large amount of settings. Where I can enable and disable options. So lets say I have a table in mysql called php_settings and then I have 100's of fields that relate to the web site. How would I load them in and then assign them to an array() I guess is the bast way and then use those settings throughout my web site. I didn't want to have to load them in on every page load. So ? A: The web is stateless - unless you want to use a $_SESSION variable to hold all those config options (I wouldn't recommend it) you're going to have to load those you want to use on every page... on every page. Personally I'd create a sort of site "ini" php file containing an app config Singleton class that bootstraps everything you need to launch the site, including the starting the session, connecting to the database and loading in any config settings (many of which may come from the database). Then all you need do at the top of any new page is something like... require_once 'path/to/app.ini.php'; $oApp = App::getInstance(); You can then access your application settings through something like $oApp->config('setting'). To cut down on the load on the database you can enable caching on the database server (as the config options are unlikely to change often) or read the values from the database but instead of using them there and then serialize the response and save it to a text file (outside the web tree) - then only return to the database IF the (cached) text file isn't present or has expired; it's slightly less of a bottleneck to go to the filesystem rather than the database server. A: For example, once a minute, run a cron which will take these variables into your specified config file $result = mysql_query("SELECT * FROM php_settings"); while($one = mysql_fetch_assoc($result)){ $config[$one['name']] = $one['value']; } A: You should not load all settings at once if you're not gonna need them all. Loading and using a few hundred items in an array isn't going to be a huge performance hit, but if you only need two or three, why not query them when they're needed? A: If you are using a table for settings you can use the oops concept as follows create a file which contains following class yourclassname { public congif=array(); function __construct(Settingarray[]) { run your query here and select the appropriate fields and assign them to the class property linke following $this->congif='Your query result'; } } create the object of above class like following obj1=new yourclassname('array of setting fields you required on that page'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Determine if element is a text node using jQuery Given a jQuery element, how can I determine if the sibling on the right is a text node and not another element? In PHP, you would compare the nodeType to #text - what's the equivalent in this case? window.jQuery('body').find('a').each(function (i) { if(window.jQuery(this).next() == '?'){ } }); I am trying to work out what I can put in the condition part. Update if(window.jQuery(this).next().length != 0){ alert(window.jQuery(this).next().get(0).nodeType); if(window.jQuery(this).next().get(0).nodeType == 3){ alert('right has text'); } For some reason, all my tests keep returning a 1 rather than a 3 to indicate text nodes! A: as the comment: check this nodeType and see if helps you. A: next() only returns elements, so you can't use it to traverse text nodes. You could instead use the DOM nextSibling property and check its nodeType property: Live demo: http://jsfiddle.net/kD9qs/ Code: window.jQuery('body').find('a').each(function (i) { var nextNode = this.nextSibling; if (nextNode && nextNode.nodeType == 3) { alert("Next sibling is a text node with text " + nextNode.data); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7597943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Javascript Alert pop up not working in IOS for phonegap I have phonegap app build for android and IOS. The alert-box is working great in Android but I am not getting alert in Iphone. Please help. This piece of code works good for droid: else { navigator.notification.alert('Invalid Username or Password!'); } A: I had a problem like that, phonegap wasn't working with iOS and working with Android. In my case, that happened because the phonegap.js is different from Android's to iOS, so I had to move my www folder to iOS app and keep the iOS phonegap.js instead of using Android phonegap.js I did that by creating a "HelloWorld" iOS + Phonegap app and copying his phonegap.js to my actual app. After that, Phonegap started to work again! See ya!
{ "language": "en", "url": "https://stackoverflow.com/questions/7597947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Maven : error: generics are not supported in -source 1.3 , I am using 1.6 I have imported an existing Maven project into Eclipse IDE . I have modified some code in it , it compiled successfully , I am using Java 1.6 as compiler and when i am trying to run maven clean install -X Its giving the following error could not parse error message: (use -source 5 or higher to enable generics) D:\bayer\util\src\main\java\com\tata\bayer\util\BrokerageCalendar.java:179: error: generics are not supported in -source 1.3 private static Hashtable<String, Boolean> nyseHolidays = new Hashtable<String, Boolean>(); ^ could not parse error message: (use -source 5 or higher to enable generics) D:\bayer\util\src\main\java\com\tata\bayer\util\APIHttpXmlClient.java:27: error: generics are not supported in -source 1.3 Class<? extends APIResponse> responseClass) { ^ Please suggest any ideas as how to resolve this ?? A: You have to configure the Maven Compiler Plugin. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> A: Did you declare that you want to use java 1.6 in your project pom.xml?: <build> <pluginManagement> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument></compilerArgument> </configuration> </plugin> </plugins> </pluginManagement> </build> A: Another way that doesn't involve modifying the pom is to specify the source and target in the command line: mvn clean install -Dmaven.compiler.source=1.6 -Dmaven.compiler.target=1.6 Note that this should be avoided generally as the build cannot be guaranteed to be repeatable this way. A: Configuring the Maven Compiler Plugin will fix the problem. It turns out the problem was caused by the Maven3 package in the Ubuntu repository. An alternate fix is to download Maven 3 from the Apache website which uses a more up to date Compiler plugin. I wanted to know why this was happening when the documentation states the default Java source is 1.5. To see what mvn is using for your compiler plugin use: mvn help:effective-pom My Maven Compiler Plugin was 2.0.2 even though I was using Maven 3.0.4 from the Ubuntu packages. When I run the same command using Maven 3.0.4 from Apache I have a plugin version 2.3.2, which defaults to Java 1.5 as expected. A: I'd prefer this: <properties> <maven.compiler.source>1.5</maven.compiler.source> <maven.compiler.target>1.5</maven.compiler.target> ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7597950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: windows command config file? I'm running a few different windows command scripts that all reference the same directory. The directory I want to reference changes from day to day depending on what I'm working on. I've looked into taking command line args, but I think the more elegant solution would be to have all the scripts reference some sort of config file, if such a thing is possible. Then I could change the directory address one place to change all of my standard command scripts. If it's not abundantly clear, I'm new to windows scripting. Q: Is there a way to retrieve data from an external config in a windows command script? PS - Don't be limited by my question, if you think you have a better solution for what I'm trying to do, I'm all ears. A: The simplest thing would be to use an environment variable. eg: set my_path=c:\foo\bar then in the script you can use %my_path% and it will be expanded for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When and how reliably are MVC filters called? I want to setup some 'stuff' at the start of a controller action, and tear it down after a page has been rendered. I've achieved this by overriding the 'OnActionExecuting' and 'OnResultExecuted' filters (I'm using MVC 2). The big question I have at the moment is, how reliably are these two filters called? If the answer to that isn't 100% of the time, I reckon the easiest way to progress this, would be to use some custom filters (specifying the order of them to 'first' and 'last'... A: 100% of the time. Its part of the MVC pipeline. If they didn't it would be a pretty big security hole with the AuthorizeAttribute. A: If you need absolute reliability you might want to implement a clean up filter as an IExceptionFilter and have it run the same clean up code as your OnResultExecuted override does (after checking first that it hasn't already been done). Depending on what kind of "clean up" is needed, you might be able to simply use the HandleErrorAttribute, which I believe still allows OnResultExecuted to be run as it simply replaces the result with an ViewResult of the Error view. A: If the built-in filters are not called relieably, why would your custom filters be any better? The great thing about code is that, if you understand it, it tends to do exactly the same thing every time if given the same inputs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xml loaded dataset is missing a table When I read an xml file into a dataset, if the root node has more than one of each child tag, it doesn't create a table for the root node. Why is this? Is there any way to get it to generate the root table without modifying the xml? static void Main(string[] args) { var ds =Load(@"<root> <Stores>Lambton Quay</Stores> <Stores>Willis Street</Stores> </root>"); var ds2 = Load(@"<root> <t>1</t> <Stores>Lambton Quay</Stores> <Stores>Willis Street</Stores> </root>"); Console.WriteLine("ds table count: {0}", ds.Tables.Count); //1 <- expecting 2 Console.WriteLine("ds2 table count: {0}", ds2.Tables.Count); //2 Console.ReadKey(); } static DataSet Load(string xml) { var xd = new XmlDocument(); xd.LoadXml(xml); var ds = new DataSet(); ds.ReadXml(new XmlNodeReader(xd)); return ds; } Edit: To be clear I want to know why the DataSet ds doesn't have a root table while ds2 does. Someone made the decisions: * *if only 1 node exists with a given tag name under a given parent tag, it becomes a column in the table named by the parent tag. *if more than one such node exists, it becomes a table on its own *if all child nodes appear more than once and the parent node is the document root, the parent table does not get created What is the reason for #3? A: The first XML example doesn't create a "root" table in the dataset because there would be no rows or columns created in a table with that name. In the second example, try adding a second <t> element. You will still get two tables but they will be named "t" and "Stores" (instead of "root" and "Stores"). Another test is to add another different element to the second example (say <r>1</r>). In this case you will still have two tables "root" and "Stores" but now the "root" table will have 1 row with 2 columns (column "r" and column "t"). When the parser sees two elements with the same name it will create a table for that element and each instance of the element will be a new row in the table. When the parser sees multiple single elements under a node, it will create a table using the name of the parent node as the table name and each single element under the parent node will be a column in the table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android, event listener? I have a loop that runs through an array of image views, adding an event listener to each, how can I find out which image view was pressed inside the listener? imageViewArray[i].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { } }); A: Doesn't the v parameter to the onClick method provide a reference to the ImageView? EDIT The thing is: You are not adding the same listener to all of the ImageViews in your code - every ImageView in your array gets its own listener. In the listener's onClick method, the View that raised the event is passed in v, so when working with v you're working with the clicked ImageView. To find the index of the ImageView in your array, you might as well set the ID as suggested by others and then use v.getId(), or you could loop over your array and check whether imageViewArray[i] == v, in which case i is the index of your ImageView within the array. A: set id for each on the index value like eg: image_view.setId(i); A: imageView.getId() will return you the ID you give this ImageView in findViewById() method. Then you can check the ID's in a switch block. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSF2.0, how commandButton knows which bean to send this I am starting in JSF2, comming from spring mvc, so I have some doubts that I cannot find answers on Core JavaServer Faces v3 Like this one... How can the tag h:commandButton know which bean I am talking about ? I can only have one Bean per JSF page, is that it ? I am only giving it a msg.next which is a text from a i18n file.(quizbean is my bean) <h:body> <h:form> <h3>#{msgs.heading}</h3> <p> <h:outputFormat value="#{msgs.currentScore}"> <f:param value="#{quizBean.score}"/> </h:outputFormat> </p> <p>#{msgs.guessNext}</p> <p>#{quizBean.current.sequence}</p> <p> #{msgs.answer} <h:inputText value="#{quizBean.answer}"/> </p> <p><h:commandButton value="#{msgs.next}"/></p> </h:form> A: The bean has to be managed by JSF, then it will know which bean you are talking about. e.g. <f:param value="#{quizBean.score}"/> Here, the bean quizBean is a Managed-Bean, managed by JSF. And to make it a managed bean you to tell JSF about it by either using annotations as follows - @ManagedBean(name="quizBean") //name is optional or you give your own name to the bean @SessionScoped //tell JSF in which scope you want to keep your managedbean public class QuizBean { //.... Or by mentioning it as follows in the JSF configuration file (faces-config.xml) - <managed-bean> <managed-bean-name>quizBean</managed-bean-name> <managed-bean-class>com.pkg.QuizBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> //Older versions of JSF requires this where annotations do not work //But if you are using JSF 2.0 then it's a lot better to use annotations You can use more than one beans in a view (page). A: The command button does not need to know this. All it generates is a HTML <input type="submit"> element. This is embedded in a HTML <form> with an action URL pointing to the same URL as the page. There's further also the <input type="hidden" name="javax.faces.ViewState">. Thanks to this field, JSF knows exactly what view you're submitting to. This view holds information about all inputs. This view knows that there's an <h:inputText value="#{quizBean.answer}" />. The view knows the field name of the generated HTML <input type="text"> element. JSF will get the submitted request parameter value by request.getParameter() using this name and then update the answer property of the current instance of quizBean with this value. Rightclick the page in your browser and choose View Source to see the JSF-generated HTML output. Put a breakpoint on ApplyRequestValuesPhase#execute() and HtmlBasicRenderer#decode() methods (assuming that you're using Mojarra not MyFaces) to track the gathering of submitted values for every UIComponent in the view. A: If this is an example from Core Java Server Faces, then read more carefully, it explains everything. msgs as far as I remember, refers to message bundle, declared in faces-config.xml. As for your question how commandButton knows which bean to call. In your example, the class name QuizBean, most likely correspond to the bean with the same name. That's enough for JSF 2.0. However, you could change that name by 2 methods: 1) If you use JSF managed beans, you should go like this: @ManagedBean(name="quiz") @ViewScoped public class QuizBean { } 2) If you use CDI-beans you would do this: @Named("quiz") @RequestScoped public class QuizBean {} Remember that CDI-beans scope annotations come from package javax.enterprise.context. And JSF scopes are in the javax.faces.bean package. Do not mix them! Update: Please refer to page 35 of the book Core Java Server Faces 3rd Edition for more details about your question and do not hurry to ask questions if you don't understand something right away.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Explanation of Base Class (Flash) and inheritance I have a MovieClip called PopUp where I wrote some code. I need to make another MovieClip that uses pretty much the same code...can I just use the PopUp class as the base class for my other MovieClip? They look different but they have the same instances on the stage and stuff. A: You can just create a new class called PopUpBase, and let your new MC's extend that class. Generally changing the base class in the IDE can cause some problems, so it's best practice not to, but to create classes (and .as files) for each MC that needs code. Depending on what you're doing with this, it might be okay just to change the base classes to PopUpBase (in the IDE) :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7597980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: i looking for how make a refresh of tableView in pulling down? if anyone can help me for make that (pull down to refresh): source: http://cdn.iphone4jailbreak.org/wp-content/uploads/pull-to-refresh-jailbreak-app-iphone-4.jpg A: There are several resources to do that: * *EGOTableViewPullRefresh - An open source project hosted on GitHub. *This tutorial from CocoaNetics. *Included in the three20 library A: You can take all needful source codes here: EGOTableViewPullRefresh A: You can subclass TTTableViewController and then delegate it to TTTableViewDragRefreshDelegate. - (id<TTTableViewDelegate>) createDelegate { TTTableViewDragRefreshDelegate *delegate = [[TTTableViewDragRefreshDelegate alloc] initWithController:self]; return [delegate autorelease]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why binary search not find my string? I have an ordered txt file like this: aaa bbb ccc ddd eee I want to check if "ddd" string exists in the file... Here my func: - (BOOL) asd:(NSString*)sting { NSArray *LinesCount = [[NSString stringWithContentsOfFile:@"longfile.txt" encoding:NSStringEncodingConversionAllowLossy error:nil] componentsSeparatedByString:@"\r\n"]; unsigned index = (unsigned)CFArrayBSearchValues( (CFArrayRef)LinesCount, CFRangeMake(0, CFArrayGetCount((CFArrayRef)LinesCount)), (CFStringRef)string, (CFComparatorFunction)CFStringCompare, NULL); if (index < [LinesCount count]) return YES; return NO; } Why does it always returns NO, with any string? A: The problem is in the way you read in the array. If you replace the code that assigns LineCount with NSArray * LinesCount = [NSArray arrayWithObjects:@"aaa", @"bbb", @"ccc", @"ddd", @"eee", nil]; you will see the binary search performs fine. There are two issues in your code: * *Line separator is probably just "\n" if the file has been created on Mac OS X *Your array will contain a left over "" as it's last element hence the requirement for ordering as required by CFArrayBSearchValues is no longer satisfied. As an example: NSLog(@"%@", [@"one\ntwo\n" componentsSeparatedByString:@"\n"]); yields (note the last empty element): 2011-09-29 16:52:33.024 a.out[4019:707] ( one, two, "" )
{ "language": "en", "url": "https://stackoverflow.com/questions/7597984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get links that are AJAXy to replace the content inside an iFrame? So, I added to my AJAX links the name of the iframe, target="name", but I think I might be erroring on the replacing part... page.replace_html("section-content",:partial=>"/path/contents/edit",:object=>@content) yeah, it's RoR, but that's not important... I think my selector isn't being found because that div is now in an iframe. How to I select elements in an iframe? I've tried window.frames['name'].document but I just get a document object that seems to have no methods. A: window.frames['name'].contentDocument.document Note: You must obey the same-origin policy. For IE7 and lower, use: window.frames['name'].contentWindow.document P.S., you can use document.getElementById('id') instead of window.frames['name']
{ "language": "en", "url": "https://stackoverflow.com/questions/7597987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 16 bit asm instruction set What set of instructions is used in COM files? I assumed it was 8086, but it seems that I was wrong. In a 8086 manual I found, shl can only accept 1 or cl for its second argument, while immediate values other than 1 work fine for me. In case it matters, I'm using NASM. Thanks for your time. A: A true COM (I won't get into COMs that are actually EXEs, etc) just means it's a simple DOS executable. Whatever instruction set is supported is available. I used to do DOS programming (both COM and EXE) on 8088 up through i486 back in the day, and whatever instructions are legal in that mode, you can use. For example, I often used 32-bit string instructions and immediate pushes when my target was "16-bit" (technically should be called "real mode") DOS. A: There are two main types of COM files. One was designed to run in MS-DOS, the other was designed to run in the CP/M OS. As far as I know, the DOS COM files should be x86 based. CP/M COM files could potentially be 8085, 8080, or Z80 instructions according to Wikipedia. As another answer mentioned, COM is just a simple executable format, and can use any supported underlying instruction set. In terms of the SHL instruction, it seems that modern x86 hardware (perhaps x64) supports using an immediate value for this instruction. I couldn't find reference to it when looking just at 8086 docs, though, so it must have been added at some point. Here's a couple of references which go into some detail on this instruction: http://siyobik.info/main/reference/instruction/SAL%2FSAR%2FSHL%2FSHR http://ref.x86asm.net/coder32.html A: This is one of those funny questions and as always the answers are misleading. a true DOS COM file has no headers and has to fit inside a single segment of memory, because it had no relocation information, DOS had to put the file where it needed, and so the only true way of being compatible (with x86) was to use 8086 compatible assembly. Edit: To clarify the above, this is because the 8086 didn't have memory pages. You could certainly compile in 286/386 operands in, as once the program is running, there's no executive runtime in DOS to stop you and say 'no you can't do that, it's a 386 instruction'. Which, funnily enough, is part of the reason why COM files don't work very often in Windows7 x32 or at all in Windows7 x64. Because of way DOS worked, command.com was unloaded when you execute your .com file, and reloaded afterwards, so essentially your .com file could access all memory of the system, and in theory use DOS memory extenders like Phar lap's DOS/4GW and CWSDPMI come to mind. Long story short; you could use any sort of commands that the current system could support, but you should only use 16-bit x86 compatible commands to be sure. If the above sounds like a PITA, it's because it was, I remember :) It's also why the .EXE format got very popular very quickly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Making Selection & Adding tag dynamically in JavaScript I need some help about JavaScript on iPhone UIWebView; I have HTML like below: <html> <head> <title>Example</title> </head> <body> <span>this example for selection <b>from</b> UIWebView</span> </body> </html> I want to make a selection, and add <span> tag with color to the selected text in HTML to write a note just like an e-book reader. This is my JavaScript code to get the selected text: NSString *SelectedString = [NSString stringWithFormat:@"function getSelText()" "{" "var txt = '';" " if (window.getSelection)" "{" "txt = window.getSelection();" " }" "else if (document.getSelection)" "{" "txt = document.getSelection();" "}" "else if (document.selection)" "{" "txt = document.selection.createRange().text;" "}" "else return;" "alert(txt);" "}getSelText();"]; [webView stringByEvaluatingJavaScriptFromString:SelectedString]; This works good, and returns me the selected text. Also this JS code for adding a new tag: NSString *AddSpanTag = [NSString stringWithFormat:@"function selHTML() {" "if (window.ActiveXObject) {" "var c = document.selection.createRange();" "return c.htmlText;" "}" "var nNd = document.createElement(\"span\");" "var divIdName = \'myelementid\';" "var ColorAttr = \"background-color: #ffffcc\";" "nNd.setAttribute(\'id\',divIdName);" "nNd.setAttribute(\'style\',ColorAttr);" "var w = getSelection().getRangeAt(0);" "w.surroundContents(nNd);" "return nNd.innerHTML;" "}selHTML();"]; [webView stringByEvaluatingJavaScriptFromString:AddSpanTag]; My problem is so: if I select "example" (look at the HTML text) text from WebView, it works, because it doesn't contain any tag. But if I select "selection from" (look at the HTML text) text from WebView, it's not working, because it starts the tag of <b>, and </b> is out of my selection, then I can't add a new tag between <b> and </b>. How can I solve this problem? A: Since this is a UIWebView, this is Mobile Safari and you can lose a lot of those branches for obtaining the selection. I would suggest using document.execCommand() with the "HiliteColor" command, which is built into the browser and works on the whole selection even when it crosses element boundaries: var sel = window.getSelection(); if (!sel.isCollapsed) { var selRange = sel.getRangeAt(0); document.designMode = "on"; sel.removeAllRanges(); sel.addRange(selRange); document.execCommand("HiliteColor", false, "#ffffcc"); sel.removeAllRanges(); document.designMode = "off"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to determine + key down? Using jQuery, how do I determine that user has pressed '+'. I know that by matching keycode in the keydown event is the way to go, but that is apparently not cross platform. Since, the keycodes vary in Linux OS. Matching to charcode is also not an option because it is not cross browser. IE, of course, does not support charcode. Does anyone know a cross platform solution to do this? Google+ has apparently been able to achieve this. A: $("#element").keyup(function(e){ if (e.keyCode == 61 || e.keyCode == 107){ // 61 for windows, 107 for mac //do stuff } } or, if you feel this isn't reliable, use if ($.firefox){ var keycode = ..; } if ($.opera){ var keycode = ..; } // and more where you have to change .. with certain keycode working in that browser
{ "language": "en", "url": "https://stackoverflow.com/questions/7597993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange (for me) declaration of function What that declaration means in C ? void help_me (char *, char *); I'm newbie, but I know about pointers. Seems like this is something different ? A: This declaration says that help_me is a function taking two pointers to char (for example, two strings). For a function prototype declaration the variable names are optional: void help_me (char *, char *); and void help_me (char * foo, char * bar); are equivalent. A: It's a prototype for a function. It doesn't give the argument names because it isn't strictly require in a prototype. Here it is declaring that there exists a function, help_me that takes 2 arguments both of type char * and returns nothing. A: It's a prototype, and in a prototype only the type of arguments are needed, i..e you don't need to state something like: void help_me (char* a_char, char* another_char);
{ "language": "en", "url": "https://stackoverflow.com/questions/7597994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL return max value from child for each parent row I have 2 tables - 1 with parent records, 1 with child records. For each parent record, I'm trying to return a single child record with the MAX(SalesPriceEach). Additionally I'd like to only return a value when there is more than 1 child record. parent - SalesTransactions table: +-------------------+---------+ |SalesTransaction_ID| text | +-------------------+---------+ | 1 | Blah | | 2 | Blah2 | | 3 | Blah3 | +-------------------+---------+ child - SalesTransactionLines table +--+-------------------+---------+--------------+ |id|SalesTransaction_ID|StockCode|SalesPriceEach| +--+-------------------+---------+--------------+ | 1| 1 | 123 | 99 | | 2| 1 | 35 | 50 | | 3| 2 | 15 | 75 | +--+-------------------+---------+--------------+ desired results +-------------------+---------+--------------+ |SalesTransaction_ID|StockCode|SalesPriceEach| +-------------------+---------+--------------+ | 1 | 123 | 99 | | 2 | 15 | 75 | +-------------------+---------+--------------+ I found a very similar question here, and based my query on the answer but am not seeing the results I expect. WITH max_feature AS ( SELECT c.StockCode, c.SalesTransaction_ID, MAX(c.SalesPriceEach) as feature FROM SalesTransactionLines c GROUP BY c.StockCode, c.SalesTransaction_ID) SELECT p.SalesTransaction_ID, mf.StockCode, mf.feature FROM SalesTransactions p LEFT JOIN max_feature mf ON mf.SalesTransaction_ID = p.SalesTransaction_ID The results from this query are returning multiple rows for each parent, and not even the highest value first! A: select stl.SalesTransaction_ID, stl.StockCode, ss.MaxSalesPriceEach from SalesTransactionLines stl inner join ( select stl2.SalesTransaction_ID, max(stl2.SalesPriceEach) MaxSalesPriceEach from SalesTransactionLines stl2 group by stl2.SalesTransaction_ID having count(*) > 1 ) ss on (ss.SalesTransaction_ID = stl.SalesTransaction_ID and ss.MaxSalesPriceEach = stl.SalesPriceEach) OR, alternatively: SELECT stl1.* FROM SalesTransactionLines AS stl1 LEFT OUTER JOIN SalesTransactionLines AS stl2 ON (stl1.SalesTransaction_ID = stl2.SalesTransaction_ID AND stl1.SalesPriceEach < stl2.SalesPriceEach) WHERE stl2.SalesPriceEach IS NULL; A: I know I'm a year late to this party but I always prefer using Row_Number in these situations. It solves the problem when there are two rows that meet your Max criteria and makes sure that only one row is returned: with z as ( select st.SalesTransaction_ID ,row=ROW_NUMBER() OVER(PARTITION BY st.SalesTransaction_ID ORDER BY stl.SalesPriceEach DESC) ,stl.StockCode ,stl.SalesPriceEach from SalesTransactions st inner join SalesTransactionLines stl on stl.SalesTransaction_ID = st.SalesTransaction_ID ) select * from z where row = 1 A: SELECT SalesTransactions.SalesTransaction_ID, SalesTransactionLines.StockCode, MAX(SalesTransactionLines.SalesPriceEach) FROM SalesTransactions RIGHT JOIN SalesTransactionLines ON SalesTransactions.SalesTransaction_ID = SalesTransactionLines.SalesTransaction_ID GROUP BY SalesTransactions.SalesTransaction_ID, alesTransactionLines.StockCode; A: select a.SalesTransaction_ID, a.StockCode, a.SalesPriceEach from SalesTransacions as a inner join (select SalesTransaction_ID, MAX(SalesPriceEach) as SalesPriceEach from SalesTransactionLines group by SalesTransaction_ID) as b on a.SalesTransaction_ID = b.SalesTransaction_ID and a.SalesPriceEach = b.SalesPriceEach subquery returns table with trans ids and their maximums so just join it with transactions table itself by those 2 values
{ "language": "en", "url": "https://stackoverflow.com/questions/7597995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the complete structure of the browser object in QTP? I know this might be a very basic question but I've recently started using QTP and am still picking up a few things. For the last couple of hours I've been searching for an answer to this but no luck so far. My question: In QTP code we usually write: Browser("x").Page("y").Navigate("url") I want to understand where this Browser object is coming from and what exactly are x and y. 1) Is it part of VBScript or is it part of QTP? 2) Also, where can I get complete details about this object structure? I would like to know what else I can write besides "page" and besides "navigate". A: The Browser test object represents a single tab in a tabbed browser. When calling the Browser function QTP returns a test object, usually this is the Browser with that name from an associated object repository (as with your "x" example) but it may use descriptive programming to create a new test object. When calling a subelement of the Browser you have two options (as with all test objects) * *Call a method of the test object. The list of methods supported by the test object can be found in QTP's documentation. *A child of the test object from the object repository (or descriptive programming). This is the case in your sample. The children of Browser are almost always Page but Window or other objects can appear (depending on the application you're testing). The Page test object represents the top level HTML document displayed in the Browser. BTW, The code snippet you wrote is wrong. Page does not support the Navigate method, Browser does. A: In your example, "x" and "y" refer to the logical name in the Object Repository. So to answer question #1, this is part of QTP, not VBScript. The Object Repository is a go-between which maps logical names in your VBScript code from the actual details of identifying an object at runtime. It's just an abstraction. In general, I suggest getting some formal training on the tool. Training will answer most of your questions regarding this sort of thing. There are also numerous tutorials on the web as well. Lastly, the help guide will walk you through a lot of the basics. A: Actually, the Browser object represents a collection of all browser windows and tabs that are currently open. You specify a specific one by name or description like this: Browser("website") where "website" is either a named "browser object" in the object repository, or alternately, a description (string or object) that describes a specific window/tab that you want to work with. The Page object represents a collection of all possible pages that the above mentioned browser might have loaded. Instances in the collection correspond to named "Page objects" in the object repository. You specify a specific one by name or description like this: Browser("website").Page("Logon Page") This concept can be very confusing, especially considering the fact that any given actual browser window/tab can only have ONE actual Page loaded at any given moment. In other words, if you iterate over the realtime child objects of Browser("website"), there will always be only one. The best way to think of this Browser/Page relationship is to use the right metaphor. When I first started programming with QTP, I thought it was best to think of the browser object as either IE, Chrome, Firefox, etc, and I tried to manage my object repository objects that way, and it made a huge mess. I now understand that the best way to organize browser objects in the Object repository is this way: Think of a browser object in the repository as a single website object. Amazon.Com MSN.Com StackOverflow.Com LifeHacker.Com etc etc. Think of a page object in the repository as a single clearly unique page of the website object. For each different page the website might display (with different controls on it), you should create a separate Page object under the browser object. Your repository might look something like this: Amazon.com Login Page Music Page Books Page Checkout Page StackOverFlow.Com Login Page username field password field Questions Page Jobs Page Tags Page Users Page Badges page etc etc... The idea here is to create logical pages to contain the control objects that occur only on those pages. Now for the tricky stuff... In order to make this work, we have to make sure the browser and page objects actually "exist" when they should. For a browser object, it should "exist" whenever ANY of it's pages are loaded in any browser tab. For a page object, it should "exist" only when that page of that website is loaded, and it's specific controls are on the screen. This means we need to carefully edit the identification properties for browser objects such that no matter which page of the website is currently loaded, it will always properly identify the website as that browser object. Here's an example... At my work, I have a website called "Trade". The browser can ususally reliably be found with "name:=Trade"... but the login page is a little different - it's name is "Welcome to Trade"... so to make the website object work, I use a Regular Expression in the identification properties like this: "name:=(?:Welcome to Trade|Trade)". This way, the same browser objects says that it "exists" when either name is found. In this way, I can contain the login page as part of the whole website object instead of having to clutter up the object repository with a browser object that only contains a login page. which makes reading the code later more annoying, and complicates use of WITH blocks) Another problem is that Page objects are often difficult to tell apart. The URL's that they are loaded with can be dynamic, and the page titles might not change from one page to another at all. To resolve this, I ADD additional identification properties to my page objects in the object repository... For example, I might manually add the URL property, and then use a regex to watch for a specific tag within the URL like this: "URL:=https://TradeTools-(?:SIT|UAT).*userLogin.*" This would be in addition to the mandatory title property (never remove a mandatory property, or the recording engine will fail to record properly) So, to more directly answer this question... * *Browser and Page objects are part of QTP. QTP is providing this API to you, and you (touch it/use it/manipulate it) using VBScript. The Browser and Page classes to not exist outside of QTP. *You can get the complete list of methods and properties available for the browser and page objects in the QTP/UFT help files. Also, you can read this: http://community.hpe.com/t5/All-About-the-Apps/Understanding-the-web-test-object-model-in-HP-Unified-Functional/ba-p/6168133#.Vvp0V-IrK03 I hope this helps. Once I switched my understanding of browsers/pages to the metaphor I've described here, it has greatly increased my capabilities with QTP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linq - Query a query result agains a list of strings I have a list of strings List<string> firstNames = new List<string>(); I have a query result var contacts = (from p in datacontext.Contact) How Can I Query the original result (contacts) against the list of strings? select * from contacts where contacts.firstname like firstNames something like firstNames.Any(x=>x.contacts.Contains(x)) A: You should probably push the first names into the database query, like this: var contacts = dataContext.Contacts.Where(c => firstNames.Contains(c.FirstName)); Now you used "like" in your sample query, so maybe you want: var contacts = dataContext.Contacts .Where(c => firstNames.Any(f => c.FirstName.Contains(f))); If you could provide some concrete examples it would help. EDIT: If you're really pulling back all the contacts from the database already into (say) a List<Contact> contacts, then you could use: var matchingContacts = from contact in contacts join name in firstNames on contact.FirstName equals name select contact; A: First, visit this link, download the class and add it to your App_Code folder: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx Then be sure to add "using System.Linq.Dynamic;" Then construct your query like this: DatabaseDataContext db = new DatabaseDataContext(); List<string> firstNames = new List<string>(); //--- loop through names and build a where query string WhereClause = string.Empty; for (int i = 0; i < firstNames.Count(); i++) { string s = firstNames[i].ToLower(); if (i != Communities.Length - 1) WhereClause += "FirstName.ToLower().Contains(\"" + s + "\") OR "; //--- first name is the field name in the db else WhereClause += "FirstName.ToLower().Contains(\"" + s + "\")"; } //--- execute query and pass the dynamic where clause IQueryable contacts = db.Contacts .Where(WhereClause) .OrderBy("FirstName"); Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7598011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CodeIgniter: Preventing row_array() vs row() typo's? Twice now I've mistakenly used row() instead of row_array() when fetching a single row result. Usually, it goes unchecked without any warning messages. 15-30 minutes later I finally notice the issue; doh doh! Does anyone have any good suggestions as to ways to prevent this mistake. The object format doesn't throw a PHP warning, but - of course - the code doesn't work when you expect an array from a model method. I accidentally used: if ($query->num_rows() > 0) { return $query->row(); } Which should instead be: if ($query->num_rows() > 0) { return $query->row_array(); } I thought about overriding the row() database method and adding in a log_message() statement that would at least let me know (on debug level) that I'm using the object format, instead of the much more typical (for my code) format. A: How do you avoid making data-type errors in your CodeIgniter model methods? Simple, declare your methods' return data type. // returns null or an object public function getFlatObject(int $id): ?object { return $this->db->get_where("your_table", ['id' => $id])->row(); } // unconditionally returns an array public function getFlatArray(int $id): array { return $this->db->get_where("your_table", ['id' => $id])->row_array(); } If your return data does not match the declared type(s) (after :), then php is going to generate errors for you. Let's take this opportunity to clear up any confusion... * *If you call either row() or row_array() and your sql logic affords the possibility of more than one row of data -- then you are only going to get the first row of the result set. *If you call row() but there are no rows in the result set, you will have a return value of null. *If you call row_array() but there are no rows in the result set, you will receive an empty array as the return value. *Hence, row() may return an iterable or non-iterable data type; whereas row_array() can ALWAYS be safely passed directly into an iterator (like foreach() or array_map()) -- it just might not having anything to iterate. A: row() returns object type, and row_array() returns array. So it is better in parsing the data of row data in DB when using row_array. A: The only way to "prevent" is pretty much learn over the documentation again so you can keep a common habit of using which function. You can note yourself, if you are going to return multiple records, use the row_array(), for a singular record, use the row() function. Remember, don't speed type your code, proofread your code step by step before continuing. Overriding the original function is bad practice, using the row() function is useful when retrieving a singular record, so don't do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passenger is listing all files instead of running my Rails application I'm trying to add the Rails application to the a directory of another application and for some reason the rails application is not rendering Here's a link to my application Here's VHOST <VirtualHost 184.106.111.142:80> ServerAdmin joe@joe.com ServerName transprintusa.com/design # ServerAlias DocumentRoot /srv/www/www.transprintusa.com/design/design.transprintusa.com/current/public ErrorLog /srv/www/design.transprintusa.com/logs/error.log RailsEnv production <Directory "/srv/www/www.transprintusa.com/design/design.transprintusa.com/current/public"> Order allow,deny Allow from all </Directory> </VirtualHost> but the Rails application is showing all the files. Passenger and everything is installed on this server because the Rails site was at design.transprintusa.com. Any ideas on what I'm doing wrong? If there is anything I can give to help anyone help me UPDATE - Here is my new VHOST and still displays the rails files <VirtualHost 184.106.111.142:80> ServerAdmin jom@jom.com ServerName transprintusa.com ServerAlias www.transprintusa.com DocumentRoot /srv/www/www.transprintusa.com/ ErrorLog /srv/www/www.transprintusa.com/logs/error.log CustomLog /srv/www/www.transprintusa.com/logs/access.log combined <Directory "/srv/www/www.transprintusa.com/"> AllowOverride all Options -MultiViews </Directory> RailsBaseURI /rails <Directory /srv/www/www.transprintusa.com/design> Options -MultiViews </Directory> </VirtualHost> A: It doesn't work in this way. The ServerName must be a hostname. You must set ServerName transprintusa.com, then use the Location or Directory directive to enable passenger when the request matches given location. See Deploying to a sub URI from the Passenger documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django flush vs sqlclear & syncdb Can anyone tell if there is a difference between >manage.py flush # or reset and >manage.py sqlclear appname | python manage.py dbshell >manage.py syncdb A: Official docs for flush and sqlclear Flush carries out the SQL Drops on the entire db, sqlflush only prints out the SQL that flush would actual run (again on the entire db). sqlclear prints out SQL Drops for a particular app or apps. Both flush and sqlflush/dbshell/syncdb will install fixtures. A: flush will truncate (delete data) sqlclear will drop (delete table, thus data too) => if you have structural modifications in your db, you have to do sqlclear (but better use south) Update: South has been deprecated. From Django 1.7 upwards, migrations are built into the core of Django. If you are running a previous version, you can use South.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Create Custom Search Bar I would like to add a search bar to my activity that should look like this: My Layout.xml looks like this: <?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"> <LinearLayout android:orientation="horizontal" style="@android:style/ButtonBar" android:id="@+id/header" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true"> <EditText android:id="@+id/ean" android:layout_width="100dp" android:layout_height="fill_parent" android:layout_weight="1.5"/> <Button android:id="@+id/search" android:layout_width="0.0dip" android:layout_height="fill_parent" android:text="@string/Search" android:layout_weight="1.0" /> </LinearLayout> <LinearLayout android:orientation="horizontal" style="@android:style/ButtonBar" android:id="@+id/footer" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true"> <Button android:id="@+id/cancel" android:layout_width="0.0dip" android:layout_height="fill_parent" android:text="@string/cancel" android:layout_weight="1.0" /> <Button android:id="@+id/light" android:layout_width="0.0dip" android:layout_height="fill_parent" android:text="@string/light" android:layout_weight="1.0" /> </LinearLayout> The Graphical Layout looks like this: How can i style my layout that it looks like in the image above? A: I'd try and replace the Button by an ImageButton. Then I'd create 9patch images for both the button and the text box and assign them using a style. A: is just nothing. just design your theme in xml layout file with that particulate background and add one editText and button as per your design and access that by activity. comment me if need further help. thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7598025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IOS: index page of a scrollview with infinite paging I have this code: it's for 3 scroll view to have a random paging CGRect frame = scrollView.frame; CGRect frame1 = scrollView1.frame; CGRect frame2 = scrollView2.frame; frame.origin.x = frame.size.width * (arc4random() % (arrayimage.count )); frame.origin.y = 0; frame1.origin.x = frame.size.width * (arc4random() % (arrayimage.count )); frame1.origin.y = 0; frame2.origin.x = frame.size.width * (arc4random() % (arrayimage.count )); frame2.origin.y = 0; int pageFirst = scrollView.contentOffset.x/scrollView.frame.size.width; int pageSecond = scrollView1.contentOffset.x/scrollView1.frame.size.width; int pageThird = scrollView2.contentOffset.x/scrollView2.frame.size.width; my problem is that when I launch my app nslog values for pageFisrt, pageSecond and PageThird is ever equal but paging is random and different; how can I have the correct value of pagefirst, pageSecond and pageThird? A: You are setting the frame of your 3 scroll views which will position the 3 scrollViews at random places in their superview - this does not affect the contentOffset. It looks as though what you meant to do was scrollView.contentOffset = (CGPoint){scrollView.bounds.size.width * (arc4random() % (arrayimage.count )), 0};
{ "language": "en", "url": "https://stackoverflow.com/questions/7598030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET MVC3 Multilingual webpage Javascripts not working on changing culture name In my multilingual website, Javascripts in all the pages are not working when i am changing the culture name in the web.config file. (using <globalization culture="" uiCulture=""/>) The javascript is not working for the below mentioned cultures * *be-by{Belarus) *ro-ro(Romania) *bg-bg(Bulgaria) *sv-se(Sweden) *th-th(Thailand) *lv-lv(Latvia) Whereas it works for spanish cultures (like es-mx,es-pa),english cultures and a few other cultures(like hu-hu(hungary)) Javascript in my website is used for popup windows and asynchronous call for cascading dropdowns. Its noteworthy that i am using culture specific resource files for translating the website into their specific languages. EDIT: Jquery pop up code - $("#dialog").dialog("open"); $("#Product_BookingEndDate").val($("#Product_BookingEndDate").val().split(' ')[0]); $("#Product_BookingStartDate").val($("#Product_BookingStartDate").val().split(' ')[0]); $("#Product_StartDate").val($("#Product_StartDate").val().split(' ')[0]); $("#Product_EndDate").val($("#Product_EndDate").val().split(' ')[0]); this opens pop up window and removes the time portion from datetime value in en-us culture but not in above mentioned cultures. Culture settings are specified in web.config, e.g <globalization culture="tr-tr" uiCulture="tr-tr"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7598033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom Component using JSF I want to create my own tag, but it doesn't work Component: package com; import javax.faces.component.UIOutput; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import java.io.IOException; public class Printer extends UIOutput { private String label; public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } @Override public Object saveState(FacesContext context) { Object values[] = new Object[2]; values[0] = super.saveState(context); values[1] = label; return ((Object) (values)); } @Override public void restoreState(FacesContext context, Object state) { Object values[] = (Object[]) state; super.restoreState(context, values[0]); label = (String) values[1]; } public void encodeBegin(FacesContext context) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("label", this); writer.write(label); writer.endElement("label"); writer.flush(); } public String getFamily() { return "printer"; } public void encodeEnd(FacesContext context) throws IOException { return; } public void decode(FacesContext context) { return; } } Tag package com; import javax.faces.component.UIComponent; import javax.faces.webapp.UIComponentELTag; public class PrinterTag extends UIComponentELTag { private String label; public PrinterTag() { int i = 10; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } @Override public String getComponentType() { return "printer"; } @Override public String getRendererType() { return null; } protected void setProperties(UIComponent component) { super.setProperties(component); ((Printer) component).setLabel(label); } } web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <context-param> <description> </description> <param-name>javax.faces.CONFIG_FILES</param-name> <param-value> /WEB-INF/faces-config.xml </param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <jsp-config> <taglib> <taglib-uri>http://ff.com</taglib-uri> <taglib-location>/WEB-INF/ff.tld</taglib-location> </taglib> </jsp-config> <listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> </web-app> tld <?xml version="1.0" encoding="ISO-8859-1"?> <taglib xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1"> <display-name>RichFaces</display-name> <tlib-version>3.3.3</tlib-version> <short-name>ff</short-name> <uri>http://ff.com</uri> <tag> <name>mylabel</name> <tag-class>com.PrinterTag</tag-class> <body-content>tagdependent</body-content> <attribute> <description>The attribute takes a value-binding expression for a component property of a backing bean </description> <name>label</name> <rtexprvalue>false</rtexprvalue> <type>java.lang.String</type> </attribute> </tag> </taglib> faces-config <?xml version='1.0' encoding='UTF-8'?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> <component> <component-type>printer</component-type> <component-class>com.Printer</component-class> </component> </faces-config> test.xhtml <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:ff="http://ff.com"> <h:head> <title>Simple JSF Facelets page</title> </h:head> <h:body> before-<ff:mylabel label="This is my first tag"/>-after </h:body> </html> (prints before--after) I'm using 2.0.1-FCS jsf-api/jsf.impl/jstl-1.1.0 jsp-api/servlet-api/standart Where I'm wrong? A: You've definied the tag in a JSP TLD, while you're using JSP's successor Facelets. You need to define the tag in a Facelets TLD. When reading tutorials/books about creating custom JSF components, ensure that you're reading the JSF 2.0 targeted ones, not the JSF 1.2 targeted ones. See also: * *Java EE 6 Tutorial - creating Custom UI Components * *Steps for Creating a Custom Component *Creating Custom Component classes *Delegating Rendering to a Renderer *Defining the Custom Component Tag in a Tag Library Descriptor <-- this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Spring Test Configurations I'm fairly new to Spring and my understanding is a bit scratchy so bear with me and word answers for an idiot. I've started working on a relatively large, maven based project which has a load of (xml) spring configuration. For this we have a bunch of JUnit tests. At the moment spring configuration for the tests replaces the configuration for the core project modules, which is an issue because it means that if we make changes to the configuration of the main project then those changes aren't reflected in the test module and hence it's possible to get funny test results. We are currently changing this structure so that the test module configuration overrides (rather than replaces) the main modules configuration. So we only have to override the particular beans we are interested in for each tests. Is this the best way to do this? Are there alternative ways? Is it possible to fine tune this ever further so that you can override specific setters of a particular bean (rather than the entire bean) for tests? Any advice is much appreciated. A: Ow having to mess with the method to test it is a bit weird by it self in my opinion. I would avoid that at all if possible, and use spring resources to help you, with dependency injection, different application-contexts for test and dev and mock frameworks you can test almost every thing I can think of. Maybe you could try to use those. An example, it's a bit hard to simulate an user security context, but with spring it becomes fairly easy, you just need to create an application-context.xml for the tests (and point to it) and assign a factory in it to create a Bean of Authentication type(it's an interface) and you can use easy mock to automate this bean responses. But for that to work you have to build your code with that in mind so instead of calling SecurityContext.getContext.... you inject that Authentication Bean from the factory. A: In your main configuration separate out all the environment dependent configuration (like datasource, jms connectionfactory etc) to a separate config file - (something like infrastructure-config.xml). The configuration that doesn't change across test & deploy goes into a different file - application-config.xml. Now for the test only create a new version of the infrastructure config file - test-infrastructure-config.xml and use it with the application-config from the main. A: You can split your main configuration in separate (logical) units and import them into your test configuration as needed. Keep in mind that Spring 3.1 will introduce XML profiles. This is perfect for testing (with different enviroment specific configurations). It's not finally released yet but I would (and do) use the milestone in new projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Online receipt validation for Mac App Store In-App Purchases For in-app purchases for iOS we can use an online API for validation, meaning that we can validate the purchase on our own server. Is there any way (API) for such validation of in app purchases for OS X? I've found only this snippet about in-app validation for Mac and it seems that Apple doesn't provide any API for online validation. Or maybe there is some plan from Apple to support online validation for OS X? A: My app EasyBooks provides an online component that users pay yearly for. It wouldn't make sense to provide this as a non-consumable type as it only really works as a consumable (however it's really a non-repeating subscription in iOS). I would like to offer this in-app and I think I have a solution finally... I used one of my Apple DTS tickets to query a statement made in the StoreKitGuide document. It says ... "OS X supports both the server validation method described in this chapter and the local validation method..." I got a reply from Apple saying ... "The steps for verifying your In-App Purchase products for Mac applications are the same used for iOS applications. The difference is that you will be assigning your base 64 encoded app receipt (rather than the content of the transactionReceipt property) to the receipt-data field. Retrieve the full Mac App Store receipt for your application, then encode it using base64 encoding. Create a JSON object with a single key named receipt-data and assign your encoded receipt to it. Proceed as outlined in the Verifying a Receipt with the App Store section of the In-App Purchase Programming Guide. Note: In App Purchases receipt are included in the associated Mac app's receipt. You must check the receipt associated with your app to verify the validity of the In-App Purchase receipts that it contains. Doing so also allows you to enable the appropriate functionality in your app." So after some failed attempts, I did manage to get this working with the caveat that the receipt data returned by Apple's servers does not contain the 'hash of the GUID' and therefore does not tie the receipt data to any particular hardware. This can be tested on your Mac quite easily using these steps: * *Find the Mac app receipt file (it's in your app's bundle once you've run the app and entered your (test) Apple ID and password. *At the command line, base64 -i receipt will base64 encode the receipt with no line breaks (that's important) *Again at the command line, curl -d '{ "receipt-data": "<your b64 string here>" }' https://sandbox.itunes.apple.com/verifyReceipt This returns JSON data in the format {"status":0, "environment":"Sandbox", "receipt":{"adam_id":"0", "bundle_id":"uk.co.geode.easybooks", "application_version":"2.2.7", "download_id":"0", "in_app":[ {"quantity":"1", "product_id":"uk.co.geode.easybooks.syncing", "transaction_id":"1000000034508678", "purchase_date":"2012-09-05 12:00:17 Etc/GMT", "original_transaction_id":"1000000034508678", "original_purchase_date":"2012-01-24 10:16:17 Etc/GMT"} ]}} I have not confirmed it yet, but apparently (according to the Apple engineer) any consumable types of in-app purchase will be added to the receipt when first purchased, but removed after any further purchases or restore operations. I wonder whether it might be a good idea to make the code running in the app make a copy of the receipt file after each purchase just in case our own servers are down at the time the app tries to validate the receipt. Users may otherwise try to restore purchases, not realising this will remove any consumable product receipts. I hope that helps. (ORIGINAL COMMENTS FOLLOW) I have the same issue. I have an iOS app in the store that has a mix of consumable and non-consumable products that can be purchased in-app. The consumable product is a service, which is fulfilled by my webserver. In the StoreKit delegate method paymentQueue:updatedTransactions:, I use the transactionReceipt property, which is an NSData object. I encode this to base64 and send it to the server. Out on the server I pass the receipt to Apple's servers for validation. But for Mac OS, there is no transactionReceipt property on the SKPaymentTransaction, so we cannot validate receipts in the same way. We can do the non-consumable products, which may help you. When an in-app purchase is made on Mac OS, the receipt is updated in the app bundle. It is then possible to parse the receipt file looking for each in-app receipt, which are all stored in the receipt file in the main bundle. For more about that see http://developer.apple.com/library/mac/#releasenotes/General/ValidateAppStoreReceipt/_index.html This works fine for me when I use the non-consumable product, but I have one consumable and this is not updated into the app's receipt file. Without the transactionReceipt property, I don't see any way for my server to validate that the receipt is genuine. If anyone else has any other experience please let us know! Anyone with an Apple developer account can also read about this on the Apple developer forum: https://devforums.apple.com/message/548411#548411 A: SwiftyStoreKit is popular: * *https://github.com/bizz84/SwiftyStoreKit InAppReceipt for local receipt validation: * *https://github.com/tikhop/TPInAppReceipt
{ "language": "en", "url": "https://stackoverflow.com/questions/7598047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: I don't understand how "?" is being used here So, I have this PHP code: $tabid = getTabid($module); if($tabid==9) $tabid="9,16"; $sql = "select * from field "; $sql.= " where field.tabid in(?) and"; Now, how exactly does the ? work here? I vaguely understand that in PHP, ?: is a ternary operator, but the colon isn't being used here, and ? is part of a Postgresql query anyway. The final query looks a bit like this: select * from field where field.tabid in('9,16') So, the question mark is replaced by the contents of $tabid, how does that happen? The issue is that ('9,16') is not accepted by Postgres as an integer, it needs to be written like (9,16), so how do I do that? How do I remove the apostrophes? Thanks a lot for the help, have a good day! edit: More code was requested: $sql.= " field.displaytype in (1,2,3) and field.presence in (0,2)"; followed by if statements, I think this is the relevant one: if($tabid == 9 || $tabid==16) { $sql.= " and field.fieldname not in('notime','duration_minutes','duration_hours')"; } $sql.= " group by field.fieldlabel order by block,sequence"; $params = array($tabid); //Running the query. $result = $adb->pquery($sql, $params); Oh, I think I see now, I think it is a place holder, a part of the pquery function: function pquery($sql, $params, $dieOnError=false, $msg='') { Stuff $sql = $this->convert2Sql($sql, $params); } Now, this is where it seems to get fun, here's part of the convert2Sql function: function convert2Sql($ps, $vals) { for($index = 0; $index < count($vals); $index++) { if(is_string($vals[$index])) { if($vals[$index] == '') { $vals[$index] = "NULL"; } else { $vals[$index] = "'".$this->sql_escape_string($vals[$index]). "'"; } } } $sql = preg_replace_callback("/('[^']*')|(\"[^\"]*\")|([?])/", array(new PreparedQMark2SqlValue($vals),"call"), $ps); return $sql; } The problem I think lies in the $vals[$index] = "'".$this->sql_escape_string($vals[$index]). "'"; line. The sql_escape_string($str) function just returns pg_escape_string($str). Sorry for the super long edit, but I still haven't been able to get past I am afraid, thanks for all the help! Edit 2: I fixed the problem, all it took was changin $tabid = "9,16" to $tabid = array(9,16). I have no idea why, oh and I also had to remove the group by statement because Postgresql requires every field to be placed in that statement. A: it is a positional parameter for a prepared statement See: http://php.net/manual/en/function.pg-prepare.php You don't actually 'remove' the quotes, you have to pass SQL array of ints instead of a string value into the parameter when doing pg_execute An example: // Assume that $values[] is an array containing the values you are interested in. $values = array(1, 4, 5, 8); // To select a variable number of arguments using pg_query() you can use: $valuelist = implode(', ', $values); // You may therefore assume that the following will work. $query = 'SELECT * FROM table1 WHERE col1 IN ($1)'; $result = pg_query_params($query, array($valuelist)) or die(pg_last_error()); // Produces error message: 'ERROR: invalid input syntax for integer' // It only works when a SINGLE value specified. Instead you must use the following approach: $valuelist = '{' . implode(', ', $values . '}' $query = 'SELECT * FROM table1 WHERE col1 = ANY ($1)'; $result = pg_query_params($query, array($valuelist));
{ "language": "en", "url": "https://stackoverflow.com/questions/7598052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Displaying errors in divs, one below other I need to display some error messages (one, two, n errors) in a series of divs in my page. They need to appear horizontal centered and fixed at top (even with scroll page). I tried something like this (for two divs for now): <div id="mensagens"> <div id="erros" style="display: none;"> <span></span> </div> <div id="alertas" style="display: none;"> <span></span> </div> </div> css: #mensagens { position:absolute; position: fixed; top: 0px; z-index:9999; } #alertas { width: 700px; margin-left: 350px; left: 50%; font-size: 100%; font-weight: bold; background:orange; padding:6px; } #erros { width: 700px; margin-left: 350px; left: 50%; font-size: 100%; font-weight: bold; background:red; padding:6px; } But this is not centering it horizontally. Any ideas how I can do this? A: Instead of using the margin-left and left properties on #erros and #alertas, use: margin-left: auto and margin-right: auto, which will set them to be equidistant from the left and right sides of the page, respectively. You should be able to change your code to the following: #mensagens { position:absolute; position: fixed; top: 0px; z-index:9999; } #alertas { width: 700px; margin-left: auto; margin-right: auto; font-size: 100%; font-weight: bold; background:orange; padding:6px; } #erros { width: 700px; margin-left: auto; margin-right: auto; font-size: 100%; font-weight: bold; background:red; padding:6px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML Forms: Display entered data on a separate page I have a simple HTML form like this: <form name='input' action='thankyou.jsp' method='post'> <p>Email Address: <input type='text' name='email' size='16' /><br> <p>Password: <input type='password' name='password' size='16' /><br> <p>Verify Password: <input type='password' name='verifypassword' size='16' /><br> <br> <input type='submit' value='Submit your data'/> </form> I want to be able to take the information a user enters and display it on a thank you page afterwards, how could I go about doing so? A: you can first study the server-side scripting language,if you want to read JavaScript than this link may help you. visit this site Click Here. you can also choose other scripting language which you understand easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unique attribute for 2 elements via XML Schema I have the next xml structure: <menubar> <menu id="id1"> <menuitem id="id2"/> <menuitem id="id3"/> <menuitem id="id4"/> <menu id="id5"> <menuitem id="id1"/> -error because has the same id as the first menu element ... <menuitem id="id7"/> </menu> </menu id="id8"> <menu id="id9"> <menuitem id="id10"/> <menuitem id="id11"/> </menu> ... </menubar> Verbal form: menubar has * menu menu has * menu and * menuitem Question: how to specify uniquess for space of 2 elements: menu and menuitem? In other words: all menus and menuitems elements should have unique id attributes between itselfs and each others. Nesting of menu and menuitem elements for menu element could be endless. Here what I have now: <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.alexblog.me" xmlns="http://www.alexblog.me" elementFormDefault="qualified"> <xsd:element name="menubar" type="MenubarType"> <xsd:unique name="uniqueIdsForMenubarElements"> <xsd:selector xpath=".//*"/> <xsd:field xpath="@id"/> </xsd:unique> </xsd:element> <xsd:element name="menu" type="MenuType"/> <xsd:element name="menuitem" type="MenuitemType" nillable="true"/> <xsd:attributeGroup name="MenubarElementsAttributeGroup"> <xsd:attribute name="id" type="xsd:string" use="required"/> </xsd:attributeGroup> <xsd:complexType name="MenuitemType"> <xsd:attributeGroup ref="MenubarElementsAttributeGroup"/> </xsd:complexType> <xsd:complexType name="MenuType"> <xsd:choice minOccurs="0" maxOccurs="unbounded"> <xsd:element name="menu" type="MenuType"/> <xsd:element name="menuitem"/> </xsd:choice> <xsd:attributeGroup ref="MenubarElementsAttributeGroup"/> </xsd:complexType> <xsd:complexType name="MenubarType"> <xsd:sequence> <xsd:element ref="menu" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> </xsd:schema> It works, but only for menu elements. Menuitem elements just ignors. A: In MenuType declaration, element's type for menuitem is omitted. Specify it and validation will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If the admin don't set the ssh service port on default 22, how can i find the port that he set? nmap can't do the work. I have checked that. ps: I just use the basic nmap function(nmap host). Oh, My god. Trust me i don't plan to do bad things. I am just curious! Please don't do -1! update, use command: nmap -v -p1-65535 -sV Scanning hidethehostaddress [2 ports] Completed Ping Scan at 21:38, 0.00s elapsed (1 total hosts) Initiating Parallel DNS resolution of 1 host. at 21:38 Completed Parallel DNS resolution of 1 host. at 21:38, 0.00s elapsed Initiating Connect Scan at 21:38 Scanning hidethehostaddress [65535 ports] Connect Scan Timing: About 11.88% done; ETC: 21:43 (0:03:50 remaining) Connect Scan Timing: About 32.96% done; ETC: 21:41 (0:02:04 remaining) Completed Connect Scan at 21:40, 83.98s elapsed (65535 total ports) Initiating Service scan at 21:40 Nmap scan report for hidethehostaddress Host is up (0.080s latency). Not shown: 65532 filtered ports PORT STATE SERVICE VERSION 23/tcp closed telnet 80/tcp closed http 443/tcp closed https Read data files from: /usr/share/nmap Service detection performed. Please report any incorrect results at http://nmap.org /submit/ . Nmap done: 1 IP address (1 host up) scanned in 84.13 seconds A: It can: nmap -v -p1-65535 -sV scanme.nmap.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7598062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to create a Windows-style textbox in a C++ Win32 application I tried this: #include <windows.h> #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR nCmdLine, int nCmdShow) { LPTSTR windowClass = TEXT("WinApp"); LPTSTR windowTitle = TEXT("Windows Application"); WNDCLASSEX wcex; wcex.cbClsExtra = 0; wcex.cbSize = sizeof(WNDCLASSEX); wcex.cbWndExtra = 0; wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wcex.hInstance = hInstance; wcex.lpfnWndProc = WndProc; wcex.lpszClassName = windowClass; wcex.lpszMenuName = NULL; wcex.style = CS_HREDRAW | CS_VREDRAW; if (!RegisterClassEx(&wcex)) { MessageBox(NULL, TEXT("RegisterClassEx Failed!"), TEXT("Error"), MB_ICONERROR); return EXIT_FAILURE; } HWND hWnd; if (!(hWnd = CreateWindow(windowClass, windowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL))) { MessageBox(NULL, TEXT("CreateWindow Failed!"), TEXT("Error"), MB_ICONERROR); return EXIT_FAILURE; } HWND hWndEdit = CreateWindow(TEXT("Edit"), TEXT("test"), WS_CHILD | WS_VISIBLE | WS_BORDER, 100, 20, 140, 20, hWnd, NULL, NULL, NULL); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return EXIT_SUCCESS; } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_DESTROY: PostQuitMessage(EXIT_SUCCESS); default: return DefWindowProc(hWnd, msg, wParam, lParam); } return FALSE; } I use: CreateWindow(TEXT("Edit"), TEXT("test"), WS_CHILD | WS_VISIBLE | WS_BORDER, 100, 20, 140, 20, hWnd, NULL, NULL, NULL); to create a textbox, and it's just an ugly black-solid-border textbox. How to create a windows style textbox (with a 3D light blue border)? A: The OP edited his question, removing the original code and therefore invalidating the answers, saying: This is a simple example to create a window with a textbox. I rolled it back to restore the original code, but I thought the working example was nice, so here it is: #include <windows.h> #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR nCmdLine, int nCmdShow) { LPTSTR windowClass = TEXT("WinApp"); LPTSTR windowTitle = TEXT("Windows Application"); WNDCLASSEX wcex; wcex.cbClsExtra = 0; wcex.cbSize = sizeof(WNDCLASSEX); wcex.cbWndExtra = 0; wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wcex.hInstance = hInstance; wcex.lpfnWndProc = WndProc; wcex.lpszClassName = windowClass; wcex.lpszMenuName = NULL; wcex.style = CS_HREDRAW | CS_VREDRAW; if (!RegisterClassEx(&wcex)) { MessageBox(NULL, TEXT("RegisterClassEx Failed!"), TEXT("Error"), MB_ICONERROR); return EXIT_FAILURE; } HWND hWnd; if (!(hWnd = CreateWindow(windowClass, windowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL))) { MessageBox(NULL, TEXT("CreateWindow Failed!"), TEXT("Error"), MB_ICONERROR); return EXIT_FAILURE; } HWND hWndEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("Edit"), TEXT("test"), WS_CHILD | WS_VISIBLE, 100, 20, 140, 20, hWnd, NULL, NULL, NULL); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return EXIT_SUCCESS; } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_DESTROY: PostQuitMessage(EXIT_SUCCESS); default: return DefWindowProc(hWnd, msg, wParam, lParam); } return FALSE; } A: Instead of using CreateWindow, use CreateWindowEx and specify WS_EX_CLIENTEDGE as the first parameter. You can compare the styles of your created edit control with a stock one (for example, when you show 'Properties' on a file in the explorer) with the Spy++ tool that comes along Visual Studio. A: In Codeblocks put manifest file near project: program_name.exe.manifest And to program_name.exe.manifest write this: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" processorArchitecture="*" name="CompanyName.ProductName.YourApplication" type="win32" /> <description>Program name</description> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> </assembly> And then your program look like this:
{ "language": "en", "url": "https://stackoverflow.com/questions/7598067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Link in TextField of flash cannot be clicked if it is embedded in different domain I wrote a flash (ActionScript3) based radio streaming player, there is a link in the player for users to click. It's is a "a" tag in TextField. The code looks like this textField.htmlText = '<u><a href="' + url +'">' + htmlEscape(text) + '</a></u>'; It works fine if I put my flash player in same domain of web-page, however, if the domain of web-page is different from the location of flash player, then the link is not clickable. For example: A radio example page You can see there is a link in the title bar of radio player, I hosted the flash player on CDN, its domain is different from the web-page, therefore, the link is not clickable. Why the link cannot be clicked if it is embedded in a cross-domain page? It doesn't make any sense. I did set the crossdomain.xml file properly, but it appears that it doesn't work. How can I solve this? I want to make the link clickable everywhere, no matter what domain the web-page is located. Thanks. A: I get this error message when testing it: URL for window '_self' halted (AllowScriptAccess is 'sameDomain'): http://now.in/radio/victor So maybe it can be fixed by setting allowScriptAccess="always" in the embedding code in the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Izpack: Validator doesn't work? I have a field description in my "UserInputSpec.xml" file. <field type="radio" variable="selected.source" > <description align="left" txt="Please select TBPAPIIntegrator data source:" id="combo.text" /> <spec> <choice txt="IMKB Server" id="combo.item.imkb" value="imkb"/> <choice txt="Exernal Database" id="combo.item.database" value="db"/> </spec> <validator class="com.j32bit.installer.validator.SelectSourceValidator" txt="Please select one source!" > <param name="selected.source" value="${selected.source}"/> </validator> </field> and this my Validator class: package com.j32bit.installer.validator; import java.util.Map; import com.izforge.izpack.panels.ProcessingClient; import com.izforge.izpack.panels.Validator; public class SelectSourceValidator implements Validator{ @Override public boolean validate(ProcessingClient client) { Map<String, String> params = client.getValidatorParams(); if( params.get("selected.source").equals("imkb") || params.get("selected.source").equals("db")) return true; return false; } } Also variable deceleration as below in "Installer.xml": <variables> <variable name="selected.source" value="" /> </variables> Radio buttons comes unselected. While buttons still unselected if I click "next" button installer continuous the next page and validation does not work. Please help! Thanks in advance. A: It seems like declaring a variable in <dynamicvariables></dynamicvariables> or in <variables></variables> does not work at all. Instead you can just write a variable name to a field and it can be used and referenced in anywhere in installer. I also removed validator from field declaration in UserInputPanelSpec.xml and moved it to panel declaration in Installer.xml. Installer.xml: <panels> <panel classname="UserInputPanel" id="select.source" > <validator classname="com.j32bit.installer.validator.SourceValidator"/> </panel> </panels> UserInputPanelSpec.xml: <!-- SELECT SOURCE PANEL --> <panel id="select.source"> <field type="radio" variable="selected.source" > <description align="left" txt="Please select TBPAPIIntegrator data source:" id="radio.text" /> <spec> <choice txt="IMKB" id="radio.item.imkb" value="imkb" /> <choice txt="Exernal Database" id="radio.item.db" value="db" /> </spec> </field> </panel> Now it is working with no problem. A: For field, it can help if you include validator element inside the spec one: <field type="radio" variable="selected.source" > <description align="left" txt="Please select TBPAPIIntegrator data source:" id="combo.text" /> <spec> <choice txt="IMKB Server" id="combo.item.imkb" value="imkb"/> <choice txt="Exernal Database" id="combo.item.database" value="db"/> <validator class="com.j32bit.installer.validator.SelectSourceValidator" txt="Please select one source!" > <param name="selected.source" value="${selected.source}"/> </validator> </spec> </field>
{ "language": "en", "url": "https://stackoverflow.com/questions/7598073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NULL Exception in EF 4.1 I use Entity Framework 4.1, SQL Server 2008 & .NET 4.0 I have a Sql table: create table SchemaVersion ( Version int not null, constraint PK_SCHEMAVERSION primary key (Version) ) And POCO [Table("SchemaVersion")] public class SchemaVersion { [Key] public Int32 Version { get; set; } } I added the column in table Context ctx = new Context(); ctx.SchemaVersions.Add(new SchemaVersion() { Version = 2 }); ctx.SaveChanges(); after i get the exception : Cannot insert the value NULL into column 'Version', table 'Simply.dbo.SchemaVersion'; column does not allow nulls. INSERT fails. The statement has been terminated. Context setup: public class Context : DbContext { public DbSet<SchemaVersion> SchemaVersions { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { this.Configuration.ValidateOnSaveEnabled = false; base.OnModelCreating(modelBuilder); } } I think it is very strange, Who can help me solve this issue A: Try to disable database generation of the key: [Table("SchemaVersion")] public class SchemaVersion { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public Int32 Version { get; set; } } You seem to want to supply your Version values manually when you add a new entity to the database. By default, EF assumes the keys of type int are identities in the database and will be generated there. Therefore EF would not send a value to the database. If the key is NOT an identity in the DB then no value for the key will be supplied at all, resulting in the exception. If you set DatabaseGeneratedOption.None EF will sent the value you set as the key to the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my counter variable not come back to 0 in a multithreaded scenario? I'm building a Windows Service base class to manages the polling off a schedule's table of any pending task and the running them. The Windows service is using the System.Timers.Timer to start the schedule's table polling. I'm setting the ThreadPool.SetMaxThread to 10 before initialising the timer. protected override void OnStart(string[] args) { ThreadPool.SetMaxThreads(10, 10); this._Timer = new System.Timers.Timer(); this._Timer.Elapsed += new ElapsedEventHandler(PollWrapper); this._Timer.Interval = 100; this._Timer.Enabled = true; } The delegate method called by the timer keeps the count of the running threads so that it can be used in the OnStop() method to wait for each thread to complete before disposing the service. private void PollWrapper(object sender, ElapsedEventArgs e) { numberOfRunningThreads++; try { this.Poll(sender, e); } catch (Exception exception) { //some error logging here } finally { numberOfRunningThreads--; } } protected override void OnStop() { this._Timer.Enabled = false; while (numberOfRunningThreads > 0) { this.RequestAdditionalTime(1000); Thread.Sleep(1000); } } Often, the service would not stop when I try to stop it from the Windows service management console. If I debug it and add a breakpoint to the OnStop() method I can see that it is not because the numberOfRunningThreads is stuck on a number greater than 0 (often much greater than 10!). No tasks are running and it stays on that number forever! Firstly, I don't understand how that number could ever be greater than 10, despite the ThreadPool.SetMaxThreads should limit it to 10? Secondly, even if I did not set the maximum number of threads, I would expect the finally block of the PollWrapper's to eventually bring the count back to 0. If the counter stays greater than 0, it can be explained only with the finally block not executing, right!? How that is possible? And lastly, would you suggest a differently way to limit the Poll to a number of possible concurrent running threads to a fixed number (.NET 3.5)? Many thanks. UPDATE: After reading Yahia's comments on reentrancy and SetMaxThread I have modified the PollWrapper so that it should always limit the max number of spawned running threads. I will still to make sure Poll is reentrant. private void PollWrapper(object sender, ElapsedEventArgs e) { lock(this) { if(this.numberOfRunningThreads < this.numberOfAllowedThreads) { this.numberOfRunningThreads++; Thread t = new Thread( () => { try { this.Poll(sender, e); } catch (Exception ex) { //log exception } finally { Interlocked.Decrement(ref this.numberOfRunningThreads); } } ); t.Start(); } } A: Yes, there are situations where a finally block may never run. * *You can turn off your computer before the finally executes. *The code in the try block might never terminate (e.g. infinite loop). *Environment.FailFast does not run finally blocks. *A severe error in the runtime might cause the entire process to crash without executing the finally. In addition the finally block might start running but not complete if it is interrupted, if it throws an exception, or if it goes into an infinite loop. Here though your problem seems to be that you are using multiple threads but not synchronizing access to shared variables: numberOfRunningThreads++; You need to lock on a shared object here. A: Your problem is that you don't lock the access of numberOfRunningThreads. Multiple threads can modify this as once causing a race condition where numberOfRunningThreads is not incremented or decremented correctly. You can use Interlocked.Increment, Interlocked.Decrement instead of ++ and ... A: As per request of OP (see comments above) in regards to the updated question/code: The lock statement behaves like a "critical" section i.e. it stops that specific code block from being executed in parallel - the parameter of lock is used as the "syncrhonization object" so that any code block surrounded by a lock on the same variable wouldn't be executed in parallel on a different thread. The lock statement doesn't do anything with the variable/its contents - for example it doesn't "freeze" the contents so they can still be change anywhere anytime in any executing code (parallel) as long as that code is not protected by lock and the same variable as a parameter. If you look at the link I provided (your points to an outdated documentation version for VS2003) it says explicitely that lock(this) for example is NOT ok to use - the reason and a best practice is described accordingly... ALL of the above renders the provided code (updated version) still not thread-safe (although definitively better than the original version).
{ "language": "en", "url": "https://stackoverflow.com/questions/7598081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to set placeholders in like statement query I am creating a PreparedStatement with SQL which have a like statement, and I am setting the placeholders using setString(), method, but it does not give any error or fetch any records. When I run the query direct at database by setting arguments in like statements then I get results, so I think there may be any other way to put place holders in sql, I am doing like below: select name from employee where name like ? I also tried: select name from employee where name like (?) and set parameters using setString() method but I did not get any results. Please help what is wrong in it A: this is an example from API: PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); // set the first (?) pstmt.setBigDecimal(1, 153833.00) // set the second (?) pstmt.setInt(2, 110592) you can see more in : http://download.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html A: It is the way by which you used it first. If you need another post which explains this, please see: Cannot use a LIKE query in a JDBC PreparedStatement?
{ "language": "en", "url": "https://stackoverflow.com/questions/7598082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Purpose of Activator.CreateInstance with example? Can someone explain Activator.CreateInstance() purpose in detail? A: Well i can give you an example why to use something like that. Think of a game where you want to store your level and enemies in an XML file. When you parse this file, you might have an element like this. <Enemy X="10" Y="100" Type="MyGame.OrcGuard"/> what you can do now is, create dynamically the objects found in your level file. foreach(XmlNode node in doc) var enemy = Activator.CreateInstance(null, node.Attributes["Type"]); This is very useful, for building dynamic enviroments. Of course its also possible to use this for Plugin or addin scenarios and alot more. A: The Activator.CreateInstance method creates an instance of a specified type using the constructor that best matches the specified parameters. For example, let's say that you have the type name as a string, and you want to use the string to create an instance of that type. You could use Activator.CreateInstance for this: string objTypeName = "Foo"; Foo foo = (Foo)Activator.CreateInstance(Type.GetType(objTypeName)); Here's an MSDN article that explains it's application in more detail: http://msdn.microsoft.com/en-us/library/wccyzw83.aspx A: Say you have a class called MyFancyObject like this one below: class MyFancyObject { public int A { get;set;} } It lets you turn: String ClassName = "MyFancyObject"; Into MyFancyObject obj; Using obj = (MyFancyObject)Activator.CreateInstance("MyAssembly", ClassName)) and can then do stuff like: obj.A = 100; That's its purpose. It also has many other overloads such as providing a Type instead of the class name in a string. Why you would have a problem like that is a different story. Here's some people who needed it: * *Createinstance() - Am I doing this right? *C# Using Activator.CreateInstance *Creating an object without knowing the class name at design time A: My good friend MSDN can explain it to you, with an example Here is the code in case the link or content changes in the future: using System; class DynamicInstanceList { private static string instanceSpec = "System.EventArgs;System.Random;" + "System.Exception;System.Object;System.Version"; public static void Main() { string[] instances = instanceSpec.Split(';'); Array instlist = Array.CreateInstance(typeof(object), instances.Length); object item; for (int i = 0; i < instances.Length; i++) { // create the object from the specification string Console.WriteLine("Creating instance of: {0}", instances[i]); item = Activator.CreateInstance(Type.GetType(instances[i])); instlist.SetValue(item, i); } Console.WriteLine("\nObjects and their default values:\n"); foreach (object o in instlist) { Console.WriteLine("Type: {0}\nValue: {1}\nHashCode: {2}\n", o.GetType().FullName, o.ToString(), o.GetHashCode()); } } } // This program will display output similar to the following: // // Creating instance of: System.EventArgs // Creating instance of: System.Random // Creating instance of: System.Exception // Creating instance of: System.Object // Creating instance of: System.Version // // Objects and their default values: // // Type: System.EventArgs // Value: System.EventArgs // HashCode: 46104728 // // Type: System.Random // Value: System.Random // HashCode: 12289376 // // Type: System.Exception // Value: System.Exception: Exception of type 'System.Exception' was thrown. // HashCode: 55530882 // // Type: System.Object // Value: System.Object // HashCode: 30015890 // // Type: System.Version // Value: 0.0 // HashCode: 1048575 A: You can also do this - var handle = Activator.CreateInstance("AssemblyName", "Full name of the class including the namespace and class name"); var obj = handle.Unwrap(); A: A good example could be next: for instance you have a set of Loggers and you allows user to specify type to be used in runtime via configuration file. Then: string rawLoggerType = configurationService.GetLoggerType(); Type loggerType = Type.GetType(rawLoggerType); ILogger logger = Activator.CreateInstance(loggerType.GetType()) as ILogger; OR another case is when you have a common entities factory, which creates entity, and is also responsible on initialization of an entity by data received from DB: (pseudocode) public TEntity CreateEntityFromDataRow<TEntity>(DataRow row) where TEntity : IDbEntity, class { MethodInfo methodInfo = typeof(T).GetMethod("BuildFromDataRow"); TEntity instance = Activator.CreateInstance(typeof(TEntity)) as TEntity; return methodInfo.Invoke(instance, new object[] { row } ) as TEntity; } A: Building off of deepee1 and this, here's how to accept a class name in a string, and then use it to read and write to a database with LINQ. I use "dynamic" instead of deepee1's casting because it allows me to assign properties, which allows us to dynamically select and operate on any table we want. Type tableType = Assembly.GetExecutingAssembly().GetType("NameSpace.TableName"); ITable itable = dbcontext.GetTable(tableType); //prints contents of the table foreach (object y in itable) { string value = (string)y.GetType().GetProperty("ColumnName").GetValue(y, null); Console.WriteLine(value); } //inserting into a table dynamic tableClass = Activator.CreateInstance(tableType); //Alternative to using tableType, using Tony's tips dynamic tableClass = Activator.CreateInstance(null, "NameSpace.TableName").Unwrap(); tableClass.Word = userParameter; itable.InsertOnSubmit(tableClass); dbcontext.SubmitChanges(); //sql equivalent dbcontext.ExecuteCommand("INSERT INTO [TableNme]([ColumnName]) VALUES ({0})", userParameter); A: Coupled with reflection, I found Activator.CreateInstance to be very helpful in mapping stored procedure result to a custom class as described in the following answer. A: Why would you use it if you already knew the class and were going to cast it? Why not just do it the old fashioned way and make the class like you always make it? There's no advantage to this over the way it's done normally. Is there a way to take the text and operate on it thusly: label1.txt = "Pizza" Magic(label1.txt) p = new Magic(lablel1.txt)(arg1, arg2, arg3); p.method1(); p.method2(); If I already know its a Pizza there's no advantage to: p = (Pizza)somefancyjunk("Pizza"); over Pizza p = new Pizza(); but I see a huge advantage to the Magic method if it exists. A: We used it for something like e.g. public interface IExample { void DoSomethingAmazing(); } public class ExampleA : IExample { public void DoSomethingAmazing() { Console.WriteLine("AAAA"); } public void DoA() { Console.WriteLine("A") } } public class ExampleB : IExample { public void DoSomethingAmazing() { Console.WriteLine("BBBB"); } public void DoB() { Console.WriteLine("B") } } and then provided the type serialized from a settings file => Even after compilation we can still change the applications behaviour by using different settings Something like e.g. public static class Programm { public static void Main() { var type = MagicMethodThatReadsASerializedTypeFromTheSettings(); var example = (IExample) Activator.CreateInstance(type); example.DoSomethingAmazing(); switch(example) { case ExampleA a: a.DoA(); break; case ExampleB b: b.DoB(); break; } } } And I use it in a custom multi-user serialization where I send RPC (Remote Procedure Calls) to other devices with parameters. Extremly cropped to the necesarry it basically does public ISendable { public byte[] ToBytes(); public void FromBytes(byte[] bytes); } // Converts any ISendable into a byte[] with the content // typeBytes + contentBytes public byte[] ToBytes(ISendable toSend) { var typeBytes = Encoding.ASCII.GetBytes(toSend.GetType().AssemblyQualifiedName); var contentBytes = ISendable.ToBytes(); return MagicMethodToCombineByteArrays(typeBytes, contentBytes); } // Coonverts back from byte[] to the according ISendable // by first reading the type, creating the instance and filling it with // contentBytes public T FromBytes<T>(byte[] bytes) where T : ISendable { MagicMethodToSplitInputBytes(out var typeBytes, out var contentBytes); var type = Encoding.ASCII.GetString(typeBytes); var instance = (T) Activator.CreateInstance(type); instance.FromBytes(contentBytes); return instance; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "164" }
Q: Books and tutorials about jQuery and Rails 3 I am trying to learn jQuery in Rails 3 context. (I have no experience with other JS libraries). A couple hours Googling didn't turn up much. The only book I can find is Practical Rails with jQuery Projects. Could you recommend books, tutorials etc. that cover more than just up and running jQuery in Rails? (I know some people will suggest to learn jQuery as a separate topic, and I am doing that. But integrate it to Rails brings unique challenges). A: There's some good stuff about doing ajaxy stuff with rails here: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/ Apart from that there's not much that is rails specific.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery dialog and ajax postback A page on my site are auto-reloading every 15th second. It's being done by using jQuery's .ajax function. My problem are, that everytime the page are being loaded by the user, the form in the dialogs work fine. But when it's reloaded automatically by the page itself, the inputs are being moved OUTSIDE the form. Many on the internet writes, that it is possible to move it back into the form by appending a div into the first form found. My problem is, that when i try to move my "input-wrapper" back into the form, i get a hirachy-problem. Can anyone help? Or point out an alternative solution? My jQuery-script: <script type='text/javascript'> var intval; var xmlhttp; function init() { $('#dialog:ui-dialog').dialog('destroy'); $('.ui-dialog').dialog({ modal: true, draggable: false, resizable: false, autoOpen: false, open: function(event, ui) { stopTimer(); }, close: function(event, ui) { startTimer(); } }); $('#targets').dialog({ width: 400, buttons: { 'close': { text: 'Luk', height: '30px', click: function() { $(this).dialog('close'); } }, 'submit': { text: 'OK', class: 'submit', height: '30px', click: function() { $(this).find('form').trigger('submit'); } } } }); $('#targets" & id2 & "Opener').click(function() { $('#targets').dialog('open'); return false; }); }; function startTimer() { intval = setTimeout('ajaxRefresh()', 15000); }; function stopTimer() { clearTimeout(intval); if(xmlhttp) xmlhttp.abort(); }; function ajaxRefresh() { xmlhttp = $.ajax({ url: '/', data: {h: 'ok'}, beforeSend: function() { stopTimer(); }, success: function(result) { $('body').html(result); } } }) }; $(document).ready(function() { init(); startTimer(); $('#targetsFormWrap').parent().appendTo('#targetsForm'); }); </script> The HTML: <div id='targets' class='ui-dialog' title='The Dialog Title' style='text-align: center; display: none;'> <form id='targetsForm' name='targetsForm' method='post'>") <div id='targetsFormWrap'>") <input id='input1target' name='input1target' type='text' value='' style='width: 95%; /> <input id='input2target' name='input2target' type='text' value='' style='width: 95%; /> <input id='input3target' name='input3target' type='text' value='' style='width: 95%; /> </div> </form> </div> A: you are trying to add targetFormWrap to targetsForm right? so just do: $("#targetsForm").append($("#targetsFormWrap"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7598090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Not specifying which list implementation I have a doubt considering changing this : List<String> elements = new ArrayList<String>(); elements = elementDao.findElementsById(elementId); to List<String> elements; elements = elementDao.findElementsById(elementId); (I'm using DAO with Hibernate) Can this cause any errors or exceptions (the fact that i'm not specifying which List implementation should be returned) ? A: The first one creates a new arraylist for nothing. The created list is just garbage that has to be collected. The second one is better, but should be reduced to List<String> elements = elementDao.findElementsById(elementId); You seem to be thinking that the assignment operator could be used to fill a list created by the caller. This is not the case. the assignment operator just takes the reference to the list created by the DAO (and which could be any kind of List), and assigns this reference to the variable. A: You can safely change it because: List<String> elements = new ArrayList<String>(); creates a new ArrayList and assigns it to elements, then elements = elementDao.findElementsById(elementId); throws the original ArrayList away (and marks it to be garbage collected) and assign elements to it the List created inside elementDao, so the second approach is just as safe and more efficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Insert a Linefeed with PDFBox drawString I have to make a PDF with a Table. So far it work fine, but now I want to add a wrapping feature. So I need to insert a Linefeed. contentStream.beginText(); contentStream.moveTextPositionByAmount(x, y); contentStream.drawString("Some text to insert into a table."); contentStream.endText(); I want to add a "\n" before "insert". I tried "\u000A" which is the hex value for linefeed, but Eclipse shows me an error. Is it possible to add linefeed with drawString? A: The pdf format doesn't know line breaks. You have to split the string and move the text position to the next line, using moveTextPositionByAmount. This is not a special "pdfbox-feature", it is due to the pdf format definition; so there is no way for drawString and there are also no other methods to be called that support linefeeds. A: The PDF format allows line breaks, but PDFBox has no build in feature for line breaks. To use line breaks in PDF you have to define the leading you want to use with the TL-operator. The T*-operator makes a line break. The '-operator writes the given text into the next line. (See PDF-spec for more details, chapter "Text". It´s not that much.) Here are two code snippets. Both do the same, but the first snippet uses ' and the second snippet uses T*. private void printMultipleLines( PDPageContentStream contentStream, List<String> lines, float x, float y) throws IOException { if (lines.size() == 0) { return; } final int numberOfLines = lines.size(); final float fontHeight = getFontHeight(); contentStream.beginText(); contentStream.appendRawCommands(fontHeight + " TL\n"); contentStream.moveTextPositionByAmount(x, y); contentStream.drawString(lines.get(0)); for (int i = 1; i < numberOfLines; i++) { contentStream.appendRawCommands(escapeString(lines.get(i))); contentStream.appendRawCommands(" \'\n"); } contentStream.endText(); } private String escapeString(String text) throws IOException { try { COSString string = new COSString(text); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); string.writePDF(buffer); return new String(buffer.toByteArray(), "ISO-8859-1"); } catch (UnsupportedEncodingException e) { // every JVM must know ISO-8859-1 throw new RuntimeException(e); } } Use T* for line break: private void printMultipleLines( PDPageContentStream contentStream, List<String> lines, float x, float y) throws IOException { if (lines.size() == 0) { return; } final int numberOfLines = lines.size(); final float fontHeight = getFontHeight(); contentStream.beginText(); contentStream.appendRawCommands(fontHeight + " TL\n"); contentStream.moveTextPositionByAmount( x, y); for (int i = 0; i < numberOfLines; i++) { contentStream.drawString(lines.get(i)); if (i < numberOfLines - 1) { contentStream.appendRawCommands("T*\n"); } } contentStream.endText(); } To get the height of the font you can use this command: fontHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize; You might want to multiply it whit some line pitch factor. A: Because the PDF model often isn't the best model for the task at hand, it often makes sense to write a wrapper for it that adds support for whatever's "missing" in your case. This is true for both reading and writing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: jQuery .get - how to display the result of the .get request? I'm TRYING to get jQuery .get to work. I have two files. I. Where I'm perfoming this, on .click event: $.get("employee.php", { FirstName: substr[0], LastName: substr[1] }, function(data) { // HOW DO DISPLAY THE RESPONSE in #div? } ); substr coming from: var substr = ( $(this).html() ).split('<span>')[0].split(' '); II. Params are being successfuly past to employee.php and firebug display the response like this: <div class="employeePopUpBox"> GET isn't empty. John, Doe </div> PHP file: <div class="employeePopUpBox"> <?php if(!empty($_GET)) { $FistName = $_GET['FirstName']; $LastName = $_GET['LastName']; echo 'GET isn\'t empty. '.$FistName.', '.$LastName; } else { echo "GET is empty"; } ?> The quastion is how to display the response inside div#response? Any suggestion are much appreciated. A: Just use normal .html() method. $.get("employee.php", { FirstName: substr[0], LastName: substr[1] }, function(data) { $("div#response").html(data); } ); or use this one, one-line instead $("div#response").load("employee.php?FirstName="+substr[0]+"&LastName="+substr[1]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7598105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: bash if [ -n "$output of a variable" ] line=$(grep "# rvm line" ~/.bashrc) if [ ! -n "$line" ]; then echo "found" else echo "not found" fi What's wrong with my quotes in the first line? EDIT: The problem is set -o errexit, which I use in my script. I suppose -n is treated as an error, exiting the following processes. How can I overcome this, keeping the error check? (Alternatives to -n could work too). A: If you don't plan to use $line for anything else than testing if it's empty or not, then you might as well do this: if grep -q '# rvm line' ~/.bashrc; then echo "found" else echo "not found" fi A: Nothing Nothing is apparently wrong with the quotes? Are you not getting expected result ? ok,your if condition is wrong - if it was intended to check that something was returned by the grep statement. I will leave that as a clue for yourself to figure out. Goodluck
{ "language": "en", "url": "https://stackoverflow.com/questions/7598106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysqldump with InnoDB tables, how to import them without errors? I've exported a mysqldump of a database with InnoDB tables and foreign key relationships in them, using the --single-transaction flag (that I read somewhere I should use for InnoDB). No problems. But when trying to import that dump into another existing database (same database, different server) I get all sorts of errors when trying to drop the tables because it would break the InnoDB relationships. I also read that I should use foreign_key_checks=0 to avoid this, but this is a server variable, not part of the dump process. So I'm trying to figure out how to automate all this since I have a script that backs up the DB, it was working when all we had were MyISAM tables: mysqldump -u user -p'password' --single-transaction -q database | ssh user@backup.com mysql -u user -p'password' database Thanks. A: You can dump into a file, add the required SET FOREIGN_KEY_CHECKS=0; in that file, and then feed the file to mysql. A: It turns out that the mysqldump file is smart enough to detect that they are InnoDB tables and puts the appropriate comments at the top of the file. My problem was that when I exported through PHPMyAdmin it didn't put the correct comments on the file, hence causing all this trouble. Thanks for your response. A: You can also add to the mysql command line when restoring without editing the original file. This is very useful as mysql backups can become huge, and editing a GB+ file takes lots of CPU time versus adding this to the commandline, mysql -D YourDatabaseName -u YourUserName -p --init-command="set @@foreign_key_checks=0"<YourBackupDumpFile.sql
{ "language": "en", "url": "https://stackoverflow.com/questions/7598108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Overlapping mutli-line comments In C#, is there a reason why multi-line /* */ comments can't overlap? This also applies to HTML (and I'm sure lots of other languages) too. e.g. /* int a = SomeFunction(); /* int i = 0; */ int b = SomeFunction(); */ won't compile. When writing code I often want to quickly check the logic, and isolate certain parts by removing a section using multi-line comments, but then have to go through the code block replacing all multi-line comments with single line ones //. I don't like using single line comments to comment-out code blocks (even though Visual Studio provides shortcuts to do this) as these then affect text comments when it comes to removing all comments in the block using the shortcut. Is there a reason why the multi-line comment cannot mean: 'ignore everything between here'? A: I'm afraid this is the way how it's designed. I think you should use single line comments as much as possible. It's also much clearer when you are viewing the history of a file in source control. If you commented an entire method with /* */ then only two lines will appear changed, otherwise the entire method will have been changed (// added).
{ "language": "en", "url": "https://stackoverflow.com/questions/7598115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Fatal error: String could not be parsed as XML I'm trying to include an RSS feed on my website. The following code works locally but causes a fatal error on the live site: <?php // Initialise the cURL resource handle: $ch = curl_init("http://www.blogs.stopjunkmail.org.uk/diary/index.php?/feeds/index.rss2"); // Set connection options: curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); // Execute connection, wait for response, and close: $data = curl_exec($ch); curl_close($ch); // Parse the data: $doc = new SimpleXmlElement($data, LIBXML_NOCDATA); // Define the function to parse RSS: function parseRSS($doc) { echo '<ul>' . "\n"; for($i=0; $i<5; $i++) { $url = $doc->channel->item[$i]->link; $title = $doc->channel->item[$i]->title; $date = $doc->channel->item[$i]->pubDate; echo '<li>' . "\n"; echo '<a href="'.$url.'">'.$title.'</a>' . "\n"; echo '</li>' . "\n"; } echo '</ul>' . "\n"; } ?> <!doctype html> <html lang="en-GB"> <head> <meta charset="UTF-8" /> <title>Test feed</title> </head> <body> <h2>Recent blog entries</h2> <?php parseRSS($doc); ?> </body> </html> This causes the following errors: [Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/sites/stopjunkmail.org.uk/public_html/news/_test.php:11 [Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] Stack trace: [Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] #0 /home/sites/stopjunkmail.org.uk/public_html/news/_test.php(11): SimpleXMLElement->__construct('', 16384) [Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] #1 {main} [Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] thrown in /home/sites/stopjunkmail.org.uk/public_html/news/_test.php on line 11 After lots of trial and error and looking up similar questions I've found it's the feed that's causing the problem. If I change the feed to a very basic sample feel (for instance http://feedparser.org/docs/examples/rss20.xml) it all works fine. The feed I'm trying to parse is valid (though has some warnings). Question is... what do I need to do get the script to accept the feed? A: Change to utf8 using mb_convert_encoding() and don't forget to call the parseRSS() function. // Initialise the cURL resource handle: $ch = curl_init("http://www.blogs.stopjunkmail.org.uk/diary/index.php?/feeds/index.rss2"); // Set connection options: curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); // Execute connection, wait for response, and close: $data = curl_exec($ch); curl_close($ch); // Parse the data: $enc = mb_detect_encoding($data); $data = mb_convert_encoding($data, 'UTF-8', $enc); // Define the function to parse RSS: function parseRSS($doc) { echo '<ul>' . "\n"; for($i=0; $i<5; $i++) { $url = $doc->channel->item[$i]->link; $title = $doc->channel->item[$i]->title; $date = $doc->channel->item[$i]->pubDate; echo '<li>' . "\n"; echo '<a href="'.$url.'">'.$title.'</a>' . "\n"; echo '</li>' . "\n"; } echo '</ul>' . "\n"; } parseRSS($doc); ?> <!doctype html> <html lang="en-GB"> <head> <meta charset="UTF-8" /> <title>Test feed</title> </head> <body> A: Maybe another option to force the MIME type? curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/xml')); EDIT: Could also be a problem with cURL on your webserver compared to your local environment. If the PHP versions are different then that could be an issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determine winner print_r($scores); Array ( [Player 1] => 39 [Player 2] => 39 [Player 3] => 39 ) Lets say there are a variable amount of players in this array. What is the simplest way to calculate a winner or tie game? A: Determine the winning score, then get all players with the winning score: $max_score = max($scores); $winners = array_keys($scores, $max_score); A: Sort the array in reverse order: arsort($scores); arsort will sort the array in reverse order and maintain index associations. I am supposing that the winner will have most point, if it's the one with less points use instead asort(). The winner will be in position 0, ties will be in successive positions, if they have the same amount of points of the winner. A: Simplest: Use sort: http://php.net/manual/en/function.asort.php $sorted_array = asort($scores); The first item has the slowest score. Or use arsort, which sorts the other way round $sorted_array = arsort($scores); The first item has the highest score. See: http://php.net/manual/en/array.sorting.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7598124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detecting arrow keys input in C++ using curses on a unix platform is not working after calling a system command I have an application in which the user inputs data and needs to be able to move around the screen using the arrow keys. now I've used the curses library but I am having a problem detecting the arrows after calling a system command which is system("more filename); I've been able to detect them before calling this command. but afterwards, even after trying to turn the keypad on again using keypad(scrn, TRUE); it's not working. any suggestions? thank you:) A: Try the advice here: http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/misc.html#TEMPLEAVE Some times you may want to get back to cooked mode (normal line buffering mode) temporarily. In such a case you will first need to save the tty modes with a call to def_prog_mode() and then call endwin() to end the curses mode. This will leave you in the original tty mode. To get back to curses once you are done, call reset_prog_mode() . This function returns the tty to the state stored by def_prog_mode(). Then do refresh(), and you are back to the curses mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: File Not Found : maven-jaxb2-plugin i am trying to compile schema from an artifact(dependency) using jaxb2 plugin , i followed the topic: Compiling a schema from a Maven artifact in http://confluence.highsource.org/display/MJIIP/User+Guide#UserGuide-UsingcustomJAXB2plugins and the code i have is <plugin> <groupId>org.jvnet.jaxb2.maven2</groupId> <artifactId>maven-jaxb2-plugin</artifactId> <executions> <execution> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <forceRegenerate>true</forceRegenerate> <generatePackage>com.xxx.it.esp.subscription.schema</generatePackage> <generateDirectory>src/main/java/</generateDirectory> <!-- <schemas> <schema> <dependencyResource> <groupId>com.xxx.it.esp</groupId> <artifactId>esp-schemas</artifactId> <version>1.0-SNAPSHOT</version> <resource>index.xsd</resource> </dependencyResource> </schema> </schemas> </configuration> </plugin> Caused by: java.io.FileNotFoundException: JAR entry index.xsd not found in the jar esp-schemas-1.0-SNAPSHOT By the way index.xsd is under src/main/resources/schema/ folder and i tried giving the entire folder also but same error A: Please try <resource>schema/index.xsd</resource>. The resource is the path of XSD inside the JAR.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement search modes in Android Search Bar pattern? Android Search Bar pattern has a search mode selection drop down. Can anybody tell me how is it implemented? Any pointers to source code/examples would be great. I want code that works on Android 2.2+ devices. A: Ok then check this example How to Create QuickAction Dialog in Android and implement the same on your button click. A: The Greendroid library has Quick Actions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to search and replace globally, starting from the cursor position and wrapping around the end of file, in a single command invocation in Vim? When I search with the / Normal-mode command: /\vSEARCHTERM Vim starts the search from the cursor position and continues downwards, wrapping around to the top. However, when I search and replace using the :substitute command: :%s/\vBEFORE/AFTER/gc Vim starts at the top of the file, instead. Is there a way to make Vim perform search and replace starting from the cursor position and wrapping around to the top once it reaches the end? A: 1. It is not hard to achieve the behavior in question using a two-step substitution: :,$s/BEFORE/AFTER/gc|1,''-&& First, the substitution command is run for each line starting from the current one until the end of file: ,$s/BEFORE/AFTER/gc Then, that :substitute command is repeated with the same search pattern, replacement string, and flags, using the :& command (see :help :&): 1,''-&& The latter, however, performs the substitution on the range of lines from the first line of the file to the line where the previous context mark has been set, minus one. Since the first :substitute command stores the cursor position before starting actual replacements, the line addressed by '' is the line that was the current one before that substitution command was run. (The '' address refers to the ' pseudo-mark; see :help :range and :help '' for details.) Note that the second command (after the | command separator—see :help :bar) does not require any change when the pattern or flags are altered in the first one. 2. To save some typing, in order to bring up the skeleton of the above substitution command in the command line, one can define a Normal-mode mapping, like so: :noremap <leader>cs :,$s///gc\|1,''-&&<c-b><right><right><right><right> The trailing <c-b><right><right><right><right> part is necessary to move the cursor to the beginning of the command line (<c-b>) and then four characters to the right (<right> × 4), thus putting it between the first two slash signs, ready for the user to start typing the search pattern. Once the desired pattern and the replacement are ready, the resulting command can be run by pressing Enter. (One might consider having // instead of /// in the mapping above, if one prefers to type the pattern, then type the separating slash oneself, followed by the replacement string, instead of using the right arrow to move the cursor over an already present separating slash starting the replacement part.) A: % is a shortcut for 1,$ ( Vim help => :help :% equal to 1,$ (the entire file).) . is the cursor postion so you can do :.,$s/\vBEFORE/AFTER/gc To replace from the beginning of the document till the cursor :1,.s/\vBEFORE/AFTER/gc etc I strongly suggest you read the manual about range :help range as pretty much all commands work with a range. A: I've FINALLY come up with a solution to the fact that quitting the search wraps around to the beginning of the file without writing an enormous function... You wouldn't believe how long it took me to come up with this. Simply add a prompt whether to wrap: if the user presses q again, don't wrap. So basically, quit search by tapping qq instead of q! (And if you do want to wrap, just type y.) :,$s/BEFORE/AFTER/gce|echo 'Continue at beginning of file? (y/q)'|if getchar()!=113|1,''-&&|en I actually have this mapped to a hotkey. So, for example, if you want to search and replace every word under the cursor, starting from the current position, with q*: exe 'nno q* :,$s/\<<c-r>=expand("<cword>")<cr>\>//gce\|echo "Continue at beginning of file? (y/q)"\|if getchar()==121\|1,''''-&&\|en'.repeat('<left>',77) A: Here’s something very rough that addresses the concerns about wrapping the search around with the two-step approach (:,$s/BEFORE/AFTER/gc|1,''-&&) or with an intermediate “Continue at beginning of file?”-prompt approach: " Define a mapping that calls a command. nnoremap <Leader>e :Substitute/\v<<C-R>=expand('<cword>')<CR>>//<Left> " And that command calls a script-local function. command! -nargs=1 Substitute call s:Substitute(<q-args>) function! s:Substitute(patterns) if getregtype('s') != '' let l:register = getreg('s') endif normal! qs redir => l:replacements try execute ',$s' . a:patterns . 'gce#' catch /^Vim:Interrupt$/ return finally normal! q let l:transcript = getreg('s') if exists('l:register') call setreg('s', l:register) endif endtry redir END if len(l:replacements) > 0 " At least one instance of pattern was found. let l:last = strpart(l:transcript, len(l:transcript) - 1) " Note: type the literal <Esc> (^[) here with <C-v><Esc>: if l:last ==# 'l' || l:last ==# 'q' || l:last ==# '^[' " User bailed. return endif endif " Loop around to top of file and continue. " Avoid unwanted "Backwards range given, OK to swap (y/n)?" messages. if line("''") > 1 1,''-&&" endif endfunction This function uses a couple of hacks to check whether we should wrap around to the top: * *No wrapping if user pressed L, Q, or Esc, any of which indicate a desire to abort. *Detect that final key press by recording a macro into the s register and inspecting last character of it. *Avoid overwriting an existing macro by saving/restoring the s register. *If you are already recording a macro when using the command, all bets are off. *Tries to do the right thing with interrupts. *Avoids “backwards range” warnings with an explicit guard. A: You are already using a range, %, which is short hand for 1,$ meaning the entire file. To go from the current line to the end you use .,$. The period means current line and $ means the last line. So the command would be: :.,$s/\vBEFORE/AFTER/gc But the . or current line can be assumed therefore can be removed: :,$s/\vBEFORE/AFTER/gc For more help see :h range A: I am late to the party, but I relied too often on such late stackoverflow answerrs to not do it. I gathered hints on reddit and stackoverflow, and the best option is to use the \%>...c pattern in the search, which matches only after your cursor. That said, it also messes up the pattern for the next replacement step, and is hard to type. To counter those effects, a custom function must filter the search pattern afterwards, thus resetting it. See below. I have contended myself with a mapping that replaces the next occurence and jumps to the following after, and not more (was my goal anyway). I am sure, building on this, a global substitution can be worked out. Keep in mind when working on a solution aiming at something like :%s/.../.../g that the pattern below filters out matches in all lines left to the cursor position — but is cleaned up after the single substitution completes, so it loses that effect directly after, jumps to the next match and thus is able to run through all matches one by one. fun! g:CleanColFromPattern(prevPattern) return substitute(a:prevPattern, '\V\^\\%>\[0-9]\+c', '', '') endf nmap <F3>n m`:s/\%><C-r>=col(".")-1<CR>c<C-.r>=g:CleanColFromPattern(getreg("/"))<CR>/~/&<CR>:call setreg("/", g:CleanColFromPattern(getreg("/")))<CR>``n
{ "language": "en", "url": "https://stackoverflow.com/questions/7598133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "138" }
Q: How to read a file as a byte array in Scala I can find tons of examples but they seem to either rely mostly on Java libraries or just read characters/lines/etc. I just want to read in some file and get a byte array with scala libraries - can someone help me with that? A: The library scala.io.Source is problematic, DON'T USE IT in reading binary files. The error can be reproduced as instructed here: https://github.com/liufengyun/scala-bug In the file data.bin, it contains the hexidecimal 0xea, which is 11101010 in binary and should be converted to 234 in decimal. The main.scala file contain two ways to read the file: import scala.io._ import java.io._ object Main { def main(args: Array[String]) { val ss = Source.fromFile("data.bin") println("Scala:" + ss.next.toInt) ss.close val bis = new BufferedInputStream(new FileInputStream("data.bin")) println("Java:" + bis.read) bis.close } } When I run scala main.scala, the program outputs follows: Scala:205 Java:234 The Java library generates correct output, while the Scala library not. A: val is = new FileInputStream(fileName) val cnt = is.available val bytes = Array.ofDim[Byte](cnt) is.read(bytes) is.close() A: This should work (Scala 2.8): val bis = new BufferedInputStream(new FileInputStream(fileName)) val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray A: You might also consider using scalax.io: scalax.io.Resource.fromFile(fileName).byteArray A: You can use the Apache Commons Compress IOUtils import org.apache.commons.compress.utils.IOUtils val file = new File("data.bin") IOUtils.toByteArray(new FileInputStream(file)) A: Java 7: import java.nio.file.{Files, Paths} val byteArray = Files.readAllBytes(Paths.get("/path/to/file")) I believe this is the simplest way possible. Just leveraging existing tools here. NIO.2 is wonderful. A: Asynchronous File reading using Scala Future and Java NIO2 def readFile(path: Path)(implicit ec: ExecutionContext): Future[Array[Byte]] = { val p = Promise[Array[Byte]]() try { val channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ) val buffer = ByteBuffer.allocate(channel.size().toInt); channel.read(buffer, 0L, buffer, onComplete(channel, p)) } catch { case t: Exception => p.failure(t) } p.future } private def onComplete(channel: AsynchronousFileChannel, p: Promise[Array[Byte]]) = { new CompletionHandler[Integer, ByteBuffer]() { def completed(res: Integer, buffer: ByteBuffer): Unit = { p.complete(Try { buffer.array() }) } def failed(t: Throwable, buffer: ByteBuffer): Unit = { p.failure(t) } } } A: I have used below code to read a CSV file. import scala.io.StdIn.readLine import scala.io.Source.fromFile readFile("C:/users/xxxx/Downloads/", "39025968_ccccc_1009.csv") def readFile(loc :String,filenm :String): Unit ={ var flnm = fromFile(s"$loc$filenm") // Imported fromFile package println("Files testing") /*for (line <- flnm.getLines()) { printf("%4d %s\n", line.length, line) }*/ flnm.getLines().foreach(println) // getLines() is imported from readLines. flnm.close() }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "83" }
Q: Problems sharing CookieContainer between HttpWebRequests on Windows Phone 7 (Mango) I have a production app that makes two calls via HttpWebRequest. The first call sets a session and receives cookies back to maintain the session, the second call is for data from the api. The responses are httponly. I am using a shared CookieContainer between the two calls, but the second call always fails. I narrowed the problem down to the cookies not being sent in the second request. I've used Network Monitor to watch the traffic, and if I explicitly set the cookies in the second request (see code below), the call succeeds. Anybody have any ideas on this issue? I need to figure out how to get it to work with the shared CookieContainer. private string URL_01 = "https:// [...]"; private string URL_02 = "https:// [...]"; private CookieContainer _cookieContainer = new CookieContainer(); private NetworkCredential nc = new NetworkCredential("username", "password"); private void MainPage_Loaded(object sender, RoutedEventArgs e) { HttpWebRequest request = HttpWebRequest.CreateHttp(URL_01); request.CookieContainer = _cookieContainer; request.Credentials = nc; request.UseDefaultCredentials = false; request.BeginGetResponse(new AsyncCallback(HandleResponse), request); } public void HandleResponse(IAsyncResult result) { HttpWebRequest request = result.AsyncState as HttpWebRequest; if (request != null) { using (WebResponse response = request.EndGetResponse(result)) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string data = reader.ReadToEnd(); // gets returned data and deserializes it to an object SessionObject so = JsonConvert.DeserializeObject<SessionObject>(data); if (so.DeviceAPI.Session == "true") { // make a second call for the data HttpWebRequest requestData = HttpWebRequest.CreateHttp(URL_02); // when this is used, the call fails requestData.CookieContainer = _cookieContainer; // when this is used, the call works //requestData.Headers[HttpRequestHeader.Cookie] = "_key=value; _secret=value"; requestData.Credentials = nc; requestData.BeginGetResponse(new AsyncCallback(DataResponse), requestSongData); } } } } } public void DataResponse(IAsyncResult DataResult) { HttpWebRequest requestData = DataResult.AsyncState as HttpWebRequest; if (requestData != null) { using (WebResponse dataResponse = requestData.EndGetResponse(DataResult)) { using (StreamReader reader = new StreamReader(dataResponse.GetResponseStream())) { string data = reader.ReadToEnd(); // do something with the data } } } } } } A: This problem is a known issue with the CookieContainer when the domain name has no "www" on it. The CookieContainer is expecting a "www" and does not identify existing cookies for the domain. The work around was to read the cookies from the response headers and add them to any other requests. Was considered for a fix for Mango, but got pushed out. Jeff A: I had his issue and it seemed to be with using an old cookie container. Just create a new one by Iterating through the old one, and creating new cookies. Step 1. Create a dictionary to store cookies. //create a dictionary to store your persistent cookies public static Dictionary<string, Cookie> CookieCollection { get; set; } Step 2. Add the cookies you have stored, onto the webrequest before it's sent off. var request = WebRequest.Create(...); //add the cookies you have in your persistent cookie jar foreach (KeyValuePair<string, Cookie> cookie in _collection) { try { request.CookieContainer.Add(request.RequestUri, new Cookie(cookie.Value.Name, cookie.Value.Value)); } catch { } } Step 3. Saving the Cookies ResponseCallback(...) { //update your local cookie list as required foreach (Cookie clientcookie in response.Cookies) { if (!_collection.ContainsKey(clientcookie.Name)) _collection.Add(clientcookie.Name, clientcookie); else _collection[clientcookie.Name] = clientcookie; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: FullCalendar date & time handling I am using the FullCalendar script and am having trouble formatting the date/time of EVENTS on the calendar. I need all the events date/time data to look like: 2011-09-28 08:15:00 All the dates are like this in my JSON source, which display on the calendar correctly. However, if the event is moved or a new event is added (dropped by eternal dragging), the time format looks like: Fri Sep 30 2011 14:30:00 GMT-0400 (EDT) It doesn't DISPLAY in that format, but it appears this way when I try to insert the event.start or event.end into my database, or when I do this: eventClick: function(event) { alert("Event ID: " + event.id + " Start Date: " + event.start + " End Date: " + event.end); } I am using this only to see how the date & time are saved within the calendar. I need to update my database with new events, but in the format first shown above, but I am having trouble doing this. How do I use the formatDate function? I see it listed, and the reason I'm asking is because I don't know what to do with it. I did: $.fullCalendar.formatDate(event.start, 'MM-dd-yyyy'); but that doesn't do anything... A: what I did, is, first put it in a var, but only seemed to work in IE - FF still produced the IETF format (ex: "Wed, 18 Oct 2009 13:00:00 EST"): var formDate = $.fullCalendar.formatDate(event.start, 'MM-dd-yyyy'); alert(" Start Date: " + formDate); A: Just use the following code before you render your events: start=moment(start).format('YYYY/MM/DD hh:mm'); end=moment(end).format('YYYY/MM/DD hh:mm'); Make sure you are using moment.js. A: I have found your answer in a similar question, in here Answered by H.D: dateStr = "Tue Aug 13 2013 18:00:00 GMT-0400 (EDT)" (new Date(dateStr)).toISOString().slice(0, 10) It will display: '2013-08-13' (new Date(dateStr)).toISOString() It will display: '2013-08-13T18:00:00.000Z' A: I have used below code while rendering the event on calendar. Hope this code help you. eventRender: function(event, element) { eventsdate = moment(event.start).format('hh:mm a'); eventedate = moment(event.end).format('hh:mm a'); element.find('.fc-time').html(eventsdate + " - " + eventedate + "<br>"); } Make sure you are using moment.js A: Check out formatDate and parseDate and it'll probably solve your problems. A: Q : How do I use the formatDate function? I see it listed, the reason I'm asking is because I don't know what to do with it. I did: $.fullCalendar.formatDate(event.start, 'MM-dd-yyyy'); That doesn't do anything... Answer : You can use look likes : eventClick: function(event) { alert("Event ID: " + event.id + " Start Date: " + $.fullCalendar.formatDate(event.start, 'MM-dd-yyyy') + " End Date: " + event.end); } A: If you are trying to pass date object from java to full calendar and using Java 7 or lesser, below function will work for you. Date date= new Date("passyourdatestring"); date.toLocaleString(); And following will be the event object. { id: '_jobName' , url: 'url ', title: 'title', allDay: 'false', description: 'displayname', start': 'schedDateTime', end: date.toLocaleString() }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: SQL Server 2008 Multi-database Permissions via role or schema or scripting Let's say that there are multiple users in my office that need access to multiple databases that are dependent upon each other. I have users who are sysadmins but as more employees are added I want to be able to apply specific permissions for these new users who are not sysadmins but need owner level permissions on the specific databases without giving them permissions to modify other users. Instead of just adding each one manually I would like to either create a role that can be applied to the user and will give permissions on every database or create a schema that would give these permissions to the user on every database or create a script to give permissions to a user for every database. for example DB1 -sysadmin (contains user1, user2) -role1 (contains user3, user4) DB2 -sysadmin (contains user1, user2) -role1 (contains user3, user4) DB3 -sysadmin (contains user1, user2) -role1 (contains user3, user4) I want to add user3 and user4 to role1 one time and they will have permissions on all three databases (DB1, DB2, DB3). From my understanding this is basically a server level role, but from what I have read you are not allowed to create custom server level roles. Also as I understand it schemas are database level specific instead of server level specific (I can't group 3 databases into one schema and then add users to that schema). So does that leave me with scripting only or am I missing a way to do this with a role or schema? A: DECLARE @username varchar(50) = 'mynewuser' DECLARE @dbRole varchar(50) DECLARE @SQL varchar(max) DECLARE @DatabaseName varchar(MAX) DECLARE my_cursor CURSOR FOR SELECT CAST([Name] AS varchar(MAX)) AS databasename FROM sys.sysdatabases --only user databases WHERE DBID>4 AND [NAME] NOT LIKE '$' OPEN my_cursor WHILE 1=1 BEGIN FETCH NEXT FROM my_cursor INTO @DatabaseName IF @@FETCH_STATUS <> 0 BEGIN BREAK END SET @SQL = ' USE ' + @DatabaseName + '; IF NOT EXISTS( SELECT p.name FROM ' + @DatabaseName + '.sys.database_principals p WHERE p.name = ''' + @username + ''' ) BEGIN USE ' + @DatabaseName + '; CREATE USER ' + @username + ' FOR LOGIN ' + @username + ' EXEC sp_addrolemember ''db_owner'', ''' + @username + ''' END' EXECUTE(@SQL) END CLOSE my_cursor DEALLOCATE my_cursor
{ "language": "en", "url": "https://stackoverflow.com/questions/7598144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the minimum value between several columns I'm using SQL Server 2008; Suppose I have a table 'X' with columns 'Date1', 'Date2', 'Dateblah', all of type DateTime. I want to select the min value between the three columns, for example (simplified, with date mm/dd/yyyy) ID Date1 Date2 Dateblah 0 09/29/2011 09/20/2011 09/01/2011 1 01/01/2011 01/05/2011 03/03/2010 ID MinDate 0 09/01/2011 1 03/03/2010 Is there a bread and butter command to do that ? Thanks in advance. EDIT: I've seen this question What's the best way to select the minimum value from several columns? but unfortunately it won't suit me as I'm being obligated to do it against normalization because I'm making tfs work item reports, and the 'brute-force' case thing will end up being a pain if I have 6 ou 7 columns. A: based on scalar function (from Tom Hunter): SELECT ID, (SELECT MIN([date]) FROM (VALUES(Date1),(Date2),(Dateblah)) x([date])) MinDate FROM TableName A: There is no built in function to return the min/max of two (or more) columns. You could implement your own scalar function to do this. In SQL Server 2005+ you could use UNPIVOT to turn the columns into rows and then use the MIN function: CREATE TABLE [X] ( [ID] INT, [Date1] DATETIME, [Date2] DATETIME, [Date3] DATETIME ) INSERT [X] VALUES (0, '09/29/2011', '09/20/2011', '09/01/2011'), (1, '01/01/2011', '01/05/2011', '03/03/2010') SELECT [ID], MIN([Date]) AS [MinDate] FROM [X] UNPIVOT ( [Date] FOR d IN ([Date1] ,[Date2] ,[Date3]) ) unpvt GROUP BY [ID] A: Implementing a scalar function: CREATE FUNCTION [dbo].[MIN](@a SQL_VARIANT, @b SQL_VARIANT) RETURNS SQL_VARIANT AS BEGIN RETURN ( SELECT MIN([x]) FROM (VALUES(@a),(@b)) x([x]) ) END GO DECLARE @a DATETIME = '12 JUL 2011', @b DATETIME = '20 AUG 2011' SELECT [dbo].[MIN](@a, @b) DECLARE @c INT = 12, @d INT = 32 SELECT [dbo].[MIN](@c, @d) A: Simply lets say the table where your dates are is called sells and it has two date fields Date1 and Date2 from which you want the minimum. SELECT ( SELECT MIN([x]) FROM (VALUES(Date1),(Date2)) x([x]) ) as minimum FROM sells
{ "language": "en", "url": "https://stackoverflow.com/questions/7598150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Changing value of constant object with pointer There is such code: #include <iostream> int main(){ const int a = 2; int* ptr = (int*)&a; *ptr = 3; std::cout << &a << " " << ptr << " " << a << " " << *ptr << std::endl; return 0; } Result: 0xbf88d51c 0xbf88d51c 2 3 Why these two values differ? What does it here happen? A: int* ptr = (int*)&a; This is dangerous (this itself doesn't invoke UB, though). But this, *ptr = 3; This invokes undefined behavior (UB), because you're attempting to modify the const object pointing to by ptr. UB means anything could happen. Note that a is truly a const object. §7.1.5.1/4 (C++03) says, Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior. [Example: [...] const int* ciq = new const int (3); // initialized as required int* iq = const_cast<int*>(ciq); // cast required *iq = 4; // undefined: modifies a const object A: Don't do things like this. It's undefined behavior. If you lie to the compiler, it will get its revenge (c) A: I have a hypothesis that I have not tested: Compiler set aside an address for a (0xbf88d51c), and fills it with 2. int *ptr gets set to that address, and *ptr = 3 put 3 at that address. So *ptr now points to a 3. But when it comes across the value a, compiler hard codes the "2", as though you'd said #define a 2. One way to verify is to pull up the resulting assembly code. By the way, I know it's undefined behavior, but so what? The OP asking WHY it happens. A: That's because compiler replaces ... " " << a << " " ... with ... " " << 2 << " " .... It does so to avoid reading a's value from memory when it's already know, constant and can be added right to assembler instruction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Executing a Python Script From Python Shell I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py. I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter the Python shell. My goal is to be able to execute the python script amazon.py within this shell. What command should I be using to execute amazon.py? A: Normally, you just import the file and call a function within it: import APP.amazon APP.amazon.main() This would only work if amazon.py is laid out like this: def main(): ...code... if __name__ == '__main__': main() Also, in the directory ~/PROJECT/APP there needs to exist a file __init__.py with nothing in it, or else Python won't see APP as a package with the module amazon in it. Disclaimer: I don't actually know what manage.py does. A: Normally a script is "executed" upon import. I'd suggest you wrap your functionality in amazon.py in a function: def call_functionality(): ... In your shell you can now import it with: import path.to.amazon as amazon and then execute it by amazon.call_functionality()
{ "language": "en", "url": "https://stackoverflow.com/questions/7598159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get the form values when i click on submit in sencha touch i new to sencha touch,and i created a login form which accepts user id and password and a login button,so when i click on login button i should get the user id value as a alert.and the code is, Ext.setup ({ onReady: function () { var myform=new Ext.form.FormPanel({ id:'form', fullscreen:true, standardSubmit:true, dockedItems:[{ Dock:'top', xtype:'toolbar', height:40, title:'Tool Bar', id:'login', } ], items:[{ xtype:'textfield', name:'id', width:'50%', align:'center', label:'User Id' }, { xtype:'textfield', name:'pwd', id:'pwd', width:'50%', align:'center', label:'Password' }, { xtype:'button', ui:'round', width:'50%', text:'Login', align:'center', handler:function() { gettingvalues();/* var fields = form.getValues(); console.log(fields['name']); */ } } ], }); gettingvalues=function() { var fields=myform.getValues(); Ext.Msg.alert(fields['id'].getValue()); } } }); But am not getting any value in alert,what i have to do. and after that i want to send those values to our local server which requires id and password,it will be in the format of... oururl?action=login&id=xyz&pwd=xyz, in this it will accepts and returns the response,so for that what i have to write, please let me know as soon as possible. Thanks in advance. A: You can get form values via their name attribute, like this: { xtype:'button', ui:'round', width:'50%', text:'Login', align:'center', handler:function() { var form = myForm.getValues(); console.log('Form Object: ' + form); console.log('User ID Field: ' + form.id); console.log('Password Field: ' + form.pwd); } } A: have you tried: var fields=myform.getValues(); Ext.Msg.alert(fields['id']); do you get any javascript errors?
{ "language": "en", "url": "https://stackoverflow.com/questions/7598163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the purpose of this JS pattern? I am looking through someone else's code and I see this pattern being applied: var MyObj = function(){ this._myHiMember = this.assignHi(); }; MyObj.prototype = { assignHi : function(){ return 'hi, ppl';} }; What is the purpose of creating a reference on the instance to the method on the prototype? A: Properties of the prototype object are defined once but inherited by all instances which reference it. The document here has a good treatise on the subject. Could it be this fact the original programmer is trying to take advantage of? A: If a function is declared as part of the prototype then only one copy of that function is created. If you create it in the constructor you create a new copy for every instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to run Java programs from the terminal? I am trying to run a Java program from my Terminal. I have Mac OS X 10.7. teamL javac -jar kxml2-2.3.0.jar XMLHandler.java ServiceEndpoint.java TeamL.java This is my Eclipse class file structure: I am not able to find why is this throwing Unable to access jarfile kxml2-2.3.0.jar? A: If you are referencing any external libraries, then you have to add them to the classpath. You can add it during compilation of the classes this way. Go to the src directory and : javac -classpath ".:<path_to_jar_file>" teamL/*.java TO execute : java -cp ".:<path_to_jar_file>" teamL.<class_name> if your are using eclipse, then go to <project_directory>/bin/ here you can find the compiled classes (so you dont have to compile them) and directly run them using the above java command Note: Since your classes are packaged under teamL package, you have to run the classes from outside the package by specifying the fully qualified name like teamL.ServiceEndpoint A: Have you added that jar to the classpath when you execute the program on the command line? e.g. java -classpath location_of_jar ... A: javac is a command to compile instead of that you should use the command Java. * *First set the classpath *Then run it like this java -classpath %classpathVariable% %YourClass% %arguments... Running a Java Program from Command Prompt this could give you a better idea is for Windows but is similar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: error insert DateTime c# type to SQL DateTime column i am trying to make INSERT command to my SQLEXPRESS db and recieve error while trying to enter a value to my DateTime column. this is the sql command i use: SqlDateTime sTime = new SqlDateTime(book.PublishedDate); string sql = string.Format("Insert into Books" + "(Name, PublishDate, IsInternal) Values" + "('{0}', '{1}', '{2}')", book.Name, sTime.Value, book.IsInternal); book.PublishedDate - is DateTime type and the PublishedDate column is sql DateTime i recieve the following error: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. how can i resolve that ? A: Use parametrised queries. They're supported in practically any data access technology you might be using. And they allow you to keep treating dates as dates, instead of converting everything into strings. E.g. (ADO.Net SqlCommand) SqlCommand cmd = new SqlCommand("Insert into Books (Name,PublishDate,IsInternal) Values (@Name,@PublishDate,@IsInternal)"); cmd.Parameters.Add(new SqlParameter("@Name", System.Data.SqlDbType.VarChar, 50)); cmd.Parameters.Add(new SqlParameter("@PublishDate", System.Data.SqlDbType.DateTime)); cmd.Parameters.Add(new SqlParameter("@IsInternal", System.Data.SqlDbType.Bit)); cmd.Parameters["@Name"].Value = book.Name; cmd.Parameters["@PublishDate"].Value = book.PublishedDate; cmd.Parameters["@IsInternal"].Value = book.IsInternal; The single largest source of errors people make when they report datatype issues between their client code and an SQL database is where, for whatever reason, they've converted everything to strings. Not only is this usually less efficient, but you're also relying on at least two conversions to happen correctly in between (Type -> string and string -> Type), and frequently at least one of those conversions will be left to whatever the default conversion function(s) are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }