text
stringlengths
8
267k
meta
dict
Q: compare lists in Haskell I've been trying to compare two lists in Haskell and found an answer here. I wonder how all (flip elem listx) input works, especially for the role flip plays here. When I take out flip it won't work anymore. A: * *flip elem listx is equivalent to (flip elem) listx. *(flip elem) is the same as elem, but with the arguments in opposite order. This is what flip does. *elem is a function that takes an element and a list, and checks whether the element belongs to the list. *So flip elem is a function that that takes a list and an element, and checks whether the element belongs to the list. *Therefore flip elem listx is a function that that takes an element, and checks whether the element belongs to listx. *Now all takes a predicate and a list, and checks whether all elements of the list satisfy the predicate. *all (flip elem listx) take a list, and checks whether all elements of the list satisfy flip elem listx. That is, whether they all belong to listx. *all (flip elem listx) input checks whether all elements of input belong to listx. *Q.E.D.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSF provide very basic REST get method Is there a way to have a doGet method in a @ManagedBean and define a URL on which this bean will react. I am using JSF and want to provide a really basic feed, but for this I need to react on a get request. I wrote it with normal servlets first, but now I noticed that I need information from another ManagedBean therefore I need a @ManagedProperty - hence JSF... My questions: * *Is there a URLPattern annotation or similar? *Is there a doGet method that is similar to the Servlet's doGet? A: If you want a RESTful web service, use JAX-RS (e.g. Jersey) instead of JSF. Or, if you just want "pretty" (REST-like) URLs for JSF, use PrettyFaces. A: Assuming servlets... If you're relying on the JSF context, the trick will be to get the FacesServlet to execute the code. The FacesServlet is responsible for creating and destroying the request context. Here is the managed bean we want to invoke: @ManagedBean @RequestScoped public class Restlike { public void respond() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext ext = context.getExternalContext(); HttpServletResponse response = (HttpServletResponse) ext.getResponse(); response.setContentType("text/plain; charset=UTF-8"); try { PrintWriter pw = response.getWriter(); pw.print("Hello, World!"); } catch (IOException ex) { throw new FacesException(ex); } context.responseComplete(); } } Here is the placeholder view that will execute the code. resty.xhtml: <?xml version='1.0' encoding='UTF-8' ?> <metadata xmlns="http://java.sun.com/jsf/core"> <event type="preRenderView" listener="#{restlike.respond}"/> </metadata> Hitting resty.faces doesn't look very RESTful, but it is trivial to handle with a filter: @WebFilter("/rest/*") public class RestyFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.getRequestDispatcher("/resty.faces").forward(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void destroy() {} } The resultant URL will look something like http://host/context/rest This solution is a bit of a hack and only applicable to servlet environments. A better approach might be to add a custom ResourceHandler but I haven't spent much time investigating that part of the API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Entity Framework 4.1 Persisting a getter Lots of Like for EF4.1, but have got stuck on doing this! I want to end up with a class like this, where EF handles both properties, and they are both in the database. public class myClass { public int priority { get; set; } public string status { get { return priority > 10 ? "Low" : "High" } } } 1) When I generate the model from the database, I need to somehow inject the status calculation into its property. 2) Hopefully the solution works when I regenerate my model from the database. A: You cannot persist such property. It is business logic (computed property). If you want to save it the property must have setter because EF will try to set it when materializing entity loaded from the database but once you expose a setter your getter will not make sense and this logic will have to be moved elsewhere. Edit: The workaround is to wrap your Status logic into helper extension method: public static IsHighPriority(this IQueryable<MyClass> query) { return query.Where(x => x.Priority > 10); } Now you can use it in the query like: var query = from x in context.MyClasses.IsHighPriority() where ... select x;
{ "language": "en", "url": "https://stackoverflow.com/questions/7619225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IplImage exists memory leak after cvReleaseImage IplImage* psrcImage = cvLoadImage("E:\\ImageDataBase\\image_905\\manualExtract\\3.jpg") ; cvReleaseImage( &psrcImage); For instance, before loading image, memory is 700k. After load and release, memory is 730k. What's the reason? We need to process millions of images, the app will break down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework code first relationships and navigation property? i have the following classes public class Subject{ public int SubjectId { get; set; } public String SubjectName { get; set; } public String SubjectCategory { get; set; } } public class QuestionDescriptor { public int QuestionDescriptorId { get; set; } public String QuestionText { get; set; } public String Answer { get; set; } public int SubjectId { get; set; } public virtual Subject Subject { get; set; } } i have configured it using the following code ,i want that a Subject can have many QuestionDescriptors modelBuilder.Entity<QuestionDescriptor>() .HasRequired(qd => qd.Subject) .WithMany() .HasForeignKey(qd => qd.SubjectId) .WillCascadeOnDelete(true); Now i have the following question * *have i done it correctly ? *do i need a navigation property in the Subject class? *what happems if i do this public class Subject { public int SubjectId { get; set; } public String SubjectName { get; set; } public String SubjectCategory { get; set; } public int QuestionDescriptorId {get;set;} public virtual QuestionDescriptor {get;set;} } *if i do the above what changes do i need in the configuration and why? *if i want all the questions belonging to a particular subject then i can get them by querying the QuestionDescriptor ,why then do i need a bi-directional property ? A: 1) have i done it correctly ? Yes. 2) do i need a navigation property in the Subject class? No. You don't need it. It can be helpful for certain queries but it is not required. 3) what happems if i do this ... That's another relationship. It would represent a one-to-one relationship. But because you want a one-to-many relationship you must have a navigation collection on your entity: public class Subject { public int SubjectId { get; set; } public String SubjectName { get; set; } public String SubjectCategory { get; set; } public virtual ICollection<QuestionDescriptor> Descriptors {get;set;} } 4) if i do the above what changes do i need in the configuration and why? For the change above you can leave you mapping configuration as it is - with the only exception that you now must specify the collection as the other side of the relationship. Instead of .WithMany() you use .WithMany(s => s.Descriptors) 5) if i want all the questions belonging to a particular subject then i can get them by querying the QuestionDescriptor ,why then do i need a bi-directional property ? You don't need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I optimize this code by using SENDER? I have a form that contains 16 TCheckBox and 32 TEditBox. Every 2 TEditBox en-ability is depending of the checkBox state. so I uses this code which is too long: //T1 procedure TOFAddForm.T1Click(Sender: TObject); begin Q1.Enabled:=T1.Checked; P1.Enabled:=T1.Checked; Q1.OnChange(Sender); end; . . . //T16 procedure TOFAddForm.T16Click(Sender: TObject); begin Q16.Enabled:=T16.Checked; P16.Enabled:=T16.Checked; Q1.OnChange(Sender); end;` I used this code but nothing happen: procedure TOFAddForm.T1Click(Sender: TObject); var Q, P: TEdit; begin with Sender as TCheckBox do begin Q.Name:='Q'+copy(Name,1,2); P.Name:='P'+Copy(Name,1,2); Q.Enabled:=Checked; P.Enabled:=Checked; end; Q1.OnChange(Sender); end; thank you. A: If all the checkboxes and edits are consistently named, you can add this OnClick event to all checkboxes: procedure TOFAddForm.TClick(Sender: TObject); var C: TCheckBox; Q, P: TEdit; N: string; begin C := Sender as TCheckBox; N := Copy(C.Name, 2, Length(C.Name)); Q := FindComponent('Q' + N) as TEdit; P := FindComponent('P' + N) as TEdit; Q.Enabled := C.Checked; P.Enabled := C.Checked; Q.OnChange(Sender); end; A: I suggest you store the TEdit pointers into an array and then use the TCheckBox.Tag property as an index into the array, eg: var Edits: array[0..15, 0..1] of TEdit; procedure TOFAddForm.FormCreate(Sender: TObject); var K: Integer; begin for k := 0 to 15 do begin Edits[k, 0] := FindComponent('Q' + IntToStr(k+1)) as TEdit; Edits[k, 1] := FindComponent('P' + IntToStr(k+1)) as TEdit; (FindComponent('T' + IntToStr(k+1)) as TCheckBox).Tag := k; end; procedure TOFAddForm.T1Click(Sender: TObject); begin with Sender as TCheckBox do begin Edits[Tag, 0].Enabled := Checked; Edits[Tag, 1].Enabled := Checked; Edits[Tag, 0].OnChange(Sender); end; end; A: I would strongly advise in cases like this to create the controls yourself. In the OnCreate event handler, call TEdit.Create(Self), store the object reference in a data structure you manage yourself, e.g. a dynamic array, set properties like Parent, SetBounds and eventhandlers, and look-up Sender in your collection of object references (optionally depending on the value of Tag), this is almost always more performant than using FindComponent. Added bonusses are you can alter the number of repeating controls easily (even make it dynamic at run-time!) and the dfm-code (which is embedded into the final executable) contains less almost-identical repeating data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ubuntu 11.04: Installing GCC 4.4.6 I am trying to install GCC 4.4.6 on Ubuntu 11.04 64 bit and having some trouble. As the package does not ship with this distribution I try to build it from source. It needs GMP and MPFR which I installed from the package system. I am using distinct source, build and install directories as advised. Target=build=host. Except --prefix I do not give any configure options: gcc-4.4.6/configure --prefix=[absolute_path]/install/gcc-4.4.6 These environment variables are also used: CXX=/usr/bin/g++-4.4 CC=/usr/bin/gcc-4.4 since (gcc and g++ default to 4.5 which is also installed) make produces the following error (it seems after the bootstrap compiler was built) when it comes to compile gcc-4.4.6/libgcc/../gcc/libgcc2.c /usr/include/gnu/stubs.h:7:27: error: gnu/stubs-32.h: No such file or directory The filename might suggest that this is a 64/32 bit issue. Is there something to consider when building GCC on a 64 bit machine? The config.log says: uname -m = x86_64 uname -r = 2.6.38-11-generic uname -s = Linux uname -v = #50-Ubuntu SMP Mon Sep 12 21:17:25 UTC 2011 /usr/bin/uname -p = unknown /bin/uname -X = unknown /bin/arch = unknown /usr/bin/arch -k = unknown /usr/convex/getsysinfo = unknown hostinfo = unknown /bin/machine = unknown /usr/bin/oslevel = unknown /bin/universe = unknown PATH: /usr/local/sbin PATH: /usr/local/bin PATH: /usr/sbin PATH: /usr/bin PATH: /sbin PATH: /bin ----------- Core tests. ----------- configure:1563: checking build system type configure:1581: result: x86_64-unknown-linux-gnu configure:1616: checking host system type configure:1630: result: x86_64-unknown-linux-gnu configure:1638: checking target system type configure:1652: result: x86_64-unknown-linux-gnu configure:1696: checking for a BSD-compatible install configure:1762: result: /usr/bin/install -c configure:1773: checking whether ln works configure:1795: result: yes configure:1799: checking whether ln -s works configure:1803: result: yes configure:3002: checking for gcc configure:3028: result: /usr/bin/gcc-4.4 configure:3274: checking for C compiler version configure:3277: /usr/bin/gcc-4.4 --version &5 gcc-4.4 (Ubuntu/Linaro 4.4.5-15ubuntu1) 4.4.5 Copyright (C) 2010 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. A: The problem is a missing package: "libc6-dev-i386" apt-file update apt-file search stubs-32.h libc6-dev-i386: /usr/include/gnu/stubs-32.h apt-get install libc6-dev-i386 That solves it!
{ "language": "en", "url": "https://stackoverflow.com/questions/7619236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP.NET Forms Authentication Cookie and Sessions for additional data Application Background Security: The applications are all hosted on a private extranet (and / or a local intranet - depending on the installation instance). So while security is important, it's not as important as if it were an application on the intranet. However saying that it is important that the system cannot be easily be hacked or hijacked. The apps: The application comes in 2 parts:- * *Class Library (dll) *Authentication Front-end ASP.NET application The dll is part of the front-end authentication application, and is to be added to other applications ("consumer apps") that require users to be authenticated. The authentication app is a central store of all users, applications they have access to and permissions levels based on their username. For consumer apps that have the dll installed, when an end-user hits a page that requires them to be logged in, the consumer app fires them off to the authentication application login.aspx page along with the appid, the user logs in, if they have required permissions then the auth app, sends them back to the consumer app (via a form with encrypted data) - which includes basic data about who the user is, username, realname, job role, organisation etc... and importantly a list of their permission levels for the consumer app. The consumer app then takes that data, and processes it, decrypts it etc.. and creates a forms authentication cookie & populates a user class, and user roles class - this is all done from within the dll itself. The Problem Now this all works great, and initially all the data was stored in the authentication cookie, in the userdata part of the cookie, however here's the issue.... A consumer app (and there is one central one that we has been written in-house, can have lots of permissions (user roles) associated with a single user (mainly application administrators) and so we need something that can hold lots of data, more than the 4KBs that the authentication cookie can hold. So I've attempted to put this into Session variables, well initially a single variable with all the sent over decrypted data into a single session variable called "userdata". Which I then check when a requested is made. However... The first issue I had was that the authentication cookie seems to have a longer life-span than the Session does, I think I've fixed this by extending the session to 35 minutes (5 minutes longer than the AuthCookie). But when the consumer app programmer makes changes to their code (running localhost in debug via Visual Studio 2010) and refreshes the browser, the AuthCookie remains but the Session disappears. Now initially I'm using the default InProc session mode, which I guess could be the issue. Is my assumption correct? And is there a way of programmatically syncing the session and the AuthCookie? Any other advice on solving this issue? A: Every time your application refreshes (This is happening when you are changing the code likely), but could happen on the server for various reasons, your user sessions are going to be cleared out. What you most likely want to do if, I'm reading this correctly, is checking for the existence of the cookie in Session_Start, and refreshing the Session Data so that it gets loaded back into the session. The session isn't the most stable thing in the world, and even the Session Timeout isn't always what you think it is. If you don't already have one, add a Global.asax to your project. If it's c#, edit the Global.asax.cs, or VB, I think it's Global.asax.vb. protected void Session_Start(object sender, EventArgs e) { // Check for Cookie, if it exists here, then load data into the session here. }
{ "language": "en", "url": "https://stackoverflow.com/questions/7619239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C program under Linux: how to find out if another program is running My C program running under Linux wants to find out, by name, if another program is running. How to do it? A: There are two ways basically: * *Use popen("pgrep yourproc", "r"); and then fgets from it *Use opendir and readdir to parse /proc - this is basically what ps(1) does Not the cleanest but I would go with the first of these. A: Travesing /proc really isn't much harder than popen(). Essentially you do 3 things * *Open all number formatted /proc entries. *Get the command invocation through /proc/<PID>/command/ *Perform a regex match for the name of the processs you want. I've omitted some error handling for clarity, but It should do something like what you want. int main() { regex_t number; regex_t name; regcomp(&number, "^[0-9]+$", 0); regcomp(&name, "<process name>", 0); chdir("/proc"); DIR* proc = opendir("/proc"); struct dirent *dp; while(dp = readdir(proc)){ if(regexec(&number, dp->d_name, 0, 0, 0)==0){ chdir(dp->d_name); char buf[4096]; int fd = open("cmdline", O_RDONLY); buf[read(fd, buf, (sizeof buf)-1)] = '\0'; if(regexec(&name, buf, 0, 0, 0)==0) printf("process found: %s\n", buf); close(fd); chdir(".."); } } closedir(proc); return 0; } A: In unix, programs do not run. Processes run. A process can be viewed as an instance of a program. A process can operate under another name or change its name, or have no name at all. Also, at the time of running, the program can even have ceased to exits (on disk) and only exist in core. Take for instance the following program: (is /dev/null actually running? I don't think so ...) #include <unistd.h> #include <string.h> int main(int arc, char **argv) { if (strcmp(argv[0], "/dev/null") ) { execl( argv[0], "/dev/null", NULL ); } sleep (30); return 0; } A: If you want to look at the 'right' way to do this, check out the following: Linux API to list running processes?
{ "language": "en", "url": "https://stackoverflow.com/questions/7619241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Maps API change view when options menu button was pressed? Im trying to make the view change from traffic to satelite when a button in my options menu is pressed but its not working.. Here is my code: Here is my onCrete public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Adding features for the map mainMap = (MapView)findViewById(R.id.mvMain); mainMap.setBuiltInZoomControls(true); //THESE I WILL USE!!! //mainMap.setSatellite(true); mainMap.setTraffic(true); mapViewControll = true; mapController = mainMap.getController(); } here is my onoptionItemSelected public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ //Change View case R.id.changeView: if(mapViewControll = false){ mainMap.setSatellite(true); } else{ mainMap.setTraffic(true); } break; //Help case R.id.help: break; } return super.onOptionsItemSelected(item); } I did set the mapViewControll boolean to true at the top of the code.. What can be a problem here?? A: Try calling invalidate() method on map view at end. A: Forgot to put mainMap.setTraffic(false); and vice versa in the onoptionItemSelected method
{ "language": "en", "url": "https://stackoverflow.com/questions/7619242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simulink example ideas I am putting together a workshop on Simulink. I expect that most of the attendees will be sophomore undergrads or older. I expect that most of the attendees will be in a bachelor's program for electrical or mechanical engineering or computer science. I need to think of good example problems to solve during the workshop. These are problems that I will present and solve in Simulink in front of the audience. I will also provide a .zip afterwards containing problem statements and solutions. What types of problems should I use? I have a few ideas already: * *PID controller for cruise control (appeal to EEs) *Spring/damper system (appeal to MEs) *Solar incidence calculator for rotating bodies in low-earth orbit, integrate into SolidWorks for thermal analysis (appeal to MEs) Particularly, I don't know what I can show that will appeal to a CS major. Also, I would like to minimize the number of examples by starting with something simple and progressing rapidly into advanced territory (i.e. simple and advanced examples welcome). A: Interesting CS major to Simulink will indeed be more difficult. Some ideas: * *State machine (Stateflow), *Code generation, *Integration of legacy C code into a S-function, They can be include in one of your other example. A: First of all, it sounds like a very interesting workshop, and good luck! I agree with Clement that a problem using Stateflow would probably appeal to CS majors. You could model something like a transmission using Stateflow. Another approach for CS majors might be investigating how the various optimizations in Simulink affect the generated C code. Check out the documentation for the optimizations for some examples, you could use block reduction, signal storage reuse, loop threshold, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google map GET error? I have installed Google map in my site and when my page load I get the error. GET xdc._uqt0ll&token=129509">http://maps.googleapis.com/maps/api/js/AuthenticationService.Authenticate?1shttp%3A%2F%2Fwww.mysite_here.ext%2F&callback=xdc._uqt0ll&token=129509 403 (Forbidden) AuthenticationService.Authenticate Is there anyone who know what that's mean or how can I solve it ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7619249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to call method on previous page? is there any way to call method or set propery of the previous page in the stack? Say I started a thread in the A page, then navigated to page B, now my application is going to be deactivated and I want to take care of the thread started in the page A, I want to call a method of A that will save thread job's some parameters. Thank you. A: You cannot call a method on a previous page. You should be deactivating the thread when you leave page A. If that doesn't work for your application, then the thread is an application-level feature and should be created/deactivated in Application class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find all active sessions of gmail and facebook accounts? After some research I found out a way to check all the active sessions of gmail and face book manually. Is there are APIs to get details of these accounts an sign them out? A: I don't know of any APIs, but that doesn't mean you couldn't get the same functionality by screen-scraping the sites. Without an API, however, your code is subject to potential breakage whenever Facebook or Google update their web apps. Facebook For facebook, you could screen-scrape the URL https://www.facebook.com/settings?tab=security&section=sessions&t. Also investigate the URL https://www.facebook.com/ajax/settings/security/sessions/stop.php?__a=1, which is the URL accessed in the background when you click the "End Activity" link. GMail Google's seems to be a little more complex, but if you screen-scrape https://mail.google.com/mail/h/ (the plain-html interface), find and follow the "Details" link at the bottom, you may be able to automatically log sessions out that way too. A: For Google I found another article that made this easy. google account logout and redirect As for Facebook they have the fb API you can get in JavaScript and php. These will allow you to control the currently logged in user account. There are log-out functions for the user as well. However digging around in the account is difficult to do because your domain can't see the data for that user without being authorized by both Facebook and the user. Dig around here if you want to deal with facebook data and access. https://developers.facebook.com/ Open graph is fairly easy to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Most useful Asp.net MVC 3 Library every programmer shoud have? I was was wondering that which are the most useful, easy to integrate, easy to code and powerful libraries available in the market (Free, Paid) that every MVC programmer should use to achieve the ultimate goal "Write Less, DO More" I am currently using Auto-Mapper, Structure-Map, Jquery. Please list yours so that every beginner like me can benefits from your answer. Every piece of your answers would be appreciated and it deserve the vote up. A: jQuery: The Write Less, Do More, JavaScript Library PM> Install-Package jQuery Wouldn't forgive myself this not being first one Following the write less do more principle, I could add * *MvcContrib lots of community html helpers *Cassette (aka Knapsack) - script and stylesheet reference helper library(with script dependency inspection, version control, single place output(in master file), minification, etc) *FluentValidation - when it comes to defining validation. Clear, fluent code with separate, reusable, configurable validators. Excellent support of asp.net mvc3 A: This is a very subjective question, however Nuget keeps a track of packages downloaded here: http://stats.nuget.org/#downloads if you are just looking for popularity stats. A: I don't like the UI abstraction that a library is putting on ASP.NET MVC but TelerikMvcExtensions fits your description : http://nuget.org/List/Packages/TelerikMvcExtensions However, IMO, if you like to have more Write Less, DO More approach, use ASP.NET Web Forms. Sometimes you don't need to write anything, just clicking and you are done. (which I don't like) A: I prefer powerful MVC Extensions from DevExpress vendor. Product Page: http://www.devexpress.com/Products/NET/Controls/ASP/MVC/ Demo Page: http://mvc.devexpress.com/ Download Page: https://www.devexpress.com/ClientCenter/Downloads/#Trials A: Sitemaps can be a bit tricky in MVC so take a look at MVCSitemapProvider http://mvcsitemap.codeplex.com ELMAH takes a lot of effort out of your error handling and logging http://code.google.com/p/elmah/ It's got a bit of a learning curve but KnockOutJS can fit quite well with MVC http://knockoutjs.com And not quite "write less" but definitely "do more" take a look at EF Code First http://nuget.org/List/Packages/EFCodeFirst/1.1
{ "language": "en", "url": "https://stackoverflow.com/questions/7619254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: AS3 line of sight without using hittest object. I'm working on a game project, and I am working on the AI aspect of the game. I want the enemy objects to start aiming and shooting at the player when they are in sight of the enemy, and i came across this article on a way to do that: http://www.emanueleferonato.com/2007/04/29/create-a-flash-game-like-security-part-2/ my question is can you do this same thing without using an actual line? can you for instance use a hit test point and basically define a line? or some other way of doing it without actually putting an object on the stage. I am trying to make things as efficient as possible and don't want to use this approach if possible. if you have some advice, or code or links to a helpful resource I would greatly appreciate that! A: Just use the calculations, but not the line This is the important code dist_x = _root.hero._x-_x; dist_y = _root.hero._y-_y; dist = Math.sqrt(dist_x*dist_x+dist_y*dist_y); angle = Math.atan(dist_y/dist_x)/(Math.PI/180); if (dist_x<0) { angle += 180; } if (dist_x>=0 && dist_y<0) { angle += 360; } wall_collision = 0; for (x=1; x<=dist; x++) { point_x = _x+x*Math.cos(angle*Math.PI/180); point_y = _y+x*Math.sin(angle*Math.PI/180); if (_root.wall.hitTest(point_x, point_y, true)) { wall_collision = 100; break; } } if wall_collision = 100, the player is in sight of the cop. I'd just use a Boolean for this though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple Python Processes slow I have a python script which goes off and makes a number of HTTP and urllib requests to various domains. We have a huge amount of domains to processes and need to do this as quickly as possible. As HTTP requests are slow (i.e. they could time out of there is no website on the domain) I run a number of the scripts at any one time feeding them from a domains list in the database. The problem I see is over a period of time (a few hours to 24 hours) the scripts all start to slow down and ps -al shows they are sleeping. The servers are very powerful (8 cores, 72GB ram, 6TB Raid 6 etc etc 80MB 2:1 connection) and are never maxed out, i.e. Free -m shows -/+ buffers/cache: 61157 11337 Swap: 4510 195 4315 Top shows between 80-90% idle sar -d shows average 5.3% util and more interestingly iptraf starts off at around 50-60MB/s and ends up 8-10MB/s after about 4 hours. I am currently running around 500 versions of the script on each server (2 servers) and they both show the same problem. ps -al shows that most of the python scripts are sleeping which I don't understand why for instance: 0 S 0 28668 2987 0 80 0 - 71003 sk_wai pts/2 00:00:03 python 0 S 0 28669 2987 0 80 0 - 71619 inet_s pts/2 00:00:31 python 0 S 0 28670 2987 0 80 0 - 70947 sk_wai pts/2 00:00:07 python 0 S 0 28671 2987 0 80 0 - 71609 poll_s pts/2 00:00:29 python 0 S 0 28672 2987 0 80 0 - 71944 poll_s pts/2 00:00:31 python 0 S 0 28673 2987 0 80 0 - 71606 poll_s pts/2 00:00:26 python 0 S 0 28674 2987 0 80 0 - 71425 poll_s pts/2 00:00:20 python 0 S 0 28675 2987 0 80 0 - 70964 sk_wai pts/2 00:00:01 python 0 S 0 28676 2987 0 80 0 - 71205 inet_s pts/2 00:00:19 python 0 S 0 28677 2987 0 80 0 - 71610 inet_s pts/2 00:00:21 python 0 S 0 28678 2987 0 80 0 - 71491 inet_s pts/2 00:00:22 python There is no sleep state in the script that gets executed so I can't understand why ps -al shows most of them asleep and why they should get slower and slower making less IP requests over time when CPU, memory, disk access and bandwidth are all available in abundance. If anyone could help I would be very grateful. EDIT: The code is massive as I am using exceptions through it to catch diagnostics about the domain, i.e. reasons I can't connect. Will post the code somewhere if needed, but the fundamental calls via HTTPLib and URLLib are straight off the python examples. More info: Both quota -u mysql quota -u root come back with nothing nlimit -n comes back with 1024 have change limit.conf to allow mysql to allow 16000 soft and hard connections and am able to running over 2000 script so far but still still the problem. SOME PROGRESS Ok, so I have changed all the limits for the user, ensured all sockets are closed (they were not) and although things are better, I am still getting a slow down although not as bad. Interestingly I have also noticed some memory leak - the scripts use more and more memory the longer they run, however I am not sure what is causing this. I store output data in a string and then print it to the terminal after every iteration, I do clear the string at the end too but could the ever increasing memory be down to the terminal storing all the output? Edit: No seems not - ran up 30 scripts without outputting to terminal and still the same leak. I'm not using anything clever (just strings, HTTPlib and URLLib) - wonder if there are any issues with the python mysql connector...? A: Check the ulimit and quota for the box and the user running the scripts. /etc/security/limits.conf may also contain resource restrictions that you might want to modify. ulimit -n will show the max number of open file descriptors allowed. * *Might this have been exceeded with all of the open sockets? *Is the script closing each sockets when it's done with it? You can also check the fd's with ls -l /proc/[PID]/fd/ where [PID] is the process id of one of the scripts. Would need to see some code to tell what's really going on.. Edit (Importing comments and more troubleshooting ideas): Can you show the code where your opening and closing the connections?When just run a few script processes are running, do they too start to go idle after a while? Or is it only when there are several hundred+ running at once that this happens?Is there a single parent process that starts all of these scripts? If your using s = urllib2.urlopen(someURL), make sure to s.close() when your done with it. Python can often close things down for you (like if your doing x = urllib2.urlopen(someURL).read()), but it will leave that to you if you if told to (such as assigning a variable to the return value of .urlopen()). Double check your opening and closing of urllib calls (or all I/O code to be safe). If each script is designed to only have 1 open socket at a time, and your /proc/PID/fd is showing multiple active/open sockets per script process, then there is definitely a code issue to fix. ulimit -n showing 1024 is giving the limit of open socket/fd's that the mysql user can have, you can change this with ulimit -S -n [LIMIT_#] but check out this article first: Changing process.max-file-descriptor using 'ulimit -n' can cause MySQL to change table_open_cache value. You may need to log out and shell back in after. And/Or add it to /etc/bashrc (don't forget to source /etc/bashrc if you change bashrc and don't want to log out/in). Disk space is another thing that I have found out (the hard way) can cause very weird issues. I have had processes act like they are running (not zombied) but not doing what is expected because they had open handles to a log file on a partition with zero disk space left. netstat -anpTee | grep -i mysql will also show if these sockets are connected/established/waiting to be closed/waiting on timeout/etc. watch -n 0.1 'netstat -anpTee | grep -i mysql' to see the sockets open/close/change state/etc in real time in a nice table output (may need to export GREP_OPTIONS= first if you have it set to something like --color=always). lsof -u mysql or lsof -U will also show you open FD's (the output is quite verbose). import urllib2 import socket socket.settimeout(15) # or settimeout(0) for non-blocking: #In non-blocking mode (blocking is the default), if a recv() call # doesn’t find any data, or if a send() call can’t # immediately dispose of the data, # a error exception is raised. #...... try: s = urllib2.urlopen(some_url) # do stuff with s like s.read(), s.headers, etc.. except (HTTPError, etcError): # myLogger.exception("Error opening: %s!", some_url) finally: try: s.close() # del s - although, I don't know if deleting s will help things any. except: pass Some man pages and reference links: * *ulimit *quota *limits.conf *fork bomb *Changing process.max-file-descriptor using 'ulimit -n' can cause MySQL to change table_open_cache value *python socket module *lsof A: Solved! - with massive help from Chown - thank you very much! The slow down was because I was not setting socket timeout and as such over a period of time the robots where hanging trying to read data that did not exist. Adding a simple timeout = 5 socket.setdefaulttimeout(timeout) solved it (shame on me - but in my defence I am still learning python) The memory leak is down to urllib and the version of python I am using. After a lot of googling it appears it is a problem with nested urlopens - lots of post online about it when you work out how to ask the right question of Google. Thanks all for your help. EDIT: Something that also helped the memory leak issue (although not solved it completely) was doing manual garbage collection: import gc gc.collect Hope it helps someone else. A: It is probably some system ressource you're starved of. A guess: could you feel the limits of a pool of sockets your system can handle? If yes, you might see improved performance if you can close the sockets faster/sooner. EDIT: dependent the effort you want to take, you could restructure your application such that one process does multiple requests. One socket can be reused from within the same process, also a lot of different ressources. Twisted lends itself very much to this type of programming. A: Another system resource to take into account is ephemeral ports /proc/sys/net/ipv4/ip_local_port_range (on Linux). Together with /proc/sys/net/ipv4/tcp_fin_timeout they limit the number of concurrent connections. From Benchmark of Python WSGI Servers: This basically enables the server to open LOTS of concurrent connections. echo “10152 65535″ > /proc/sys/net/ipv4/ip_local_port_range sysctl -w fs.file-max=128000 sysctl -w net.ipv4.tcp_keepalive_time=300 sysctl -w net.core.somaxconn=250000 sysctl -w net.ipv4.tcp_max_syn_backlog=2500 sysctl -w net.core.netdev_max_backlog=2500 ulimit -n 10240
{ "language": "en", "url": "https://stackoverflow.com/questions/7619259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to handle sessions php I can't find a fitting article for this subject. Indeed, there are a lot of those I found, but they are old. How should I store session? How can I secure them, as much as possible, etc. A: Those on php.net are updated. It's very easy to use sessions, you just (before any ouput) add this snippet of code session_start() and then assign whatever you want to $_SESSION variable. A: The short answer is, don't store sessions. The session_start() and $_SESSION variable should be all you need. If you need data to persist consider using either cookies or store the corresponding data in a local database which relates to a certain registered user. A: Sessions are being used in order to "pass" data which is stored in $_SESSION variables. The data you can store in those variables can be username that's being saved after successful log in , or another information you find important becuase you might use it more than once. In order to start session you use the session_start() function, and in order to create a new session variable you use $_SESSION['sessionName']=$var;
{ "language": "en", "url": "https://stackoverflow.com/questions/7619260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Retrieve auto increment last entered auto increments data. In my case the owner_ID of the previously entered record into the mySQL database. <?php require "formfunctions.inc.php"; require "connect.inc.php"; startPage("Add details"); connectAndSelect(); //Uses my include php script functions to logon to mySQL using my credentials or die if(isset($_POST['addDetails'])) //isset means Is Set, so this makes clicking the submit button true { errorCheckDetails(); } else { showAddFormDetails(); } endPage(); ?> Here is the functions include file: <?php /*This is a PHP script containing the majority of my forms, which I have made into functions. It keeps all the back-end data together, meaning the other PHP files are a lot simpler, as I only need to call the functions if I need to use any of them, less code repitition meaning maximum efficency. Again it is a required script so files relying on this will have it being required and will not parse if this file cannot be parsed by the server.*/ //******************************THIS FUNCTION IS CALLED AT THE BEGINNING OF EVERY PAGE, IT SETS UP THE DOCTYPE, DEFAULT COMMENT, NAVBAR, AND DIV TAGS TO BE DISPLAYED*************** function startPage($title = '') { echo "<!doctype html> <!--NICK LITTLE WEB 2 ASSIGNMENT 2- THE MOTOR VEHICLE REGISTER DATABASE--> <html> <head> <meta charset=utf-8> <title>$title</title> <link href='css.css' rel='stylesheet' type='text/css'> </head> <body> <div class='header'> <img src='header.jpg'/> <ul id='list-nav'> <li><a href='frontend.php'>Home</a></li> <li><a href='search.php'>Search/Delete</a></li> <li><a href='addowner.php'>Add New Owner & Vehicle</a></li> <li><a href='addvehicle.php'>Add Vehicle</a></li> </ul> </div> <div class='container'> <div class='content'>"; } //**********SIMILAR TO THE START PAGE, CLOSES OFF DIV DAGS AND HTML BODY AND ENDING********************************************************************************** function endPage() { echo " </div> </div> </body> </html>"; } //****************THIS FORM IS DISPLAYED ON THE ADD OWNER/VEHICLE PAGE. IT JUST DISPLAYS THE FORM FOR USER INPUT************************************************************************** function showAddFormDetails() { $self=$_SERVER['PHP_SELF']; //making the form self referring //start form display - EVERYTHING IS DISPLAYED IN A NICE LOOKING FORM echo "<form action='$self' method='POST'> <center> <table id='searchForm'> <thead> <tr> <th colspan ='2'>Owner</th> <th colspan ='2'> Vehicle</th> </tr> </thead> <tfoot> <tr> <td></td> <td></td> <td><input type='submit' name='addDetails' value='Add Details'/></td> </tr> </tfoot> <tbody> <tr> <td>Title:</td> <td><input type='text' name='title' size='5px'/></td> <td>Make:</td> <td><input type='text' name='make' size='20px'/></td> </tr> <tr> <td>Name:</td> <td><input type='text' name='name' size='25px'/></td> <td>Model</td> <td><input type='text' name='model' size='20px'/></td> </tr> <tr> <td>Address:</td> <td><input type='text' name='address' size='48px'/></td> <td>Year:</td> <td><input type='text' name='year' size='10px'/></td> </tr> <tr> <td>Phone:</td> <td><input type='text' name='phonenumber' size='10px'/></td> <td>Registration:</td> <td><input type='text' name='rego' size='10px'/></td> </tr> <tr> <td></td> <td></td> <td>Kilometres:</td> <td><input type='text' name='kms' size='10px'/></td> </tr> </tbody> </table> </form>"; } //**********FUNCTION TO DISPLAY FORM TO ADD A VEHICLE TO AN EXISTING OWNER******************************************************************************************************* function showAddFormVehicle() //SELECT NAME FROM THE OWNER ID TO PERFORM AN SQL QUERY ON { $self=$_SERVER['PHP_SELF']; //making the form self referring //start form display - EVERYTHING IS DISPLAYED IN A NICE LOOKING FORM echo"Please fill out the required fields to add a vehicle to the system<br /><br /> Please note: A vehicle must be added to an <strong>existing owner</strong><br /><br /> Click here to <a href='addowner.php'> add a new owner and vehicle</a> <form action='$self' method='POST'> <center> <table id='searchForm'> <thead> <tr> <th colspan ='2'> Vehicle</th> </tr> </thead> <tfoot> <tr> <td></td> <td></td> <td><input type='submit' name='addVehicle' align='right' value='Add Vehicle'/></td> </tr> </tfoot> <tbody> <tr> <td>Owner:</td> <td><select name='owner_ID'><option value='-1' selected='selected'>Please select an owner...</option>"; $selectString ="SELECT DISTINCT owner_ID, name FROM tblOwner"; $result=mysql_query($selectString); while($row = mysql_fetch_assoc($result)) { $owner_ID = $row['owner_ID']; $owner_name = $row['name']; echo "<option value='$owner_ID'>$owner_name</option>"; } echo"</select> <tr> <td>Make:</td> <td><input type='text' name='make' size='20px'/></td> </tr> <tr> <td>Model:</td> <td><input type='text' name='model' size='20px'/></td> </tr> <tr> `<td>Year:</td> <td><input type='text' name='year' size='10px'/></td> </tr> <tr> <td>Registration:</td> <td><input type='text' name='rego' size='10px'/></td> </tr> <tr> <td>Kilometres:</td> <td><input type='text' name='kms' size='10px'/></td> </tr> </tbody> </table> </form>"; } //************FUNCTION TO ERROR CHECK THE INPUT ON THE ADDING A VEHICLE PAGE - SLIGHT VARIATION ON ADDING NEW VEHICLE AND OWNER SIMULTANEOUSLY************************************************** function delete() { /*foreach($_POST as $field => $value) { /*echo "$value<br> $field<br>"; }*/ $vehicleArray = $_POST['deleteButton']; $size = sizeOf( $vehicleArray); /*echo "SIZE is: $size<br>"; //SIZE returns a '1' echo "ARRAY is: $vehicleArray"; echo" $vehicleArray[0]"; //First index of array is a 'D'*/ for ($i = 0; $i < $size; $i++) //LOOP THROUGH THE SIZE AND ARRAY { $num = $vehicleArray[$i]; $query = "DELETE FROM tblVehicle WHERE vehicle_ID='$num'"; //echo"$query"; $result = mysql_query($query); echo "Thank you, the selected vehicle(s) were removed from the system <br /> <i> Please note the OWNER of the vehicle will remain in the system </i>"; } } //*****************************THIS FUNCTION ERROR CHECKS USER INPUT WHEN ATTEMPTING TO INSERT AN OWNER************************************************************************** function errorCheckDetails() { //assigning variables to the fields filled in, creates variables and assigns to 'NAME' form input value------ //----------owner variables----------------// $ownerTitle = mysql_real_escape_string($_POST['title']); $ownerName = mysql_real_escape_string($_POST['name']); $ownerAddress = mysql_real_escape_string($_POST['address']); $ownerPhone = mysql_real_escape_string($_POST['phonenumber']); //--------vehicle variables------------// $vehicleMake = mysql_real_escape_string($_POST['make']); $vehicleModel = mysql_real_escape_string($_POST['model']); $vehicleYear = mysql_real_escape_string($_POST['year']); $vehicleRego = mysql_real_escape_string($_POST['rego']); $vehicleKms = mysql_real_escape_string($_POST['kms']); $allFilled = true; //checking to see that all individual fields are filled in: if (empty($_POST['title'])==0) $allFilled = false; //If a specefic form field is empty, it is set to true, or else it is false if (empty($_POST['name'])==0) $allFilled = false; if (empty($_POST['address'])==0) $allFilled = false; if (empty($_POST['phonenumber'])==0) $allFilled = false; if (empty($_POST['make'])==0) $allFilled = false; if (empty($_POST['model'])==0) $allFilled = false; if (empty($_POST['year'])==0) $allFilled = false; if (empty($_POST['rego'])==0) $allFilled = false; if (empty($_POST['kms'])==0) $allFilled = false; //providing if all of the fields are filled in, insert user's data into owner table, all required fields if ($allFilled) { //*********************************************mySQL queries********************************************************** $insertOwnerQuery="INSERT INTO tblOwner(title,name,address,phone) VALUES ('$ownerTitle','$ownerName','$ownerAddress','$ownerPhone')"; $result=mysql_query($insertOwnerQuery); $aOwner = mysql_insert_id(); //Assign variable to mySQL function, returns last known user id input, so as to determine auto_inc for owner_ID $insertVehicleQuery="INSERT INTO tblVehicle(owner_ID,make,model,year,rego,kms) VALUES ('$aOwner','$vehicleMake','$vehicleModel','$vehicleYear','$vehicleRego','$vehicleKms')"; $result=mysql_query($insertVehicleQuery); echo "Thank you, your entry has been added to the system"; //Echo to screen to inform user owner has been added successfully. } else { //error messages that appear for each individual field that is not filled in: if (empty($_POST["title"])) echo"<p>The 'Owner Title' field must be filled in.</p>"; if (empty($_POST["name"])) echo "<p>The 'Name' field must be filled in.</p>"; if (empty($_POST["address"])) echo "<p>The 'Address' field must be filled in.</p>"; if (empty($_POST["phonenumber"])) echo "<p>The 'Phone Number' field must be filled in.</p>"; if (empty($_POST["make"])) echo "<p>The 'Vehicle Make' field must be filled in.</p>"; if (empty($_POST["model"])) echo "<p>The 'Vehicle Model' field must be filled in.</p>"; if (empty($_POST["year"])) echo "<p>The 'Vehicle Year' field must be filled in.</p>"; if (empty($_POST["rego"])) echo "<p>The 'Vehicle Registration' field must be filled in.</p>"; if (empty($_POST["kms"])) echo "<p>The 'Vehicle Kilometers' field must be filled in.</p>"; } /*echo '<form action = '$self' method='POST'> <input type='submit' name='returnAddOwner' value='Return to Adding an Owner'> </form>';*/ } //************FUNCTION TO ERROR CHECK THE INPUT ON THE ADDING A VEHICLE PAGE - SLIGHT VARIATION ON ADDING NEW VEHICLE AND OWNER SIMULTANEOUSLY************************************************** function errorCheckVehicle() { //assigning variables to the fields filled in, creates variables and assigns to 'NAME' form input value------ //----------owner variables----------------// $owner_ID = $_POST['owner_ID']; //NEED 2 FIGURE OUT HOW TO DETECT OPTION VALUE FOR OWNER NAME //--------vehicle variables------------// $vehicleMake = $_POST['make']; $vehicleModel = $_POST['model']; $vehicleYear = $_POST['year']; $vehicleRego = $_POST['rego']; $vehicleKms = $_POST['kms']; $allFilled = true; //checking to see that all individual fields are filled in: if ($vehicleMake == "") $allFilled = false; if ($vehicleModel == "") $allFilled = false; if ($vehicleYear == "") $allFilled = false; if ($vehicleRego == "") $allFilled = false; if ($vehicleKms == "") $allFilled = false; //providing if all of the fields are filled in, insert user's data into owner table, all required fields if ($allFilled) { $insertVehicleQuery="INSERT INTO tblVehicle(owner_ID,make,model,year,rego,kms) VALUES ('$owner_ID','$vehicleMake','$vehicleModel','$vehicleYear','$vehicleRego','$vehicleKms')"; $result=mysql_query($insertVehicleQuery); echo "Thank you, the vehicle has been added to the system"; //Echo to screen to inform user owner has been added successfully. } //error messages that appear for each individual field that is not filled in: else { if (empty($_POST["make"])) echo "<p>The 'Vehicle Make' field must be filled in.</p>"; if (empty($_POST["model"])) echo "<p>The 'Vehicle Model' field must be filled in.</p>"; if (empty($_POST["year"])) echo "<p>The 'Vehicle Year' field must be filled in.</p>"; if (empty($_POST["rego"])) echo "<p>The 'Vehicle Registration' field must be filled in.</p>"; if (empty($_POST["kms"])) echo "<p>The 'Vehicle Kilometers' field must be filled in.</p>"; } } //*********************************************************DISPLAY SEARCH FORM ON PAGE************************************************************************ function showSearchForm() { $self=$_SERVER['PHP_SELF']; //making the form self referring echo " <form action='$self' method='POST'> <center> <table id='searchForm'> <thead> <tr> <th colspan='2'>Vehicle</th> <th colspan='2'>Owner</th> </tr> </thead> <tfoot> <tr> <td></td> <td></td> <td class='searchSubmitButtons'><input type='submit' name='search' value='Search Records' /></td> <td class='searchSubmitButtons'><input type='submit' name='search' value='List all database entries' /></td> </tr> </tfoot> <tbody> <tr> <td>Make:</td> <td><input type='text' name='vehiclemake' size='20' /></td> <td>Name:</td> <td><input type='text' name='ownername' size='25' /></td> </tr> <tr> <td>Model:</td> <td><input type='text' name='vehiclemodel' size='20' /></td> <td>Address:</td> <td><input type='text' name='owneraddress' size='48' /></td> </tr> <tr> <td><label for='vehicleyear'>Year:</label></td> <td><input type='text' name='vehicleyear' id='vehicleyear' size='10' /></td> <td>Phone:</td> <td><input type='text' name='ownerphone'/></td> </tr> <tr> <td>Registration:</td> <td><input type='text' name='vehiclerego' size='10' /></td> </tr> <tr> <td>Km's:</td> <td><input type = 'text' name='vehiclekms' size='10'/></td> </tr> </tbody> </table> </center> </form>"; } function showRecords() { $self=$_SERVER['PHP_SELF']; //making the form self referring //assigning variables to the fields filled in: //$owner_ID = $_POST['ownerID']; //$title = $_POST['ownertitle']; $name = $_POST['ownername']; $address = $_POST['owneraddress']; $phone = $_POST['ownerphone']; $make = $_POST['vehiclemake']; $model = $_POST['vehiclemodel']; $year = $_POST['vehicleyear']; $rego = $_POST['vehiclerego']; $kms = $_POST['vehiclekms']; //print search results from both tables - patients and owners (unnecessary fields or duplicates excluded) % is the like function, so could put 'at' to get cat: $selectString = "SELECT vehicle_ID,make,model,year,rego,kms,name,phone FROM tblVehicle,tblOwner WHERE (tblVehicle.owner_ID = tblOwner.owner_ID AND make LIKE '%$make%' AND model LIKE '%$model%' AND rego LIKE '%$rego%' AND kms LIKE '%$kms%' AND name LIKE '%$name%' AND address LIKE '%$address%' AND phone LIKE '%$phone%')"; $result = mysql_query($selectString); //vehicle_ID, tblOwner.owner_ID, echo"<form action = '$self' method='POST'> <table border='1' cellpadding='8'> <tr> <th>Vehicle ID</th> <th>Vehicle Make</th> <th>Vehicle Model</th> <th>Vehicle Year</th> <th>Vehicle Registration</th> <th>Vehicle KM</th> <th>Owner Name</th> <th>Owner Phone</th> <th>Delete</th> </tr>"; while($row = mysql_fetch_row($result)) { echo '<tr>'; foreach($row as $field => $value) { if( $field == 0) $vehicle_ID=$value; echo "<td>$value</td>"; } echo"<td><input type ='checkbox' name = deleteButton[] value='$vehicle_ID'></td>"; echo '</tr>'; } echo "</table> <br><br> <input type='submit' name='returnSearch' value='Return to Searching Records'> <input type='submit' name='del' align='right' value='Delete Selected Records'> </form>"; } ?> Sorry they are big files. Im new here :( Don't know how to post big amounts of code. Cheers A: you are answering your own question in your code $aOwner = mysql_insert_id(); //Assign variable to mySQL function, returns last known user id input, so as to determine auto_inc for owner_ID so just print the $aOwner A: You can use SELECT LAST_INSERT_ID(); or in php mysql_query("INSERT ... "); $increment = mysql_insert_id(); A: @genesis I believe you want to display the next incremement owner_ID where a user know, what will be his/her owner_ID. If i am right read below information 1] retrive the owner_ID from tblVehicle table, 2] take the highest number, 3] increment the highest number with 1, 4] then go with the insertion code, And i tested with queries listed above SELECT from table_name LAST_INSERT_ID() or SELECT LAST_INSERT_ID(); these two queries didnt work out, i provides only '0' values. better try up with code insertion $insertVehicleQuery="INSERT INTO tblVehicle(make,model,year,rego,kms) VALUES ('$vehicleMake','$vehicleModel','$vehicleYear','$vehicleRego','$vehicleKms')"; just remove the *owner_ID* from the above query A: mysql reference $result = mysql_query(SELECT from table_name LAST_INSERT_ID())"; echo $result; php reference mysql_query("watever query"); echo mysql_insert_id(); A: you can get this by $r = mysql_query("SHOW TABLE STATUS LIKE 'table_name' "); $row = mysql_fetch_array($r); $Auto_increment = $row['Auto_increment']; mysql_free_result($r);
{ "language": "en", "url": "https://stackoverflow.com/questions/7619263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: ASP DOt NET itemTemplate in GridView How to add Textbox in gridview and how to access to it and perform some calculations like Serno,Name,ServAmnt,Qty,Disc,netamt netamt=servamnt*qty*discount A: Take a look at the GridView Examples for ASP.NET 2.0: Working with TemplateFields MSDN tutorial as a strating point: Specify TemplateField.ItemTemplate; Put the asp:TextBox control into template; Bind the required TextBox’s property via the binding expression with the required field from the underlying datasource: <asp:TemplateField> <ItemTemplate> <asp:TextBox ID="txtUnitPrice" runat="server" Text='<%#Eval("UnitPrice")%>'> </asp:TextBox> </ItemTemplate> </asp:TemplateField>
{ "language": "en", "url": "https://stackoverflow.com/questions/7619264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Complex regex with custom formula builder I have a string which is like this - MVAL("A","01-01-1900")+MVAL(B,"01-01-1900")+MVAL("C")+MVAL(D). Now I want to extract B AND D out of this using regex because it is the first parameter and it has no quotes around it in both the overloaded version of the functions. Secondly because MVAL function is an overloaded function with two versions like MVAL("A") and MVAL(B,"01-01-1900") how will I find which version of the function is being used. Please help. I'm using System.Text.RegularExpressions.Regex method. A: It looks like you simply want to match the text MVAL( followed by a letter (or perhaps an identifier). Try this one: MVAL\(([A-Z]) The first part, MVAL\(, matches the prefix. Then we have some text surrounded by parentheses: ([A-Z]). The parens tell the regular expression engine to "capture" any text the contents will match, which means we can use it later. This is why we had to escape the opening one with a backslash in the prefix. The [A-Z] pattern matches any character between A and Z. This includes all uppercase alphabetic characters. We then tell the regex engine to ignore the case, so it matches all lowercase characters too. Dim regex = new Regex("MVAL\(([A-Z])", RegexOptions.IgnoreCase) Dim match = regex.Match(input) Dim parameter = match.Groups(1) If you want to match any valid identifier rather than just a single letter, try this instead: MVAL\(([A-Z_][A-Z0-9_]*) That captured part will match any letter or an underscore, followed by zero or more (denoted by the *) letters, numbers or underscores. A: Is it safe to assume that there will never be a comma after the first parameter unless it's followed by a second parameter? If so, this should be all you need: string s = @"MVAL(""A"",""01-01-1900"")+MVAL(B,""01-01-1900"")+MVAL(""C"")+MVAL(D)"; foreach (Match m in Regex.Matches(s, @"MVAL\((\w+)(,)?")) { Console.WriteLine("First param: {0}\nHas second param? {1}\n", m.Groups[1], m.Groups[2].Success); } output: First param: B Has second param? True First param: D Has second param? False If there's no comma, the overall match will still succeed because the comma is optional. But, because the second capturing group didn't participate in the match, its Success property is set to False. This regex also assumes there will never be any whitespace within the string, as in your example. This regex allows for whitespace between syntax elements: @"MVAL\s*\(\s*(\w+)\s*(,)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7619271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delphi x64 embedded database Googled for a long time but cant seem to find an answer. Is there any x64 embedded database to use with Delphi ? Cant seem to find any A: Delphi XE 2 supports FireBird 2.5 using dbExpress, So try the Firebird x64 Embedded version. A: Check AnyDAC 5.0.3 with XE2 and 64-bit support. SQLite is already included into library installer. Embedded: * *SQLite Database *Firebird Embedded *MySQL Embedded *Berkeley DB *Advantage Local A: Devart have a dbExpress driver for sqlite that supports XE2 64 bit targets. A: Among free embedded engines there is also Nexus DB to be listed. http://www.nexusdb.com/support/index.php?q=node/509 People worked with v2 told that the choice is dubious: * *only works good with their own Heap Manager *In client-server mode high chance of DB corruption when Windows terminates program *On large (hundreds thousand of rows) table queries, all the data is pulled to memory and only filtered later, if not dieing for not enough memory, cache never shrinks back then. This also makes it work rather slow. People worked with v3 mostly tell that is hollywar and totally outdated claims. Up to me, if to need on disk persistence, then go to Firebird Embedded + Unified Interbase library. If to need relatively small in-memory tables with little latency - then NexusDB Embedded would be free and natively-integrating suite.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Jquery find all images on a website link I'm trying to create an jquery "inside" bookmarklet to my website like facebook share. I need to get all images on a link. I mean if I give www.domain.com in my form, ajax request is needed to get all image links in that webpage and images should be shown in the form to select by user. I'm sure there is a jquery plugin in order to do this, but I couldn't find any. I hope anyone can help me with this. A: You can do this for the actual site where the script will reside. The following code will get you all images. $('img') I mean if I give www.domain.com in my form, ajax request is needed to get all image links in that webpage and images should be shown in the form to select by user. No, you can't do this for a remote site. It's restricted by the same origin policy. You would be able to do this if you fetched the remote page with a server side handler on the same domain jQuery code will reside.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to avoid extra indentation in Template Haskell declaration quotations? I have a toy program: $ cat a.hs main = putStrLn "Toy example" $ runghc a.hs Toy example Let's add some Template Haskell to it: $ cat b.hs {-# LANGUAGE TemplateHaskell #-} id [d| main = putStrLn "Toy example" |] $ runghc b.hs b.hs:3:0: parse error (possibly incorrect indentation) Right then, let's fix the indentation: $ cat c.hs {-# LANGUAGE TemplateHaskell #-} id [d| main = putStrLn "Toy example" |] $ runghc c.hs Toy example A single space is enough, but I do have to indent both trailing lines. Can I avoid having to indent most of my module? (My Real Modules have much more than a single line of code.) (And without using { ; ; } notation?) I do want all of the module declarations to be captured in the quotation — in normal code I can replace (...) with $ ..., is there some equivalent of [d|...|] that would let me avoid the close brackets and also the indenting? Or is there some way module A can say that the top-level declarations of any module B that A is imported into are automatically processed by a function A exports? Notes: * *The Template Haskell in my Real Program is more complex than id — it scans the declarations for variable names that start prop_, and builds a test suite containing them. Is there some other pure Haskell way I could do this instead, without directly munging source files? *I'm using GHC v6.12.1. When I use GHC v7.0.3, the error for b.hs is reported for a different location — b.hs:3:1 — but the behaviour is otherwise identical. A: If the test suite is for QuickCheck, i advise you to use the new All module instead: http://hackage.haskell.org/packages/archive/QuickCheck/2.4.1.1/doc/html/Test-QuickCheck-All.html It does the same thing except it fetches the names of properties by accessing the file system and parsing the file that the splice resides in (if you are using some other test framework, you can still use the same approach). If you really want to quote the entire file, you could use a quasi-quoter instead (which does not require indentation). You can easily build your quoter on haskell-src-meta, but i advice against this approach because it will not support some Haskell features and it will probably give poor error messages. Aggregating test suits is a difficult problem, one could probably extend the name gathering routine to somehow follow imports but it's a lot of work. Here's a workaround: You can use this modified version of forAllProperties: import Test.QuickCheck import Test.QuickCheck.All import Language.Haskell.TH import Data.Char import Data.List import Control.Monad allProperties :: Q Exp -- :: [(String,Property)] allProperties = do Loc { loc_filename = filename } <- location when (filename == "<interactive>") $ error "don't run this interactively" ls <- runIO (fmap lines (readFile filename)) let prefixes = map (takeWhile (\c -> isAlphaNum c || c == '_') . dropWhile (\c -> isSpace c || c == '>')) ls idents = nubBy (\x y -> snd x == snd y) (filter (("prop_" `isPrefixOf`) . snd) (zip [1..] prefixes)) quickCheckOne :: (Int, String) -> Q [Exp] quickCheckOne (l, x) = do exists <- return False `recover` (reify (mkName x) >> return True) if exists then sequence [ [| ($(stringE $ x ++ " on " ++ filename ++ ":" ++ show l), property $(mono (mkName x))) |] ] else return [] [|$(fmap (ListE . concat) (mapM quickCheckOne idents)) |] You also need the function runQuickCheckAll which is not exported from All: runQuickCheckAll :: [(String, Property)] -> (Property -> IO Result) -> IO Bool runQuickCheckAll ps qc = fmap and . forM ps $ \(xs, p) -> do putStrLn $ "=== " ++ xs ++ " ===" r <- qc p return $ case r of Success { } -> True Failure { } -> False NoExpectedFailure { } -> False In each test module you now define propsN = $allProperties where N is some number or other unique identifier (or you could use the same name and use qualified names in the step below). In your main test suite you define props :: [(String,Property)] props = concat [props1, props2 ... propsN] If you really want to avoid adding a list member for each module, you could make a TH script that generates this list. To run all your tests you simply say runTests = runQuickCheckAll quickCheckResult props A: [my program] scans the declarations for variable names that start prop_, and builds a test suite containing them. Is there some other pure Haskell way I could do this instead, without directly munging source files? Yes, there is! Using the language-haskell-extract package. {-# LANGUAGE TemplateHaskell #-} import Language.Haskell.Extract import Test.QuickCheck prop_foo xs = reverse (reverse xs) == (xs :: [Int]) prop_bar = 2 + 2 == 4 properties = $(functionExtractorMap "^prop_" [|\name prop -> putStrLn name >> quickCheck prop|]) main = sequence_ properties Running this, we get: prop_foo +++ OK, passed 100 tests. prop_bar +++ OK, passed 100 tests. However, before you go reinventing the wheel I would also recommend you take a look at the test-framework-th package, which does pretty much exactly this, but also supports HUnit and has a nice test runner (with colors!). {-# LANGUAGE TemplateHaskell #-} import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 import Test.Framework.TH import Test.HUnit import Test.QuickCheck prop_bar = 1+1 == 2 case_foo = 2+2 @?= 4 main = $(defaultMainGenerator) Output: Main: bar: [OK, passed 100 tests] foo: [OK] Properties Test Cases Total Passed 1 1 2 Failed 0 0 0 Total 1 1 2 There's also a testGroupGenerator which is useful if you want to combine tests from multiple files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why can't I see the invoking method in the debugger? a beginner question about xCode debugger. - (void)searchDidFinished:(NSDictionary *)info method is invoked and I'm trying to determine who is the invoker but as you can see the call stack doesn't help me: http://cl.ly/AaE4 Why ? I've also checked if the method is linked in Interface Builder. But this is not the case. thanks A: It looks like the selector is being called via performSelectorOnMainThread: or performSelector:afterDelay in which case you won't be able to see the original caller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: compile time error regarding template function instantiation I am trying to write a container class with iterator. This is my class: template <class T> class C{ private: T* v; int MAX_SIZE; int i; public: C (int size){ MAX_SIZE = size; v = new T (MAX_SIZE); i = 0; } ~C(){ delete v; } class iterator{ private: T* v; public: iterator(T* ip){ v = ip; } void operator++ (){ ++v; } void operator-- (){ --v; } T operator* () { return *v; } bool operator!= (const iterator & it) { return v != it.v; } }; iterator begin(){ return iterator (v); } iterator end() { return iterator (&v[MAX_SIZE]); } void push_back (T e){ if (i == MAX_SIZE) throw MaxSizeReached(); v[i] = e; ++i; } class MaxSizeReached{}; }; template <class T> void print(typename C<T>::iterator & start, typename C<T>::iterator & end){ for (typename C<T>::iterator s (start), e (end); s != e; ++s){ std::cout << *s << '\n'; } } int main(){ C<int> ic (3); C<float> fc (4); C<char> cc (3); ic.push_back (56); ic.push_back (76); ic.push_back (88); print<int>(ic.begin(), ic.end()); return 0; } g++ 4.5 throws this error: templatizedCustomIterator.c++: In function ‘int main()’: templatizedCustomIterator.c++:71:35: error: no matching function for call to ‘print(C<int>::iterator, C<int>::iterator) Which is incorrect - definition of print() or the call? A: Have a look the function template: template<T> void print(typename C<T>::iterator & start, typename C<T>::iterator & end); And your usage: print(ic.begin(), ic.end()); So the problem is, T cannot be deduced from the function argument. The Standard calls it non-deducible context. Here I've explained similar question in detail, read this: * *C++, template argument can not be deduced Now the question is, how would you implement the function template? So here is one good solution: template <class FwdIterator> void print(FwdIterator start, FwdIterator end) { for ( ; start != end; ++start) { std::cout << *start << '\n'; } } If you pass a third argument as: template <class FwdIterator> void print(FwdIterator start, FwdIterator end, std::ostream &out) { for ( ; start != end; ++start) { out << *start << '\n'; } } then you can use this to print to file as well: print(ic.begin(), ic.end(), std::cout); //print to console std::ofstream file("file.txt") print(ic.begin(), ic.end(), file); //print to file A: The print function has to take the parameters as const references, else it can't be used with temporary values like those returned by begin() and end(): template <class T> void print(const typename C<T>::iterator & start, const typename C<T>::iterator & end){ ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7619295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to avoid overloading of application main form by multi tabs webbrowser? I'm using multiple TCppWebBrowsers on main form, and when I start the application all tabs from last internet session are recovered. But this makes the main form of application to overload much. My question is how can I avoid overloading of main form? I tried myself to achieve it but had no success. I used TThread class from C++ Builder and tried to start navigation from there, but unsuccessful, main form still overloading. I also tried CreateThread() - same thing. I have found: WebBrowser Control (MFC) created in seperate thread working in Windows 7 and Vista, but Windows XP But I do not understand this very well. Please somebody tell me how to solve my question in C++ Builder! A: If possible, I'd leave the threads aside and would try loading one page after another. It's easier. All you have to do is to not load the content of all TCppWebBrowsersat once, instead start by loading only the first (visible to the user) then load the others one by one. Load a tab when one of the following happens: * *the user activates a tab - you should definitely load this page immediately *the application is idle and no other tab is loading - load the next one Do this until all tabs are loaded. Of course you need to be able to somehow influence the "session recovering mechanism" to implement this delay-loading. But if you would be able to add threads then you should also be able to just load the tabs one by one. This will spread the load over a longer time and should prevent overloading your app at startup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AudioTrack will only play audio once I'm working on an Android program that needs to playback audio files repeatedly with very exact timing (music program). I'm using an "AudioTrack" right now that has the PCM data loaded in from a WAV sample. here is the code im testing this feature out with. it just loops until its time to play the sample, then plays it, and repeats this 8 times. Here is the code that I am using, let me know if you need to see more: class Sequencer { private final double BPM = 120; private final double BPMS = (BPM / 60 / 1000); private long QUARTER_NOTE_DELAY = (long)(1/BPMS); private final int PCM_BYTE_OFFSET = 44; private long lastTick; private long now = 0; private int sampleRate = 8000; private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_STEREO; private int audioFormat = AudioFormat.ENCODING_PCM_16BIT; private int bufferSize = AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat)*5; private AudioTrack playbackBuffer = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate, channelConfig,audioFormat,bufferSize,AudioTrack.MODE_STATIC);; private byte[] pcmArray; public Sequencer() { Log.d("AudioTrack", "BUFFER SIZE: " +bufferSize); String path = "samples/classical_guitar_c5_16bit.wav"; try { pcmArray = parsePCMData(path); } catch (IOException e) { // TODO Auto-generated catch block Log.e("Error Initializng Sequencer", "File not Found: " + path ); e.printStackTrace(); } } public void play() { new Thread() { public void run() { lastTick = 0; // play 10 times Log.d("Sequencer", "QUARTER-NOTE = " + QUARTER_NOTE_DELAY + "ms"); for (int i = 0; i < 8; i++) { lastTick = System.currentTimeMillis(); while (!update(i)); } playbackBuffer.flush(); } }.start(); } public void stop() { } //load PCM data into the buffer private void loadPCMData(byte[] pcmData) { int numBytesWritten = playbackBuffer.write(pcmData, PCM_BYTE_OFFSET, (pcmData.length-PCM_BYTE_OFFSET)); Log.d("AudioTrack", "LOADED " + numBytesWritten + " BYTES" + " IN " + (System.currentTimeMillis()- now) + "ms!"); } private byte[] parsePCMData(String path) throws IOException { InputStream fileIn = assetManager.open(path); BufferedInputStream buffIn = new BufferedInputStream(fileIn, 8000); DataInputStream dataIn = new DataInputStream(buffIn); byte[] pcmArray; ArrayList<Byte> pcmVector = new ArrayList<Byte>(); int numBytes; //Read the file into the "music" array for(int i=0; dataIn.available() > 0; i++) { pcmVector.add(dataIn.readByte()); } //Close the input streams dataIn.close(); buffIn.close(); fileIn.close(); numBytes = pcmVector.size(); pcmArray = new byte[numBytes]; //Copy the data from the arrayLast to the byte array for(int i=0; i<numBytes; i++) { pcmArray[i] = (Byte) pcmVector.get(i); } return pcmArray; } //Start Playback of PCM data private void startPlayback() { //stop playback if(playbackBuffer.getState() != AudioTrack.STATE_NO_STATIC_DATA) { playbackBuffer.stop(); playbackBuffer.flush(); } //start loading the next batch of sounds loadPCMData(pcmArray); //reset head position playbackBuffer.setPlaybackHeadPosition(0); //playbacksounds playbackBuffer.play(); } private boolean update(int i) { now = System.currentTimeMillis(); if (now - lastTick >= QUARTER_NOTE_DELAY) { //start Sounds Log.d("AudioTrack: ", "Starting Playback. Current State: " + Integer.toString(playbackBuffer.getState())); startPlayback(); Log.d("AudioTrack: ", "Playback Started. Current State: " + Integer.toString(playbackBuffer.getState())); Log.d("MainMenu.java: ", "Event Triggered after " + Long.toString(now-lastTick) +"ms"); lastTick = now; //update UI in a seperate thread beatCounter.post(updateUI); return true; } else{ return false; } } } It plays perfectly on the first of the eight loops, but after that there is just silence, no visible errors or warnings. (although the state will remain at 1 which is " STATE_INITIALIZED" meaning "State of an AudioTrack that is ready to be used." I am aware that AudioTrack has a looping feature, as well as the "reloadStaticData" method, but when I start writing the actual app I am testing this out for the data will change each time based on a sequence generated by the user) In addition, i initially tried doing this with both mediaplayer and soundpool but both gave me too much latency. As a test i also tried it with re-initializing the AudioTrack entirely every loop through but that gave me too much latency to be really useful. I apologize for the messy code, I really hope its just something stupid i'm doing wrong, as i'm getting very frustrated. Thanks! testing on Android 2.2.2, on a handset device (not emulated) Here is my LogCat output: 10-01 05:07:22.016: DEBUG/AndroidRuntime(23316): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 10-01 05:07:22.016: DEBUG/AndroidRuntime(23316): CheckJNI is OFF 10-01 05:07:22.016: DEBUG/dalvikvm(23316): creating instr width table 10-01 05:07:22.094: DEBUG/AndroidRuntime(23316): --- registering native functions --- 10-01 05:07:22.461: DEBUG/dalvikvm(22329): GC_EXPLICIT freed 236 objects / 13984 bytes in 39ms 10-01 05:07:23.547: DEBUG/PackageParser(1089): Scanning package: /data/app/vmdl67886.tmp 10-01 05:07:23.680: DEBUG/KeyguardViewMediator(1089): wakeWhenReadyLocked(26) 10-01 05:07:23.680: DEBUG/KeyguardViewMediator(1089): handleWakeWhenReady(26) 10-01 05:07:23.680: DEBUG/KeyguardViewMediator(1089): pokeWakelock(5000) 10-01 05:07:23.680: INFO/power(1089): *** set_screen_state 1 10-01 05:07:23.696: DEBUG/Sensors(1089): using sensors (name=sensors) 10-01 05:07:24.088: INFO/PackageManager(1089): Removing non-system package:com.android.test 10-01 05:07:24.088: INFO/Process(1089): Sending signal. PID: 23293 SIG: 9 10-01 05:07:24.088: INFO/ActivityManager(1089): Force stopping package com.android.test uid=10081 10-01 05:07:24.102: INFO/WindowManager(1089): WIN DEATH: Window{44b41118 com.android.test/com.android.test.MainMenu paused=false} 10-01 05:07:24.118: INFO/UsageStats(1089): Unexpected resume of com.android.launcher while already resumed in com.android.test 10-01 05:07:24.196: DEBUG/SurfaceFlinger(1089): Screen about to return, flinger = 0x120f38 10-01 05:07:24.446: DEBUG/PackageManager(1089): Scanning package com.android.test 10-01 05:07:24.446: INFO/PackageManager(1089): Package com.android.test codePath changed from /data/app/com.android.test-2.apk to /data/app/com.android.test-1.apk; Retaining data and using new 10-01 05:07:24.453: INFO/PackageManager(1089): /data/app/com.android.test-1.apk changed; unpacking 10-01 05:07:24.453: DEBUG/installd(1012): DexInv: --- BEGIN '/data/app/com.android.test-1.apk' --- 10-01 05:07:24.602: DEBUG/dalvikvm(23325): creating instr width table 10-01 05:07:24.641: DEBUG/dalvikvm(23325): DexOpt: load 11ms, verify 23ms, opt 0ms 10-01 05:07:24.649: DEBUG/installd(1012): DexInv: --- END '/data/app/com.android.test-1.apk' (success) --- 10-01 05:07:24.657: DEBUG/PackageManager(1089): Activities: com.android.test.AndroidTestActivity com.android.test.MainMenu 10-01 05:07:24.657: INFO/ActivityManager(1089): Force stopping package com.android.test uid=10081 10-01 05:07:24.657: WARN/PackageManager(1089): Code path for pkg : com.android.test changing from /data/app/com.android.test-2.apk to /data/app/com.android.test-1.apk 10-01 05:07:24.657: WARN/PackageManager(1089): Resource path for pkg : com.android.test changing from /data/app/com.android.test-2.apk to /data/app/com.android.test-1.apk 10-01 05:07:24.829: INFO/installd(1012): move /data/dalvik-cache/data@[email protected]@classes.dex -> /data/dalvik-cache/data@[email protected]@classes.dex 10-01 05:07:24.829: DEBUG/PackageManager(1089): New package installed in /data/app/com.android.test-1.apk 10-01 05:07:24.868: DEBUG/KeyguardViewMediator(1089): pokeWakelock(5000) 10-01 05:07:25.000: DEBUG/KeyguardViewMediator(1089): pokeWakelock(5000) 10-01 05:07:25.211: WARN/InputManagerService(1089): Got RemoteException sending setActive(false) notification to pid 23293 uid 10081 10-01 05:07:25.274: INFO/ActivityManager(1089): Force stopping package com.android.test uid=10081 10-01 05:07:25.571: DEBUG/dalvikvm(1089): GC_EXPLICIT freed 24967 objects / 1341840 bytes in 159ms 10-01 05:07:25.672: DEBUG/VoiceDialerReceiver(22354): onReceive Intent { act=android.intent.action.PACKAGE_REMOVED dat=package:com.android.test flg=0x10000000 cmp=com.android.voicedialer/.VoiceDialerReceiver (has extras) } 10-01 05:07:25.977: DEBUG/dalvikvm(1089): GC_EXPLICIT freed 6005 objects / 330448 bytes in 141ms 10-01 05:07:26.016: DEBUG/VoiceDialerReceiver(22354): onReceive Intent { act=android.intent.action.PACKAGE_ADDED dat=package:com.android.test flg=0x10000000 cmp=com.android.voicedialer/.VoiceDialerReceiver (has extras) } 10-01 05:07:26.250: INFO/installd(1012): unlink /data/dalvik-cache/data@[email protected]@classes.dex 10-01 05:07:26.258: DEBUG/AndroidRuntime(23316): Shutting down VM 10-01 05:07:26.266: DEBUG/dalvikvm(23316): Debugger has detached; object registry had 1 entries 10-01 05:07:26.282: INFO/AndroidRuntime(23316): NOTE: attach of thread 'Binder Thread #3' failed 10-01 05:07:26.680: DEBUG/AndroidRuntime(23330): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<< 10-01 05:07:26.680: DEBUG/AndroidRuntime(23330): CheckJNI is OFF 10-01 05:07:26.680: DEBUG/dalvikvm(23330): creating instr width table 10-01 05:07:26.735: DEBUG/AndroidRuntime(23330): --- registering native functions --- 10-01 05:07:27.047: INFO/ActivityManager(1089): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.android.test/.AndroidTestActivity } 10-01 05:07:27.110: DEBUG/AndroidRuntime(23330): Shutting down VM 10-01 05:07:27.110: DEBUG/dalvikvm(23330): Debugger has detached; object registry had 1 entries 10-01 05:07:27.110: INFO/ActivityManager(1089): Start proc com.android.test for activity com.android.test/.AndroidTestActivity: pid=23337 uid=10081 gids={} 10-01 05:07:27.125: INFO/AndroidRuntime(23330): NOTE: attach of thread 'Binder Thread #3' failed 10-01 05:07:27.203: INFO/WindowManager(1089): Setting rotation to 1, animFlags=1 10-01 05:07:27.227: INFO/ActivityManager(1089): Config changed: { scale=1.0 imsi=310/4 loc=en_US touch=3 keys=2/1/2 nav=2/2 orien=2 layout=34 uiMode=17 seq=554} 10-01 05:07:27.613: INFO/ActivityManager(1089): Displayed activity com.android.test/.AndroidTestActivity: 513 ms (total 513 ms) 10-01 05:07:27.657: WARN/IInputConnectionWrapper(17894): showStatusIcon on inactive InputConnection 10-01 05:07:28.073: INFO/ActivityManager(1089): Starting activity: Intent { act=com.android.test.CLEARSPLASH cmp=com.android.test/.MainMenu } 10-01 05:07:28.141: DEBUG/AudioTrack(23337): BUFFER SIZE: 14860 10-01 05:07:28.571: INFO/ActivityManager(1089): Displayed activity com.android.test/.MainMenu: 488 ms (total 488 ms) 10-01 05:07:29.930: DEBUG/dalvikvm(1089): GC_EXPLICIT freed 3588 objects / 165776 bytes in 182ms 10-01 05:07:40.172: DEBUG/Sequencer(23337): QUARTER-NOTE = 500ms 10-01 05:07:40.680: DEBUG/AudioTrack:(23337): Starting Playback. Current State: 2 10-01 05:07:40.680: DEBUG/AudioTrack(23337): LOADED 14860 BYTES IN 1ms! 10-01 05:07:40.688: DEBUG/AudioTrack:(23337): Playback Started. Current State: 1 10-01 05:07:40.688: DEBUG/MainMenu.java:(23337): Event Triggered after 502ms 10-01 05:07:41.203: DEBUG/AudioTrack:(23337): Starting Playback. Current State: 1 10-01 05:07:41.203: DEBUG/AudioTrack(23337): LOADED 14860 BYTES IN 1ms! 10-01 05:07:41.203: DEBUG/AudioTrack:(23337): Playback Started. Current State: 1 10-01 05:07:41.203: DEBUG/MainMenu.java:(23337): Event Triggered after 500ms 10-01 05:07:41.711: DEBUG/AudioTrack:(23337): Starting Playback. Current State: 1 10-01 05:07:41.711: DEBUG/AudioTrack(23337): LOADED 14860 BYTES IN 1ms! 10-01 05:07:41.719: DEBUG/AudioTrack:(23337): Playback Started. Current State: 1 10-01 05:07:41.719: DEBUG/MainMenu.java:(23337): Event Triggered after 500ms 10-01 05:07:42.227: DEBUG/AudioTrack:(23337): Starting Playback. Current State: 1 10-01 05:07:42.235: DEBUG/AudioTrack(23337): LOADED 14860 BYTES IN 1ms! 10-01 05:07:42.235: DEBUG/AudioTrack:(23337): Playback Started. Current State: 1 10-01 05:07:42.235: DEBUG/MainMenu.java:(23337): Event Triggered after 500ms 10-01 05:07:42.743: DEBUG/AudioTrack:(23337): Starting Playback. Current State: 1 10-01 05:07:42.743: DEBUG/AudioTrack(23337): LOADED 14860 BYTES IN 1ms! 10-01 05:07:42.750: DEBUG/AudioTrack:(23337): Playback Started. Current State: 1 10-01 05:07:42.750: DEBUG/MainMenu.java:(23337): Event Triggered after 500ms 10-01 05:07:43.258: DEBUG/AudioTrack:(23337): Starting Playback. Current State: 1 10-01 05:07:43.258: DEBUG/AudioTrack(23337): LOADED 14860 BYTES IN 1ms! 10-01 05:07:43.258: DEBUG/AudioTrack:(23337): Playback Started. Current State: 1 10-01 05:07:43.258: DEBUG/MainMenu.java:(23337): Event Triggered after 500ms 10-01 05:07:43.774: DEBUG/AudioTrack:(23337): Starting Playback. Current State: 1 10-01 05:07:43.774: DEBUG/AudioTrack(23337): LOADED 14860 BYTES IN 1ms! 10-01 05:07:43.782: DEBUG/AudioTrack:(23337): Playback Started. Current State: 1 10-01 05:07:43.782: DEBUG/MainMenu.java:(23337): Event Triggered after 500ms 10-01 05:07:44.289: DEBUG/AudioTrack:(23337): Starting Playback. Current State: 1 10-01 05:07:44.297: DEBUG/AudioTrack(23337): LOADED 14860 BYTES IN 2ms! 10-01 05:07:44.305: DEBUG/AudioTrack:(23337): Playback Started. Current State: 1 10-01 05:07:44.305: DEBUG/MainMenu.java:(23337): Event Triggered after 500ms 10-01 05:07:44.344: DEBUG/dalvikvm(22433): GC_EXPLICIT freed 827 objects / 40752 bytes in 67ms 10-01 05:07:49.422: DEBUG/dalvikvm(20018): GC_EXPLICIT freed 596 objects / 30440 bytes in 67ms 10-01 05:07:54.563: DEBUG/dalvikvm(22329): GC_EXPLICIT freed 143 objects / 10072 bytes in 80ms 10-01 05:07:59.696: DEBUG/dalvikvm(22354): GC_EXPLICIT freed 547 objects / 30048 bytes in 68ms 10-01 05:08:09.977: DEBUG/dalvikvm(22363): GC_EXPLICIT freed 483 objects / 22512 bytes in 111ms 10-01 05:08:10.219: INFO/power(1089): *** set_screen_state 0 10-01 05:08:10.237: DEBUG/SurfaceFlinger(1089): About to give-up screen, flinger = 0x120f38 10-01 05:08:10.258: DEBUG/Sensors(1089): using accelerometer (name=accelerometer) 10-01 05:08:15.430: DEBUG/StatusBar(1089): DISABLE_EXPAND: yes 10-01 05:08:15.469: DEBUG/GoogleLoginService(16965): onBind: Intent { act=android.accounts.AccountAuthenticator cmp=com.google.android.gsf/.loginservice.GoogleLoginService } 10-01 05:08:15.469: INFO/WindowManager(1089): Setting rotation to 0, animFlags=1 10-01 05:08:15.493: INFO/ActivityManager(1089): Config changed: { scale=1.0 imsi=310/4 loc=en_US touch=3 keys=2/1/2 nav=2/2 orien=1 layout=34 uiMode=17 seq=555} 10-01 05:08:15.821: DEBUG/dalvikvm(23337): GC_FOR_MALLOC freed 1766 objects / 427920 bytes in 193ms 10-01 05:08:15.899: DEBUG/AudioTrack(23337): BUFFER SIZE: 14860 A: Maybe you should try to use streamming mode of AudioTrack instead of static one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Generate Pdf pages thumbnails Hiii I wanted to know about generating thumbnails in pdf in android. I want all the thumbnails of the pdf to be displayed when pdf is displayed. A: Andpdf is a port of pdf renderer so I think you can easily use this answer to get this done. A: It is possible to display PDF page in thumbnails using muPDF. Please check this link https://github.com/libreliodev/android. Enjoy!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7619312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python xlrd: suppress warning messages I am using xlrd to process Excel files. I am running a script on a folder that contains many files, and I am printing messages related to the files. However, for each file I run, I get the following xlrd-generated error message as well: WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero Is there a way to suppress this error message, so the CLI will only print the message I want it to? A: The answer by John works, but has a small problem: xlrd writes that warning message and the following newline character separately to the logfile. Therefore you will get an empty line in your stdout instead of the message, if you use the filter class proposed by John. You shouldn't simply filter out all newlines from the log output either though, because there could be "real" warnings that would then be missing the newlines. If you want to simply ignore all log output by xlrd, this is probably the simplest solution: book = xlrd.open_workbook("foo.xls", logfile=open(os.devnull, 'w')) A: Check out the relevant part of the xlrd docs. The 2nd arg of the open_workbook function is logfile which should be an open file object or act-alike. All it needs to support is a write method. It defaults to sys.stdout. So, something like this (untested) should do the job: class MyFilter(object): def __init__(self, mylogfile=sys.stdout): self.f = mylogfile def write(self, data): if "WARNING *** OLE2 inconsistency" not in data: self.f.write(data) #start up log = open("the_log_file.txt", "w") log_filter = MyFilter(log) book = xlrd.open_workbook("foo.xls", logfile=log_filter) # shut down log.close() # or use a "with" statement Update in response to answer by @DaniloBargen: It's not xlrd that's writing the newline separately, it's the Python print statement/function. This script: class FakeFile(object): def write(self, data): print repr(data) ff = FakeFile() for x in "foo bar baz".split(): print >> ff, x produces this output for all Pythons 2.2 to 2.7 both inclusive: 'foo' '\n' 'bar' '\n' 'baz' '\n' A suitably modernised script (print as a function instead of a statement) produces identical output for 2.6, 2.7, 3.1, 3.2, and 3.3. You can work around this with a more complicated filter class. The following example additionally allows a sequence of phrases to be checked for: import sys, glob, xlrd class MyFilter(object): def __init__(self, mylogfile=sys.stdout, skip_list=()): self.f = mylogfile self.state = 0 self.skip_list = skip_list def write(self, data): if self.state == 0: found = any(x in data for x in self.skip_list) if not found: self.f.write(data) return if data[-1] != '\n': self.state = 1 else: if data != '\n': self.f.write(data) self.state = 0 logf = open("the_log_file.txt", "w") skip_these = ( "WARNING *** OLE2 inconsistency", ) try: log_filter = MyFilter(logf, skip_these) for fname in glob.glob(sys.argv[1]): logf.write("=== %s ===\n" % fname) book = xlrd.open_workbook(fname, logfile=log_filter) finally: logf.close() A: import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() -> http://docs.python.org/library/warnings.html#temporarily-suppressing-warnings A: For what it's worth I had the same warning message; when I deleted the first row (which was empty) the warning disappeared. A: Based on John Machin's answer, here is some working code (tested with Python 3.6) that works with sys.stdout: import io import sys import xlrd path = "somefile.xls" # path to an XLS file to load or a file-like object for one encoding_override = None # Mute xlrd warnings for OLE inconsistencies class LogFilter(io.TextIOWrapper): def __init__(self, buffer=sys.stdout, *args, **kwargs): self.buffer = buffer super(LogFilter, self).__init__(buffer, *args, **kwargs) def write(self, data): if isinstance(data, str): if not data.startswith("WARNING *** OLE2 inconsistency: "): super(LogFilter, self).write(data) elif isinstance(data, bytes): super(LogFilter, self).write(data.decode(self.buffer.encoding)) else: super(LogFilter, self).write(data) def open_workbook(file_contents, encoding_override): logfilter = LogFilter() return xlrd.open_workbook(file_contents=file_contents, logfile=logfilter, encoding_override=encoding_override) if hasattr(path, 'read'): book = open_workbook(file_contents=path.read(), encoding_override=encoding_override) else: with open(path, 'rb') as f: book = open_workbook(file_contents=f.read(), encoding_override=encoding_override) A: If you're getting this warning with pandas' read_excel function, then you can do this: import os import xlrd import pandas as pd workbook = xlrd.open_workbook(your_path, logfile=open(os.devnull, "w")) df = pd.read_excel(workbook) # read_excel accepts workbooks too
{ "language": "en", "url": "https://stackoverflow.com/questions/7619319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: matplotlib: how do I easily fit the plot to the canvas May be that is a simple question - but I tried to solve it several times - and just can't make it work. My problem is that - my plot is larger than the canvas: Is there a way to make plot fit to the canvas - without changing the canvas size? Here's the code that I use to make a plot (thanks to the Louis): da = plt.figure() l1 = da.add_subplot(111).plot(dummyZ, delta_a, "k-") da.add_subplot(111).set_xlabel(r"$z/L$") da.add_subplot(111).set_ylabel(r"$\delta a(z)$") da.add_subplot(111).grid(True) da.savefig("da.png") And here's the preambule: import matplotlib.pyplot as plt plt.rcParams['font.size']=18 Edit: That's what I'm using now: da = plt.figure() l1 = da.add_subplot(111).plot(dummyZ, delta_a, "k-") da.add_subplot(111).set_xlabel(r"$z/L$") da.add_subplot(111).set_ylabel(r"$\delta a(z)$") da.add_subplot(111).grid(True) da.subplots_adjust(left=0.2, bottom=0.15) # !!! da.savefig("da.png") A: If I understand correctly the question, you want more room on the left to get the scale title ? This is to be done with fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) I had it with a simple subplots_adjust(top=0.8) to adjust the top of one of my draws. Hope this could help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Trying to make WYSIWYG on my page Being unlucky with this: A WYSIWYG Where it's possible to limit the text/height What should I do, i would like to have WYSIWYG, but the WYG part, (what you get) is inside a fixed sized box. And the editors out there makes scrollers/expands in height when you write more than the height you set the editor to. So what can i do? A: overflow: hidden in the right place should do the job. For CKEDitor, see CKEditor: Class or ID for editor body
{ "language": "en", "url": "https://stackoverflow.com/questions/7619326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending Email from SMTP server from a certain email, but make it appear as if coming from another email We have an application that prompts the user to login using his ldap username and password, from that I can get the user email but not the email password, My goal is to send email from this user's mail without the need to prompt the user for his email password. I am using the following code to send email NetworkCredential loginInfo = new NetworkCredential("[email protected]","mypassword"); MailMessage msg = new MailMessage(); sg.From = new MailAddress("[email protected]"); msg.To.Add(new MailAddress("[email protected]")); msg.Subject = "test"; SmtpClient client = new SmtpClient("smtp.mydomain.com"); client.EnableSsl = true; client.UseDefaultCredentials = true; client.Credentials = loginInfo; client.Send(msg); Is it possible to fake it, like send all emails form one email, but make the email look as if it is coming from the logged in user's email? That is only change the "From" field, to make the email look like : "From:[email protected]" but actually it is coming from "[email protected]" Note: We are obliged by SMTP Server setting to enter the password in the Network Credentials Thanks A: You can set it to whatever you like; if its being rejected its a decision that was made by the smtp server based on its security configuration - thats where you will need to make a change, not in your client code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Consume WSDL url with XML with escaped chars as argument I am executing a method of a SOAP web service which receives 3 string arguments with suds library. The first string argument should be an XML and the other 2 an username and password, this is my semi-working implementation. from suds.client import Client url = "http://www.jonima.com.mx:3014/sefacturapac/TimbradoService?wsdl" client = Client(url) client.service.timbrado(XML_AS_STRING_HERE, 'PRUEBA1', '12345678') When the first parameter contains an escaped character (ampersand, quotes, apostrophe, less than, bigger than) method does not work because the server interprets the text as if it were unescaped. If doesn't contain any of those chars the method works great XML example without ampersand works http://dl.dropbox.com/u/1990697/no_amp.xml XML example with ampersand doesn't work http://dl.dropbox.com/u/1990697/with_amp.xml Any idea how can I pass XML with escaped chars? It doesn't have to rely on suds but in python. I am using python 2.6 (How ever it could be with 2.7 if required) I am also using Django framework, don't know if that could be useful. Extra Info: * *I have no access to modify SOAP server *Customer support told me my xml are correct and that they work for them, so the error is in my implementation (or somewhere in suds?) A: You are easily able to 'escape' any XML values before it goes over to the service. Check out http://wiki.python.org/moin/EscapingXml >>> from xml.sax.saxutils import escape >>> >>> escape("< & >") '&lt; &amp; &gt;' This has worked for me in the past to do exactly what you're describing, pass XML data over a the net to a page. According to http://www.xmlnews.org/docs/xml-basics.html#references , just escaping the data before its sent will work just fine. To work off of your example XML ... descripcion="EJE&MPLO" ... after it goes through will be ... descripcion="EJE&amp;MPLO" ... A: I think the suds library is the culprit here. When you send your escaped xml into suds as a parameter to the client.service.timbrado method it also escapes it. However, it sees that you have escaped the ampersand already like this: ... descripcion="EJE&amp;MPLO" ... And it does not escape it further (although it should). You should run your escaped xml through xml.sax.saxutils.escape before passing it to client.service.timbrado. This should result in xml snippet above looking like this: ... descripcion="EJE&amp;amp;MPLO" ... When I run your code with the doubly-escaped xml, I receive the following result: <?xml version="1.0" ?> <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> <S:Body> <ns2:timbradoResponse xmlns:ns2="http://sefactura.com"> <return> <status>401 - Fecha y hora de generación fuera de rango</status> </return> </ns2:timbradoResponse> </S:Body> </S:Envelope> It is an error regarding your data (date and time of generation out of range), not about the format of the xml. A: Have you tried escaping them twice? If the service is broken, you should file a bug-report and take precautions so you will notice it when it gets fixed and your workaround should be removed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating a two column ordered list. Can I put a DIV between the OL and LI tags? Using the 960.gs framework, I'm trying to create a two columned ordered list where each list item contains a heading and paragraph and the numbering goes across, not down e.g. the top row contains 1,2 not 1,3. The only way I can get it to work is to put a DIV between the OL and LI elements. This doesn't feel right, I'm sure its wrong although I'm not sure why. What is the correct way to achieve this? I've got the following markup; <div class="container_16"> <ol> <div class="grid_8"> <li><h2>Heading</h2> <p>Paragraph</p> </li> </div> <div class="grid_8"> <li><h2>Heading</h2> <p>Paragraph</p> </li> </div> <div class="clear"></div> <div class="grid_8"> <li><h2>Heading</h2> <p>Paragraph</p> </li> </div> <div class="grid_8"> <li><h2>Heading</h2> <p>Paragraph</p> </li> </div> <div class="clear"></div> </ol> </div> A: It is invalid to place div elements inside the ol tag. Only li elements are allowed in there.. (check the W3C documentation on lists) The theory is to use ol{width:200px;} li{float:left;width:50%;} demo at http://jsfiddle.net/gaby/ZKdpf/1/ For the 960.gs system you should use <ol class="container_16"> <li class="grid_8">first</li> <li class="grid_8">second</li> <li class="grid_8">third</li> <li class="grid_8">fourth</li> <li class="grid_8">fifth</li> <li class="grid_8">sixth</li> </ol> and add in your css ol.container_16 li.grid_8{ display:list-item; } to show the numbers again.. demo at http://jsfiddle.net/gaby/ZKdpf/2/ Update Indeed as you mention in your comment you need to clear every two elements, since the height of the li elements is not the same.. For modern browsers you should add .benefits li:nth-child(odd) { clear: left; } or your can turn that in a class and add it to the odd numbered li elements. A: You right to 'feel wrong'. Lists contain list-items and nothing else. The easiest way, I think to achieve a horizontal numbering, is to float your LIs. A: The above source code is wront. You can't place anything else between <ol></ol> except <li></li> elements. You propably have to find another way to style out your lists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java live chat opensource Does anybody know any Java live chat opensource? I want to embed into the application. Please let me know. Thanks A: You could try using this one http://sourceforge.net/projects/llamachat I hope it's what you're looking for
{ "language": "en", "url": "https://stackoverflow.com/questions/7619336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Which one is faster ? Function call or Conditional if Statement? Please consider the branch prediction too before answering this question. I have some scenarios where i can replace a conditional statement with a call to a function with the help of function pointer.Some thing like this. (you can think of component based programming over inheritance for a similar type of senario) class Shape { float Area() { if(type == SQUARE) { return length*length; } else if(type == RECTANGLE) { return length*breadth; } } } The same class can be written like this. class Shape { void SetAreaFunction(void *funcptr)//this function is used to set the current AreaFunc { CurrentAreaFunc = funcptr ;//this holds the pointer to current area func } float SqauareArea();//this will return square area float RectangleArea();//this will return rectangle area float Area() { currentAreaFunc(); } } IF you consider the above cases, both achieves same results.But, I'm thinking about the performance overhead.In the second case I'm avoiding having branch prediction problem by having a function call. Now let me know which is the better practice and 'better optimized code' in this kind of senarios.(btw, I don't like the statement "Pre-mature optimization is root of all evil" as, optimization has its benefits so i do consider optimizing my code!) P.S: I don't mind if any one give a detailed overview about 'how bad branch prediction can be" even in assembly code. Update: After profiling (similar kind of above code), If Condition succeeded in this kind of senario.Can any one give a reason for this? Functional call code can be prefetched as there is no Branching code right? But here its looks the other way..branching code wins! :O Profiled on Intel Mac Osx,GCC O3/Os optimisation. A: You need to profile such code to be able to make a certain statement for a specific environment (compiler, compiler version, OS, hardware) and you need to measure in a specific application to be able to know whether this even matters for that application. Unless you are writing library code, do not bother except for when profiling has shown this to be a hot spot in your application. Just write the most readable code, that is easiest to maintain. It's always easier to optimize clean, bug-free, and easily readable code than to fix bugs optimized code. That said, I remember Lippman in his The C++ Object Model citing research that has found virtual functions (basically function pointers) to be at least as fast as switching over types in real-world applications. I don't know the details, but it's somewhere in the book. A: It is more likely that the optimizer can apply his magic on the if statement, then on a dynamically changing function pointer. Just a guess, theoretically the compiler is allowed to do anything that he can prove does not change the semantics. But in the case you do not call a function but only implement a branch (using an if in your case) the CPU is more likely to apply its magic, i.e. reorder instructions, prefetching things and the like. If there is an function call in between most CPUs will very likely "flush" their pipelines and CPU-optimization will not be possible. That said, if you put everything inside a header, caller and callees, the compiler may do away with functions calls, will reorder stuff itself and so on. Try to measure it yourself. Call it 1M times. With C++11 use <chrono>, monothonic_clock::now(). Update: My experience is: Don't over-optimize your code my hand -- it is very likely that you make it worse. Let the compiler do the work, and for that make as much code visible to it as you can. If you do, you definitely need a profiler, try out alternatives, use the hints some of them offer you. But don't forget: This must be fine-tuned very carefully. Only one measurement of performance is speed. There is also readability, testability and reusebility and many more. And to quote Donald Knuth: "Premature optimization is the root of all evil." A: You replaced an if statement with an indirection. Both your if statement, and the indirection requires memory access. However, the if will result in a short jump - which will probably won't invalidate the pipeline, while the indirection may invalidate the pipeline. On the other hand, the indirection is a jump, while the if statement is a conditional jump. The branch predictor may miss. It is hard to tell which is faster without testing it. I predict that the if statement will win. Please share your results!
{ "language": "en", "url": "https://stackoverflow.com/questions/7619338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: creating megamenu from hierachical Data using stored procedure I have a following table.I was trying to create a mega menu using single stored procedure. CategoryId Category_name ParentId displayorder 1 Electronics 0 1 2 Vehicles 0 1 3 Computer 1 2 4 Camera 1 2 5 Mobile 1 2 6 Car 1 2 i am using the query below to get a three column table. ;WITH Hierarchy AS ( SELECT Category_ID, Category_Name, Parent_ID,display_Order,show_Inmenu,Display_level FROM #tbl_Category WHERE Parent_ID = 0 UNION ALL SELECT t.Category_ID, t.Category_Name, t.Parent_ID,t.display_Order,t.show_Inmenu,t.Display_level FROM Hierarchy h INNER JOIN #tbl_Category t ON t.Parent_ID = h.Category_ID ) SELECT top 5 c.Category_ID,c.Category_Name, '<div>' + (Select '<a href="index.aspx?id=' + cast(d.Category_ID as varchar(5)) +'">' + d.Category_Name AS 'ul' From Hierarchy d Where d.parent_id = c.Category_ID ORDER BY d.Category_Name for xml path('')) + '</div>' as items FROM Hierarchy c WHERE c.Parent_ID = 0 and c.show_Inmenu=1 order by c.Display_order but the data getting from the select statement is how can i remove &lt; and &gt; from the items column. is there any method to create table as below.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php pdo save query data : Call to a member function rowCount() on a non-object in C:\wamp\www\prjy\classes\user.php on line 34 Line 29-32 $this->sth = $this->dbh->prepare("SELECT id, userlevel FROM users WHERE username = ? AND password = ?"); $this->sth->bindParam(1, $username); $this->sth->bindParam(2, $password); $this->data = $this->sth->execute(); Line 34 if ($this->data->rowCount() > 0) I want to save the result object in another variable, so I can execute another query and depending on the result, I return what is correct... Can't I save the result, (execute()) in a variable like above? How do I solve it else way? A: PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object. For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Reference A: What about using: count($this->data) for the row count? A: Matt is correct; PDOStatement::execute() returns a boolean value. And diEcho is partially correct about PDOStatement::rowCount(); the docs also say: If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications. Seeing you are using MySQL, this will work, but keep in mind that this may therefor not be portable to other RDBMSs. If portability is of no concern, PDOStatement::rowCount() is what you need and therefor you need to use this: if ($this->sth->rowCount() > 0) However, you'll need to save multiple PDOStatement objects. So I suggest doing something like the following: $stmt1 = $this->dbh->prepare( /* first select statement */ ); $stmt1->bindParam(1, $username); $stmt1->bindParam(2, $password); $stmt2 = $this->dbh->prepare( /* second select statement */ ); $stmt2->bindParam(1, $username); $stmt2->bindParam(2, $password); if( $stmt1->execute() && $stmt2->execute() ) { if( $stmt1->rowCount() > 0 ) { $result = $stmt1->fetchAll(); } else if( $stmt2->rowCount() > 0 ) { $result = $stmt2->fetchAll(); } } Or something of similar nature, depending on what criteria you will want the results of either one of the statements. PS.: be aware though, that in order for this to work, you would have to activate buffered queries for MySQL in PDO (if this wasn't activated already): $db = new PDO( 'dsn connection string', 'username', 'password', array( PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true ) ); A: You have to perform another test before calling rowCount(): $this->sth = $this->dbh->prepare("SELECT id, userlevel FROM users WHERE username = ? AND password = ?"); $this->sth->bindParam(1, $username); $this->sth->bindParam(2, $password); if($this->data = $this->sth->execute()) { if ($this->data->rowCount() > 0) { // do something here .. } } A: You are not testing for errors. PDOStatement::execute() returns false in case of an error. You should test for that! if (!$this->data = $this->sth->execute()) { echo "ERROR!"; print_r($this->sth->errorInfo()); die(); } Or something similar. That's probably the reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading indicator for MVC3 unrobustive remote validation I am doing the MVC3 unrobustive remote validation for checking username availability. It works fine, but it takes quite some time load the validation message! Is there any way to show a spinner/user name available checking message during the transition? A: You can do that with ajaxStart and ajaxComplete global methods. ajaxStart : http://api.jquery.com/ajaxStart/ ajaxComplete : http://api.jquery.com/ajaxComplete/ If you would like to implement some specific loading indicators (for example, inside the text input), you need to bind some methods with JQuery and listen to the remote validation. Then, when it kicks in, you can fire the indicator start method and when it is done, you can get it back. A: Use your ID attribute for activity_pane below jQuery('#activity_pane').showLoading(); jQuery('#activity_pane').load( '/path/to/my/url', {}, function() { // //this is the ajax callback // jQuery('#activity_pane').hideLoading(); } ); see http://contextllc.com/dev_tools/jQuery/showLoading/latest/jquery.showLoading.example.html Another link showing how to do this here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: C++ SDL keyboard response I have a problem with my game program. The program responds to my keyboard input but won't move far. It will only move 1 bit up. #include <SDL/SDL.h> #include "Mrn.h" int main (int argc,char** argv) { SDL_Init(SDL_INIT_EVERYTHING);//initialized everything. SDL_Surface* screen;//allows drawing on screen. screen=SDL_SetVideoMode(500,500,32,SDL_SWSURFACE);//sets resolution of screen. bool running = true; const int FPS = 30;//fps of the game. Uint32 start; while(running)//windows running loop. { start = SDL_GetTicks();//timer. SDL_Event event;//allows for events to happen. while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: running = false;//allows exiting. break; } } //game logic and rendering. player(screen); SDL_Flip(screen); if(1000/FPS > SDL_GetTicks() - start) { SDL_Delay(1000/FPS - (SDL_GetTicks() - start)); } } SDL_Quit(); return 0; } Player.h code: #include <SDL/SDL.h> #ifndef MRN_H_INCLUDED #define MRN_H_INCLUDED int player(SDL_Surface* screen) { SDL_Surface* Marine; SDL_Rect first; first.x = 0; first.y = 0; first.w = 42; first.h = 31; SDL_Rect position; position.x = 40; position.y = 40; Uint8 *key; key = SDL_GetKeyState(NULL); if(key[SDLK_w]) { position.y++; } Marine = SDL_LoadBMP("Images/Marine.bmp"); SDL_BlitSurface(Marine,&first,screen,&position); SDL_FreeSurface(Marine); return 0; } #endif // MRN_H_INCLUDED everything works fine except for its movement. It will never move far and on release it will move back to its original position. A: Every time you call player(), you are setting position to (40,40). You need to separate player's initialization from player's processing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which method in the Iterator interface can remove the previously returned element? I read the following in Data Structures and Algorithms by Goodrich : Java provides an iterator through its java.util.Iterator interface. We note that the java.util.Scanner class (Section 1.6) implements this interface. This interface supports an additional (optional) method to remove the previously returned element from the collection. This functionality (removing elements through an iterator) is somewhat controversial from an object-oriented viewpoint, however, and it is not surprising that its implementation by classes is optional I don't understand what the author is referring to here. Which is the method in discussion here and what does it do? A: Iterator.remove(), which removes the last node returned by a call of next() or previous() (if it is a ListIterator) A: In the Iterator Interface, there is an remove() function which can be optionally implemented. The Docs say: Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. Basically it goes into the collection from where the iterator was spawned and removes the element in the current iteration from the original collection. A: Probably the Iterator.remove() method. A: The method in question is Iterator.remove() which is part of the Iterator interface. A lot of Iterator instances don't support it - if you try to call it on the wrong kind of iterator you will most likely get an UnsupportedOperationException. I personally don't think remove() is a very good idea as part of the Iterator interface: the primary conceptual purpose of an Iterator is to do a single pass through the elements of a collection and return these elements in sequence. If you follow the "do one thing well" school of design, then it's a bad idea to also try to use Iterators as a technique for modifying such collections. Such behaviour can also cause big headaches from a concurrency perspective.... A: public interface Iterator { public abstract boolean hasNext(); public abstract Object next(); public abstract void remove(); } The remove() method is optional and removes the last element returned by next() from the Collection. A: The remove() method will delete the element that was most recently returned from next().
{ "language": "en", "url": "https://stackoverflow.com/questions/7619351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can we use domain model at UI layer in MVVM pattern Can I use domain model at UI layer instead of view model in some of the views. If No. Why shouldn't I use? A: If you are exposing some model objects in a list to an ItemsSource, I think this completely fine. I generally take the approach to only wrap a model such as this in a ViewModel when: * *I need custom formatting of a property that seems cleaner to do in a ViewModel than using IValueConverter *I need to put a method/ICommand on the object I wouldn't do it if the models are somehow bound to a View not in an ItemsSource such as a Window or UserControl, however. If you are finding you have ViewModels that don't have very many properties or methods/ICommand, then you need to merge several into the one ViewModel.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing JpegEncoder class from JavaScript in Adobe AIR application I need to encode a BitmapData object using the JPegEncoder in a Adobe AIR application using JavaScript I am trying to create a JpegEncoder object var encoder=new window.runtime.mx.graphics.codec.JPEGEncoder() and I get the error TypeError: Result of expression 'window.runtime.mx.graphics.codec.JPEGEncoder' [] is not a constructor. I am not sure if I done something wrong or it is not possible to access that class This is my mxml header <?xml version="1.0" encoding="utf-8" standalone="no"?> <application xmlns="http://ns.adobe.com/air/application/2.6"> Update: I found that you need to add a reference to the swf/swc ,here is a smaple code for an application that uses rpc <script type="application/x-shockwave-flash" src="lib/air/swf/framework/framework/library.swf"></script> <script type="application/x-shockwave-flash" src="lib/air/swf/framework/rpc/library.swf"></script> I tried adding mx instead of rpc but it does not work, I am thinking if i need to deploy the mx.swc file with the application?(i think it should not be needed) or maybe it can't resolve that path I solved it by deploying the framework.swf file wioth the application but can it be done without it?Is this file present on the client machines? A: Not sure why the 'window.runtime'... using xmlns:mx="http://www.adobe.com/2006/mxml" and explicitly importing the class works fine for me... And you would also get a compiler warning about not specifying a type for the variable, ie you want: import mx.graphics.codec.JPEGEncoder; var encoder:JPEGEncoder = new JPEGEncoder(); And please - I have seen far to much AS code that relies on not requiring a semi-colon to terminate a statement - use them - the FB ide is much nicer if you do (auto-correct indenting etc), not to mention this often leads to mixed 'usage' with some lines using it other not - I wish adobe would remove this 'feature'
{ "language": "en", "url": "https://stackoverflow.com/questions/7619356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: UIImage Does Not Load Image I am using UIImage to plot a png. I have getting a weird behavior that I cannot understand. The following piece of code results in a nil im reference and thus prints "PROBLEM!" UIImage *im = [[UIImage alloc] initWithContentsOfFile:@"tree.png"]; if (nil==im) NSLog(@"PROBLEM! IMAGE NOT LOADED\n"); else NSLog(@"OK - IMAGE LOADED\n"); This piece of code works finely: UIImage *im = [UIImage alloc]; [im initWithContentsOfFile:@"tree.png"]; if (nil==im) NSLog(@"PROBLEM! IMAGE NOT LOADED\n"); else NSLog(@"OK - IMAGE LOADED\n"); What am I missing? A: [[UIImage alloc] initWithContentsOfFile:@"tree.png"]; will return to you image if image /tree.png exist. But it doesn't exist. You should pass to initWithContentsOfFile full path, not only name of file. Now, second one code works because of [UIImage alloc] return some reference that is not initialized. In next line your are trying to init it with [im initWithContentsOfFile:@"tree.png"]; but you've forgotten to save returned value in im, like this: im = [im initWithContentsOfFile:@"tree.png"];. If image tree.png is saved in your bundle, then you can use such approach : UIImage *im = [UIImage imageNamed:@"tree.png"]; or such: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"tree" ofType:@"png"]; UIImage *im = [[UIImage alloc] initWithContentsOfFile:filePath]; A: Is the image in your bundle and is it a PNG image? The UIImage Documentation mentions the following when using initWithContentsOfFile: An initialized UIImage object, or nil if the method could not find the file or initialize the image from its contents. Also, since you are using the UIImage locally I assume from your code, you could just use the imageNamed: class method like so and it will search for the image in your main bundle: UIImage *im = [UIImage imageNamed:@"tree.png"]; if (nil==im) NSLog(@"PROBLEM! IMAGE NOT LOADED\n"); else NSLog(@"OK - IMAGE LOADED\n"); A: try: NSString *path = [[NSBundle mainBundle] pathForResource:@"tree" withExtension:@"png"]; UIImage *im = [[UIImage alloc] initWithContentsOfFile:path]; to load the image from your application bundle. A: BTW, your second piece of code is potentially dangerous. Actually initWithContentsOfFile: calls autorelease for the object, if file is not found. And if you tried to access image after a while, it would be an error (EXC_BAD_ACCESS). So that you should always use init methods in pair with alloc and do not forget to release is somewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Optimize two COUNT/DISTINCT queries I have a table with column1 and column2 (both of them contain TEXT). I want to get: 1) the count of unique rows of column1@table, case-insensitive 2) the count of unique rows of column1@table and column2@table, case-insensitive SELECT count(*) AS unique_row1 FROM (SELECT DISTINCT lower(column1) FROM table); SELECT count(*) AS unique_rows12 FROM (SELECT DISTINCT lower(column1),lower(column1) FROM table); Is there a more efficient way to do it? Is there's a way to do it in a one query? I use SQLite3. Thanks in advance. Edit (due to @ypercube's response): Collation was default (case-sensitive, at least I didn't do COLLATE NOCASE anywhere). Also I've made a test and with COLLATE NOCASE it's quite faster and the numbers are the same: # time echo "SELECT count(DISTINCT lower(column1)), count(DISTINCT lower(column1 || column2)) FROM table;" | sqlite3 db.sqlite3 1643|5997 echo 0.00s user 0.00s system 25% cpu 0.003 total sqlite3 db.sqlite3 0.58s user 0.04s system 96% cpu 0.643 total # time echo "SELECT count(DISTINCT column1), count(DISTINCT column1 || column2) FROM table;" | sqlite3 db.sqlite3 1658|6199 echo 0.00s user 0.00s system 36% cpu 0.002 total sqlite3 db.sqlite3 0.42s user 0.04s system 95% cpu 0.483 total # time echo "SELECT count(DISTINCT column1 COLLATE NOCASE), count(DISTINCT (column1 || column2) COLLATE NOCASE) FROM table;" | sqlite3 db.sqlite3 1643|5997 echo 0.00s user 0.00s system 32% cpu 0.002 total sqlite3 db.sqlite3 0.43s user 0.04s system 98% cpu 0.481 total COUNT(DISTINCT column1, column2) shows an error though: wrong number of arguments to function count(), but I hope I've got your idea. A: You can try this: SELECT count(distinct lower(column1)) FROM table And for the second: SELECT count(distinct lower(column1 || column2)) FROM table Note: In this second case you must use coalesce if your columns can be nulls. A: I think that text comparisons are by default case-insensitive. Does this work? SELECT COUNT(DISTINCT column1) , COUNT(DISTINCT column1, column2) FROM table
{ "language": "en", "url": "https://stackoverflow.com/questions/7619368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Retrieve a value from a table in a subview From a view, I push a tableView where the back button is hidden. When one row is selected, the "back button" appear. I would like to pass to the value of the selected row as the user tap on the back button as content of a textField. This is the code of the tableView (CategoryListController.m): -(NSString *)ritornaValore { return valoreCategoria; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.navigationItem setHidesBackButton:NO animated:YES]; NSDictionary *rowVals = (NSDictionary *) [categoryListItems objectAtIndex:indexPath.row]; valoreCategoria = (NSString *) [rowVals objectForKey:@"key"]; [self ritornaValore]; } valoreCategoria is a NSString declared in the .h In AddItemController i have this "categoryNameField" where i would like to put inside the value of "valoreCategoria" categoryNameField.text = ? A: Before pushing CategoryListController from AddItemController you should save reference (i.e. categoryController) to category list controller. In viewWillAppear of AddItemController you should check if categoryController != nil. If it is not nil, then you can try to retrieve value : categoryNameField.text = [categoryController ritornaValore];. And if you don't need anymore categoryController then you should release it self.categoryController = nil;. Check that categoryController is defined as @property (nonatomic, retain) CategoryListController *categoryController; and valoreCategoria as @property (nonatomic, retain) NSString *valoreCategoria;.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass an int value from one activity to other can anyone help what is the problem in my code Activiy 1: int view=1; TabFunctionality.setFirstTabFunctionality(TabFunctionality.FIRST_TAB, 1); Intent intent = new Intent(AdultTeeth.this, MainScreen.class); Bundle b = new Bundle(); b.putInt("TEXT", view); intent.putExtras(b); startActivityForResult(intent, TEETH_VIEW); finish(); Activity 2: Bundle b = this.getIntent().getExtras(); int view=b.getInt("TEXT"); A: Passactivity: Intent i = new Intent(view.getContext(), Passactivity.class); i.putExtra("font",selected_font); startActivity(i); Receving activity private int my_size; Intent i = getIntent(); my_size = i.getIntExtra("size",20); // 20 for default value. A: You can directly use putExtra also. Activity 1 Intent intent = new Intent(AdultTeeth.this, MainScreen.class); intent.putExtra("int_value", int_variable); startActivity(intent); Activity 2 Intent intent = getIntent(); int temp = intent.getIntExtra("int_value", 0); // here 0 is the default value A: The answers given are here aren't wrong but they are incomplete in my opinion. The best way to do this with validations is to make sure that the extra is taken from the previous Activity as well as the savedInstanceState which is the Bundle data received while starting the Activity and can be passed back to onCreate if the activity needs to be recreated (e.g., orientation change) so that you don't lose this prior information. If no data was supplied, savedInstanceState is null. Sending data - Intent intent = new Intent(context, MyActivity.class); intent.putExtra("name", "Daenerys Targaryen"); intent.putExtra("number", "69"); startActivity(intent); Receiving data - @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.myactivity); int no; String na; if(savedInstanceState == null){ Bundle extras = getIntent().getExtras(); if(extras != null){ no = Integer.parseInt(extras.getString("number")); na = extras.getString("name"); } }else{ no = (int) savedInstanceState.getSerializable("number"); na = (String) savedInstanceState.getSerializable("name"); } // Other code } A: in first activity :: intent1.putExtra("key",int_score); startActivity(intent1); second Activity :: Intent i1 = getIntent(); int temp = i1.getIntExtra("key",1); int temp = i1.getIntExtra("tranningscore2", 1); A: use this code may its work. intent.putExtra("Text", view); activity 2: int i = getIntent().getIntExtra("Text", 0); where 0 is the default value. A: in first activity Intent i = new Intent(name_class.this, name_class.class); i.putExtra("valu1",valu1); i.putExtra("value2", valu2); second Activity :: Bundle bundle = this.getIntent().getExtras(); String valu1 =bundle.getString("value1"); String value2 = bundle.getString("value2"); A: just pass it like a string and typecast it
{ "language": "en", "url": "https://stackoverflow.com/questions/7619380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Where is the access violation is my code? I'm getting an Access Violation when attempting to run this code which finds prime numbers in a bound. int main () { cout << "Program initialized successfully. Please wait for the next message to appear." << endl << endl ; int Primes[51] ; int runner = 0 ; int chaser = 0 ; int bound = 0 ; int count = 0 ; cout << "Please enter the maximum boundary of the calculation : " ; cin >> bound ; cout << endl << "The number you've entered, " << bound << ", has been accepted. Please wait for the calculations." << endl ; if (runner <= bound ) { Primes[0] = 2; Primes[1] = 3; Primes[2] = 5; Primes[3] = 7; Primes[4] = 11; count = 4; for ( runner = 11 ; runner <= bound ; runner ++ ) { while ( runner % Primes[chaser] != 0 ) { for ( chaser = 0 ; Primes[chaser] != 0 ; chaser ++ ) { if ( runner % Primes[chaser] == 0 ) { count ++ ; Primes[count] = runner; } } } } int chaser_count; cout << "Here's the primes computer discovered : " << endl ; for ( chaser_count = 0 ; chaser_count <= count ; chaser_count ++ ) { cout << Primes[chaser_count] << endl ; } cout << "There is " << count << " primes discovered." << endl ; } return 0; } The program runs fine until to the line of calculation : if(runner <= bound) I got a Access Violation. I Kind of know what an Access Violation is, but I don't know what raised it. edit: I got 2 answers now stating that I may have something like Primes[50] going on, but I seriously doubt so, because I get the error immediately after I specify the bound, 12. Thanks for the guy who de-comment this. I'm using Dev-C++. I found the place where the error was raised. Thanks for anyone who commented and answered for me. It is an logical error that I didn't found that leads to a Prime[51]. Thank you all for helping me. A: Here : for ( chaser = 0 ; Primes[chaser] != 0 ; chaser ++ ) { you didn't initialize you Primes array with 0, so the loop can loop over and over and chaser can be bigger than 51 (the size of you Primes array) and then Primes[something_bigger_than_50] will raise an access violation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Emacs fix the indentation of the java-mode Suppose that code : Command provisionHostCommand = new Command() { @Override public void execute() { final List<Host> hosts = new ArrayList<Host>(display.getSelectionModel().getSelectedSet()); eventBus.fireEvent(new ProvisioningHostEvent(hosts)); } }; Take a look about the indention. There's 4 spaces for the Command anonymous class. I have my c-basic-offset set to 2. How can I reduce the indentation space in a anonymous class ? Thanks. A: Well, this seems to work for me: (c-set-offset 'inexpr-class 0) I'm not quite sure why, though, I've looked at the documentation and it seems to suggest that anonymous classes should only be indented by c-basic-offset. Perhaps they're indented twice because of the opening curly brace? Edit: How about this workaround from http://www.mail-archive.com/[email protected]/msg01159.html? (add-hook 'c-mode-common-hook '(lambda () (c-set-offset 'substatement-open 0) (if (assoc 'inexpr-class c-offsets-alist) (c-set-offset 'inexpr-class 0))))
{ "language": "en", "url": "https://stackoverflow.com/questions/7619399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set a different language to the ListContents in my ListView I have two simple ListViews: public class SimpleListView extends Activity { private ListView lv1 = null; private ListView lv2 = null; private String s1[] = {"a", "b", "c", "d", "f", "g","h","i"}; private String s2[] = {"j", "k", "l", "m", "n", "o","p","q"}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv1 = (ListView) findViewById (R.id.list1); lv2 = (ListView) findViewById (R.id.list2); lv1.setAdapter(new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, s1)); lv2.setAdapter(new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, s2)); } } Here I want to list-contents i.e. s1 and s2 to be of different language instead of a,b,c.. How can I do that? Thanks EDIT: According to language support in android I came to know that I can set different language to the TextViews.Now I want to set the language to the list-contents. A: Well if you're asking how to find out what the active language on the device is look here Get the current language in device then fill your s1 and s2 according to the language A: You should use localized strings.xml files. Your res/values folder contains a strings.xml file. By creating additional values folders with a translated strings.xml file, you can cover all the regional languages you want. Here are some examples: * *res/values (for English) *res/values-de (for German) *res/values-zh (for Chinese) *res/values-es (for Spanish) *res/values-no (for Norwegian) *res/values-da (for Danish) All the folder must contain a strings.xml file with the translated strings. If your original strings.xml file looks like this: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">English title</string> </resources> ... then it could be like this for the German version: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">German title</string> </resources> Using string resources If you want to get a string from the strings resources, then here's how you do. In code: getString(R.strings.app_name) // returns "English title" for English users, "German title" for German users, etc. In layout: @string/app_name More info The Android developer site has an excellent guide on the subject here: http://developer.android.com/guide/topics/resources/localization.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7619400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery - Url checker (rss, audio or video podcast) i try to built an url checker using the google feed api. My problems: 1: the if(result) check doesn't work. Maybe an async problem? 2: any ideas for the rss,audio/video podcast check? I'm sure, i get in the response an url to the audio/video file (but i'm blind at the moment). My idea is to check this url. // somthing like that if(typeof xxxx == 'undefined') -> rss feed if xxxx.match(/mp3|wav|XXX/gi) -> audio feed if xxxx.match(/mpg|avi|flv/gi) -> video feed JS $(document).ready(function() { // valid rss feed var result = urlCheck('http://www.bild.de/rssfeeds/vw-home/vw-home-16725562,short=1,sort=1,view=rss2.bild.xml'); if(result){ console.warn('result1 is a '+result.urlIsA+' '); console.dir(result); } // valid video podcast var result = urlCheck('http://www.tagesschau.de/export/video-podcast/webl/tagesschau/'); if(result){ console.warn('result1 is a '+result.urlIsA+' '); console.dir(result); } // valid audio podcast var result = urlCheck('http://chaosradio.ccc.de/chaosradio-latest.rss'); if(result){ console.warn('result1 is a '+result.urlIsA+' '); console.dir(result); } }); function urlCheck(url) { var feed = new google.feeds.Feed(url); feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT); feed.setNumEntries('1'); feed.load(function(result) { if (!result.error) { var allEntries = result.feed.entries; console.info(url); console.dir(allEntries); /* if(XXX.match(/XXXX/,gi)) { allEntries.urlIsA = 'rss feed'; return allEntries; } if(XXX.match(/XXXX/,gi)) { allEntries.urlIsA = 'audio podcast'; return allEntries; } if(XXX.match(/XXXX/,gi)) { allEntries.urlIsA = 'video podcast'; return allEntries; } */ return false; } else { return false; } }); } Working examplehttp://jsbin.com/unikak/edit#javascript,html notice: your must copy the code in an *.html file, otherwise you get an error from jsBin google.feeds.Feed is not a constructor A: Change your RegExps, so that only mpg at the end of a string is matched: /(mpg|avi|flv/)$/gi Instead of using return, use callback functions: function urlCheck(url, callback){ .... //Insread of return false: callback(false); //Instead of return true: callback(true); At your result checker: urlCheck("http://....", function(result){ if(result){ console.warn(...); } else { //.. } })
{ "language": "en", "url": "https://stackoverflow.com/questions/7619407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recipients bar in an iPhone App I would to insert a recipients bar in an iPhone application, a bar that list address book items when I type chars on it, the same that is used in the iPhone SMS native application. How can I do? A: This is achieved using a UISearchDisplayController. You can see how to do this in Apple's TableSearch example code. A: Apple doesn't provide a public API for that type of input field. You can implement it yourself, or you can look for someone else's implementation, like JSTokenField.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get categories from a limited query i have the following query: select company_title,address,zipcode.zipcode,city,region,category from test.companies left join test.address on companies.address_id = address.address_id left join test.zipcode on companies.zipcode_id = zipcode.zipcode left join test.categories on companies.category_id = categories.category_id where company_title like '%gge%' limit 10; as you see, each company has a category. i was wondering if i can get a list of the categories (from the total results, not the limited one) just as CALC FOUND ROWS does? A: Nope, you are asking for a totaly different set of data here, you can only do another query or process this with your application code by preloading all data and counting the distincts in memory. If your dataset is big, then i'd recommend using a second query, mysql can support 1 more query easy, but working with 100 000 rows to count the distinct and preload everything is usually not the wiser choice :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7619411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assign variable in smarty? I have assigned two array to smarty : profiles and selected_id . profiles array contains the array of all profiles and the selected_id array contains ids of the profiles to be displayed .So I am displaying the all profiles like this : <select id="countries" class="multiselect" multiple="multiple" name="profiles[]"> {foreach name = feach item = k from = $profiles} <option value="{$k->bz_pro_id}">{$k->bz_pro_first_name} {$k->bz_pro_last_name}</option> {/foreach} </select> Now I want to default select the ids that are already selected by admin . That means if I want to add selected = "selected" in the option of select . For that I write : {foreach name = feach item = k from = $profiles} {foreach name = feach2 item = k2 from = $selected_id} {if $k->bz_pro_id == $k2->bz_pro_id} selected = "selected" {/if} {/foreach} {/foreach} So can I assign the select = "selected" to a variable so that I can use it in the option ? A: I have tested this, and it works. Assuming your arrays look something like this: $profiles[] = array ( 'bz_pro_id' => '1', 'bz_pro_first_name' => 'test1', 'bz_pro_last_name' => 'test2'); $profiles[] = array ( 'bz_pro_id' => '2', 'bz_pro_first_name' => 'test3', 'bz_pro_last_name' => 'test4'); $selected_id = array('1'); The syntax you're using to access variables and array members isn't correct. This is the working solution: <select id="countries" class="multiselect" multiple="multiple" name="profiles[]"> {foreach name=feach item=k from=$profiles} <option value="{$k.bz_pro_id}" {if in_array($k.bz_pro_id, $selected_id)}selected{/if}> {$k.bz_pro_first_name} {$k.bz_pro_last_name} </option> {/foreach} </select> A: you can use following code. <select id="countries" class="multiselect" multiple="multiple" name="profiles[]"> {foreach name = feach item = k from = $profiles} <option value="{$k->bz_pro_id}" {if $k->bz_pro_id|in_array($selected_id)}selected = "selected"{/if} >{$k->bz_pro_first_name} {$k->bz_pro_last_name}</option> {/foreach} </select> A: {assign var="name" value="Bob"} Reference: http://www.smarty.net/docs/en/language.function.assign.tpl
{ "language": "en", "url": "https://stackoverflow.com/questions/7619412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I grab information which users have set to private by using Graph API? If the user has set the information (e.g. movies, books, TV) to private instead of public, can I still grab such data by using the Graph API? A: If you request the appropriate extended permission like user_activities, etc then the API will return you that info for the current user regardless of privacy setting. If you try to get info from friends by asking for friends_activities etc then the privacy settings do come into play and if the friend restricts you from seeing that information, then you will not be able to see it. You also won't be able to see that info if the user opted out of the Facebook App Platform entirely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to debug HTTP traffic of a Windows 8 Metro style apps using Fiddler? I'm using 'HttpClient' in a Windows Metro style app and want to see the traffic using Fiddler. However, when Fiddler is active I get an exception that the app can't connect to the server. What's the problem? A: The answer is in this article: "Fiddler and Windows 8 Metro-style applications". Turns out that "connecting to Fiddler requires an Application Capability or Loopback Exemption".
{ "language": "en", "url": "https://stackoverflow.com/questions/7619419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Lagging of the run() method are to strong private static int millis_per_tick = 1; public void run() { // While not stop do while(true) { Thread t = Thread.currentThread(); long startTime, timeTaken; startTime = System.currentTimeMillis(); act(); timeTaken = System.currentTimeMillis() - startTime; if(timeTaken < millis_per_tick ) { try { Thread.sleep(millis_per_tick-timeTaken ); } catch(InterruptedException ex) {} } The thread.sleep method does not accept double values only float and integer. But i need a value under 1. In Space public void act() { ListIterator<Body> iterator = bodies.listIterator(); while (iterator.hasNext()) { Body body = iterator.next(); body.wirkenKraefte(); body.move(); } spaceGUI.repaint(); A: Check out the Thread.sleep(long,int) method in the API. Causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds. A: This is not possible. 1ms is even more than 1ms (15.6ms) and this is not guranteed. -> Can I improve the resolution of Thread.Sleep? A: You can't sleep for less than a millisecond using Thread.sleep(long) - and on many platforms, you'll find that even sleeping for one millisecond will actually sleep for longer (e.g. 15 milliseconds) depending on the granularity of the system clock. In other words, you basically can't do what you're trying to do with Thread.sleep(long) - and trying to get a sub-millisecond precision time is troublesome in the first place. You can try using System.nanoTime() instead, which is only appropriate for elapsed times (so fine in this case) - and you might want to consider a spin-lock to wait until the right time, instead of sleeping. In most cases it's a bad idea to even try to execute something at a fixed rate of 1000 calls per second though... what's the use case here? There may be a better approach. EDIT: I've just noticed that there is Thread.sleep(millis, nanos) - you could try using this and sleep for (say) 0 milliseconds and 100,000 nanoseconds. You should be aware that on most platforms this won't actually do what you want though. You can try it for your particular use case, but I wouldn't personally hold out too much hope.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: bucket sort analysis A simple example is bucket sort. For bucket sort to work, extra information must be available. The input a1, a2, . . . , an must consist of only positive integers smaller than m. (Obviously extensions to this are possible.) If this is the case, then the algorithm is simple: Keep an array called count, of size m, which is initialized to all 0s. Thus, count has m cells, or buckets, which are initially empty. When ai is read, increment count[ai] by 1. After all the input is read, scan the count array, printing out a representation of the sorted list. This algorithm takes O(m + n); If m is O(n), then the total is O(n). Although this algorithm seems to violate the lower bound, it turns out that it does not because it uses a more powerful operation than simple comparisons. By incrementing the appropriate bucket, the algorithm essentially performs an m-way comparison in unit time. This is similar to the strategy used in extendible hashing. This is clearly not in the model for which the lower bound was proven. My question on above paragraph * *What does author mean by "it uses a more powerful operation than simple comparisons"? *By incrementing the appropriate bucket, how algorithm performs an m-way comparision? By the way what is m-way comparision? *How above bucket sort strategy is related to extensible hashing? can any one pls give an example with extensible hashing? Thanks! A: * *the count[arr[i]] is more 'powerful' then comparison because it is actually *(count + arr[i]). each comparison op has 2 possible values: true/false, while this op has much wider range of values, [all possible addresses!] and thus it is more 'powerful' *by increasing the element, the algorithm 'knows' later how many elements where in this 'bucket', and later: just 'spill' the bucket's content out. the m-way comparison the author means, I assume is a 'comparison' with m possible outputs, as I explained above. *this is basically a hashing, you hash your elements to the range [0,m]. the importance and difference here is: two elements are hashed to the same number, if and only if they are identical. this of course can be achieved only if you hash elements with the same [or less] range then the image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine which SQLException has been returned / where's the error codes list? I'm using com.mysql.jdbc.Driver (If it means anything). I want to be able to catch and properly process the exceptions I receive from MySQL. I want to know if the transaction failed, if there's already a primary key with the value I'm trying to insert, and all the other errors. I want to do something like try { ... // Code } catch(SQLException e) { switch(e.getErrorCode()) { case... case... default... } } I've tried looking, but haven't found any, only some entries which talk about C# / .net The main reason I want this is to see if one of my transactions rolled back because of the Isolation level I put, in that case, I'll have to retry it. And of course, some other issues. Your help is much appreciated! A: drivers information is required, as the error codes returned are vendor specific. Please have a look at the following error codes for mysql, might be helpful http://www.briandunning.com/error-codes/?source=MySQL A: The MySQL error codes are all documented in the manual (surprise!) http://dev.mysql.com/doc/refman/5.1/en/error-handling.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7619430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bash: read a file line-by-line and process each segment as parameters to other prog I have some dirty work to do, so a Bash script seems to be a good choice. I'm new to Bash, and the experience makes me kind of frustrated. The file mapfiles.txt consists of lines as follow. Each line has four segments separated by a white space. Each segment represents a input parameter to an external program name 'prog'. For example, "cm19_1.png" is the filename, "0001" the index, "121422481" the longitude, and "31035995" the latitude. File: mapfiles.txt cm19_1.png 0001 121422481 31035995 cm19_2.png 0002 121423224 31035995 cm19_3.png 0003 121423967 31035995 … I want to execute similar commands to each line. As show below, the prog's input parameter order is slightly different. So it makes sense to write a bash script to handle the repeated work. [Usage] prog <index> <longitude> <latitude> <filename> example: prog 0001 121422481 31035995 cm19_1.png Generally, the bash script will operate in this way: * *Read one line from mapfiles.txt *Split the segments *Call the prog with a correct parameter order Here comes run.sh. #!/bin/sh input=mapfiles.txt cmd=prog while read line do file=$(echo $line | cut -d' ' -f1) key=$(echo $line | cut -d' ' -f2) log=$(echo $line | cut -d' ' -f3) lat=$(echo $line | cut -d' ' -f4) echo $cmd $key $log $lat $file done < "$input" What I expected is prog 0001 121422481 31035995 cm19_1.png prog 0002 121423224 31035995 cm19_2.png prog 0003 121423967 31035995 cm19_3.png … The ACTUAL result I got is cm19_1.png21422481 31035995 cm19_2.png21423224 31035995 cm19_3.png21423967 31035995 Problems that confused me * *Where is 'prog'? *Where is the white space? *What's wrong with the parameter order? Hmm… I wrote this script on my Mac using vim and copy it to a Scientific Linux box and a gentoo box. These three guys get the same ridiculous outputs. A: You can simplify this a lot: while read file key log lat do echo "$cmd" "$key" "$log" "$lat" "$file" done < "$input" A: prog could have disappeared because $cmd is not exported. Your version of /bin/sh might execute the while statement in a separate shell. This should not be the case, and this is not the case for my installation of bash, but perhaps yours behaves in interesting ways in this department. UPD I see that you have several boxes that give the same results. This makes the subshell theory unlikely. Perhaps you have some funny characters in your script and/or source file. I have copied and pasted your script and your source file to my gentoo box and it gives the expected results. Perhaps you should do the same, and compare the files with your original ones. A: Using GNU Parallel you can do it in a single line + you get it done in parallel for free: cat mapfile.txt | parallel --colsep '\s' prog {2} {3} {4} {1} Watch the intro videos to learn more: http://www.youtube.com/watch?v=OpaiGYxkSuQ
{ "language": "en", "url": "https://stackoverflow.com/questions/7619438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Add shortcut to website in right-click menu for chrome extension? I would like to add a website shortcut in the right click menu when clicking on the icon for the google chrome extension. A: You can't access that context menu, only the one you get by right clicking on the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select bin/tray when printing with javax.print I'd like to specify the input bins when printing with Java. I've found the MediaTray class which should correspond to the input bins: The following standard values are defined for input-trays (from ISO DPA and the Printer MIB): 'top': The top input tray in the printer. 'middle': The middle input tray in the printer. 'bottom': The bottom input tray in the printer. 'envelope': The envelope input tray in the printer. 'manual': The manual feed input tray in the printer. 'large-capacity': The large capacity input tray in the printer. 'main': The main input tray 'side': The side input tray Source: https://www.rfc-editor.org/rfc/rfc2911 The problem is, that I get a number from the application which specifies the input bin. Can I simply map the enum int values or what is the common way to get to the enum value with a number? Is it even officially supported to number the trays? I couldn't find attributes in the RFC that correspond to the output bins. Is there also a way to do that? And the most important question: Is the printer interface more or less reliable? Most threads I found where people asked about the trays eventually gave up, because they couldn't get it to work. Any experiences would be appreciated. A: These attributes are defined in javax.print.attribute.standard.MediaTray. See also, Standard Attributes: Media. A: If you want to use the actuall tray number instead of the general constants like TOP, you'll have to do some extra coding. There isn't any enum that lists all the tray numbers for a given printer because it isn't known at the time of coding how many trays there will be. You need to query the printer service for all it's supported attribute values for the attributetype Media.class. This will give you a list of different types. Print the results, the trays should be somewhere in this list. It's important to take the tray from this list and not to construct it yourself because some internall code in the printing framework is linked to this. Note: The printing api has some bugs related to tray printing (especially on unix). To resolve them quickly, vote for: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7107175 and/or http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7107138 A: This how to print to "Tray 1" (if it exists): PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); Media[] supportedMedia = (Media[]) prnJob.getPrintService().getSupportedAttributeValues(Media.class, null, null); for (Media m : supportedMedia) { if (m.toString().equals("Tray 1")) { aset.add(m); break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7619451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Spring Security Plugin in Modular Applications I'm starting a new, modular Grails application. I'm creating a domain plugin and of course need a User/Person domain. Do I add the Spring Security Core plugin to domain, just to generate the its user domain? If so, do I also add the plugin to the main app. Or since the main app will use the domain plugin, will it inherit the Spring Security plugin? In either case, is there anything I need to know or do differently than if I just had 1 application with the domain objects? UPDATE I added this to the buildconfig of my main app: plugins { . . . compile ":spring-security-core:1.2.1" . . . } grails.plugin.location.astdomain ="C:\\src\\astool\\astdomain" Doing generate all in the main app didn't work. The domain I specified was not found. So I did a generate all in the domain plugin then moved the generated code into the main app. And even though the generated code has the same package as the domains, I still get a compile error saying the domain isn't found. A: Check out the section on plugins. I believe the distribution process has changed, however, as the Release plugin seems to be becoming mainstream/the de-facto standard as of Grails 2.0. It all depends on how you set it up. You should be able to add the spring security plugin to your plugin (which is essentially what you are doing in building a modular app, building a larger one as a series of plugins) and specify plugin dependencies, build orders, and the such that way. With the right setup, you should be able to write your self-contained plugin, run a grails install-plugin on the main app referencing your plugin, and then use package resolution to get access to your plugin's domain classes in the main app's other classes. A: It turned out that the only problem was that I was including the plugin in the wrong place. I had grails.project.dependency.resolution = { . . . plugins { . . . compile ":spring-security-core:1.2.1" . . . } grails.plugin.location.astdomain ="C:\\src\\astool\\astdomain" } But it needs to be included outside grails.project.dependency.resolution = { . . }: grails.plugin.location.'astdomain' ="../astdomain" grails.project.dependency.resolution = { . . } Notice too that I now have quotes around 'astdomain'. I'm not sure if that matters or not, but that how I saw someone else do this. I'm also using the more general syntax: "../astdomin". But "C:..." does work too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to prevent (programmatically) a java application from starting if it's not in a pre-defined directory? how to prevent (programmatically) a java application from starting if it's not in a predefined directory? Example: I have application.jar and I want to make it runnable only if it's located in "C:\runnable" directory else the application will exit. any ideas? A: System.getProperty("user.dir").equals("C:\\runnable") A: final String classLocation = GetClassLocation.class.getName().replace('.', '/') + ".class"; -> http://www.roseindia.net/java/java-get-example/get-class-location.shtml A: Can also Try - System.out.println(new File (".").getCanonicalPath()); // Current Path System.out.println(System.getProperty("user.dir")); // Path from where java is executed A: If the actual criteria is whether the jar file is in a given location, you cannot rely on system properties, but must ask the JVM about the location of the jar file and then react accordingly. See Determine location of a java class loaded by Matlab for instructions about how to determine the location of the byte code for a given class. Then do it for a class you know to be in the jar, and go on from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to send message to a viewcontroller in another tab I use a UiTabBarController for my iPad app. One of the tabs is a UITableView with favorites. When I klick a cell I want the favorite to open in a viewController in another tab. I solved it the ugly way by assigning a variable in a singleton and then select the other tab by [self.tabBarController setSelectedIndex:2]; In ViewWillAppear on the target viewController I read the value from the singleton and then do all the action. There must be a proper way to do this. How do I reference an instance of a ViewController in another tab? Is there a way to load another viewController in a tab? Anyone? A: You can get all of the view controllers in a Tab view by using the viewControllers property. From the docs: The default value of this property is nil. When configuring a tab bar controller, you can use this property to specify the content for each tab of the tab bar interface. The order of the view controllers in the array corresponds to the display order in the tab bar. Thus, the controller at index 0 corresponds to the left-most tab, the controller at index 1 the next tab to the right, and so on. If there are more view controllers than can fit in the tab bar, view controllers at the end of the array are managed by the More navigation controller, which is itself not included in this array. A: Create a delegate protocol for your table view controller: @protocol MyTableViewControllerDelegate <NSObject> - (void) myTableViewController: (MyTableViewController *) myTableViewController didSelectSomeObject: (MyClass *) object @end and create a property for the delegate: @property (nonatomic, assign) IBOutlet id<MyTableViewControllerDelegate> delegate; Then make the second view controller be the delegate of your table view controller - either by hooking them up in interface builder, or in the app delegate if that knows about both of them. Then whenever a row in the table is selected, call the delegate method, which will inform the other view controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I check if the admin panel in django is enabled? I'm writing an app which has an effect on the admin panel if it is enabled. How can I check if it is enabled or not within a certain project? A: from django.conf import settings if "django.contrib.admin" in settings.INSTALLED_APPS: ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7619459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: saving password in device memory in android I am creating an application which connects to the server using username/password and I would like to enable the option "Save password" so the user wouldn't have to type the password each time the application starts. Can any one please tell me how to do this?? thanks. A: In such a case you would use SharedPreferences Cheers! A: How to save data, you can look here http://developer.android.com/guide/topics/data/data-storage.html But beware to save the password unencrypted. Save it encrypted and create a way you can check using the already encrypted password.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DLL not working Recently, I decided to get into DLL programming with C++. I made a simple DLL but when I inject it into a process, nothing happens. Here's the code: #include <windows.h> BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if(fdwReason == DLL_PROCESS_ATTACH){ MessageBoxA(0,"Injected","Injected",MB_OK); } return TRUE; // succesful } It's supposed to display a message box when it gets injected into a process, but it doesn't work. Any help would be appreciated I used a dll injector to inject it into a process. And my OS is windows 7. A: I advice you to read these books (from my bookstore), before you can proceed (to understand the basics) : * *Win32 System Programming. A Windows® 2000 Application Developer's Guide by Johnson M. Hart *Programming Applications for Microsoft Windows by Jeffrey Richter *Writing Secure Code for Windows Vista by Michael Howard, David LeBlanc, That is true, especially the part describing the ASR (adress space randomization), making it viirtually impossible to inject you DLL function into another process (and, rewriting some function call with your own function, either system function calls or public functions in a process) without raising an exception, except you are familiar with very advanced thechniques related with the Windows messaging and elevationg priveleges fot the call being called, bases on a known (or, not really) code flaws in a kernel functions from NT kernel (KERNEL32.dll and relevant libs).
{ "language": "en", "url": "https://stackoverflow.com/questions/7619468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generate JSON from java for jsTree I am creating a jstree with JSON data in struts 2. I want to generate JSON data into action and pass to the JSP means for creating the tree. But I cant understand how to pass JSON from Action class to JSP and create jstree. Please anybody provide me sample code for developing jstree from JSON in struts 2. A: Use the struts2-json-plugin. You can find numerous examples for using this plugin here on SO (I wrote a couple just search for them) and also here : http://struts.apache.org/2.2.3/docs/json-plugin.html Simply with the struts2-conventions-plugin and the struts2-json-plugin you would only need to place a struts2 action in a package that contains the word action. ie: /somePackageStructure/action/MyAction.java Now if you where to write http://myhost/my-action You would get a json result (assuming you set up your action with the correct annotation or correct struts.xml, which is all explained in the previous link, or a search here). How the json gets produced is quite simple. What ever you have getters for are seriallized into json. What ever getters are exposed by those objects are also serialized in turn, also maps and lists are serialized as you would expect for json. Note: "how to pass JSON from Action class to JSP" you probably meant to say: "How do I retrieve json from struts2 from a loaded page". Because what you'll need to do is create an action to load your page (with your jstree), this page on the client will then need to make calls to retrieve the data that it needs. If you have not worked with this plugin I would recommend entering the url into chrome, it will show a json result directly (If you're familiar with firebug that too is an excellent tool). Then create a page that displays something asynchronously when pressing a button. Then you'll be in a position to tackle this issue. For getting started with the client side in using json and jquery this link helped me greatly: http://api.jquery.com/jQuery.getJSON/ A: You can generate JSON using the classes found on http://json.org/java/. The pass the resulting String as a page scoped variable to the view and use it as you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Database periodic cleansing I'm creating a public messaging service and I was wondering, in order to perform a cleanse of the oldest messages, is it okay to delete the oldest message every time a new one is submitted? Or is this approach inefficient for some reason? If so, could you specify why? I considered create a Cron Job for this, but I'm not sure if it applies in this case. A: You can schedule an event in MySQL: DELIMITER $$ CREATE EVENT cleanup_messages ON SCHEDULE EVERY day ENABLE DO BEGIN DELETE FROM messages WHERE ......; END $$ DELIMITER ; http://dev.mysql.com/doc/refman/5.1/en/create-event.html A: That sounds unlikely to be appropriate. The appropriateness of removing an old message is unlikely to be dependent on the new message - for example, if you're meant to keep messages for at least a month, then you don't want to start deleting recent messages if you suddenly get a lot of messages in a short period. I suggest you work out your "garbage" criteria and then schedule a regular job to batch delete old messages (e.g. once a day). A: I suggest Cron Job, I believe there is time stamp with each message so you can remove older post with help of time stamp on cron run.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Type Casting In Groovy I have two questions. I did the following code to find the ASCII value of $ : def a = "\$" def b = (int)a println b //prints 36 Well I'm happy with the answer. But when I tried to do it in reverse like this, I found I'm missing something : def a = 36 String b = a println b // getting output only 36 Question 1: So my first question is why it prints 36 and why not $? Am I wrong here? Well if the same first code block is re-written as: def a = "\$" def b = a as int println b If I run this program I get an error like this : Caught: java.lang.NumberFormatException: For input string: "$" at T.run(T.groovy:2) Even though I'm trying to do the same as before. I'm getting an error. Question 2: So why does the as keyword doesn't work here and does def a = (int)b is not equal to to def a = b as int? Explain me. Thanks in advance. A: when you cast a string to int it's ok while you have one char in it, so we can say you cast a char to int, when you try to cast int to a string i think it uses toString method or something like that. Try to cast 36 to char and you'll see your '$'
{ "language": "en", "url": "https://stackoverflow.com/questions/7619475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: preg_replace() not finding ending delimiter? I use preg_replace() alot but I'm not a genius at it. If I start up a function and deliberately key in all the smilies that I want to use e.g. <?php function parse_emotes($body){ $body = preg_replace("#\:p#i", "<img src='images/emotes/tongue.png' alt=':p' title=':p' />", $body); //they continue like i said return $body; } ?> but today I tried to change it up and use mysql to let me just insert and delete them as I please without playing in my code, but when I tried it, it only throws Warning: preg_replace() [function.preg-replace]: No ending delimiter '#' found in PATH/TO/FILE.php on line 226 Here is the code I used the first time: <?php function parse_emotes($body){ while($row = $db->Query("SELECT * FROM emotes", 3)) { return $body = preg_replace($row['regex'], "<img src='images/emotes/" . $row['src'] . "' alt='" . $row['alt'] . "' title='" . $row['alt'] . "' />", $body); } } ?> That didn't work, and yes the regex row included the delimiters so it would output #\:p# I got the same error as stated before and then I tried to take the #s out of the data in MySQL and just changed preg_replace as follows preg_replace('#' . $row['regex'] . '#i', .......) and it still does not like it? I have also tried assigning: $regex = $row['regex']; preg_replace("#$regex#i"); Guess what? Still a no. Any help with where to go with this is very appreciated. A: Since people are still downvoting this topic. @salathe was correct in the questions comments (returning in the loop.. Ooops). but here is the answer: $emotes = $db->select(['regex', 'class'])->from("emotes")->execute(); while ($emote = $db->fassoc($emotes)) { $body = preg_replace("#{$emote['regex']}#i", "<i class='sprite-emote {$emote['class']}'></i>", $body); } /* ...other parsing... */ return $body; A: Change your code from preg_replace('#' . $row['regex'] . '#i', .......) to preg_replace('/' . $row['regex'] . '/i', .......)
{ "language": "en", "url": "https://stackoverflow.com/questions/7619476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is it possible to add jspf files to a jsp page without using jsp:include? What I want to achieve is something similar to a master page in asp.net. I'm following a tutorial, but I may have missed something cause I have added my header.jspf and footer.jspf to the WEB-INF/jspf folder and index.jsp is outside of WEB-INF. I have added info in web.xml so that certain jsp-pages should automatically add the header and footer. The problem might be that index.jsp can't access anything inside the WEB-INF folder, but I thought I had solved that in a previous step in the tutorial. When I run the project, all I get is what's left of index.jsp after I remove all the header and footer stuff. I don't want to use: <%@include file="header.jspf" %> and <..jsp:include...>. Screenshot: web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <session-config> <session-timeout> 30 </session-timeout> </session-config> <jsp-config> <jsp-property-group> <description>header and footer settings</description> <url-pattern>/index.jsp</url-pattern> <url-pattern>/WEB-INF/view/*</url-pattern> <include-prelude>/WEB-INF/jspf/header.jspf</include-prelude> <include-coda>/WEB-INF/jspf/footer.jspf</include-coda> </jsp-property-group> </jsp-config> </web-app> header.jspf: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Webshop</title> </head> <body> <h1>Webshop</h1> footer.jspf: </body> </html> A: I'm also doing that tutorial, and when I use Tomcat as the server it won't include the header and the footer, I have to use the glassfish server, is there any way to make tomcat include the header and the footer? EDIT: Replacing the default tag with this one seems to have solved the problem using tomcat as the server <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/TR/xmlschema-1/" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
{ "language": "en", "url": "https://stackoverflow.com/questions/7619480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Core Data - Get objectIDs of to-many relationship without firing a fault I have an entity with a to-many relationship. After I fetch a subset of objects from my entity, I would like to get the ManagedObjectIDs of the relationship objects - without firing a fault. Is this possible? My understanding from the documentation is that calling objectID on a fault does not cause it to fire, but when I try the following line, a fault is fired for each object's relationship nonetheless: [word.articles valueForKeyPath:@"objectID"]; I have also tried the following, with the same result: [word valueForKeyPath:@"articles.objectID"]; I have now also tried the following, but unfortunately article faults still fire: for (Article *article in word.articles) { [articleIDs addObject:article.objectID]; } Any help would be greatly appreciated please! A: This was made possible in iOS 8.3 /* returns an array of objectIDs for the contents of a relationship. to-one relationships will return an NSArray with a single NSManagedObjectID. Optional relationships may return an empty NSArray. The objectIDs will be returned in an NSArray regardless of the type of the relationship. */ - (NSArray<NSManagedObjectID *> *)objectIDsForRelationshipNamed:(NSString *)key NS_AVAILABLE(10_11,8_3); It does one trip to the store to get all the IDs. A: What you need to do is create an NSFetchRequest for the Articles entity using a predicate like this (where 'word' is a word managed object): NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY words == %@)", word]; Set resultType = NSManagedObjectIDResultType as Ashley says in his answer. The fetch request will then return a collection of Article ObjectIDs for articles containing the specified word. OR: If you want to look up by the text of the word rather than fetching it as a managed object first then use a predicate like this. (where 'wordText' is an NSString and assuming - 'text' is a field of the Word entity) NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(ANY words.text == %@)", wordText]; A: I think you might have to use an NSFetchRequest, for entity Articles, and setting request.resultType = NSManagedObjectIDResultType If the problem is multiple faults firing (so multiple SQL requests), how about a fetch request to fetch all your required Articles initially, meaning only a single SQL request is made? A: One possibility would be to perform prefetching so that your relationship objects are fetched during your initial fetch and therefore will not cause faults later. Look into the relationshipKeyPathsForPrefetching property in the NSFetchRequest class. Here is an example where the request is returning an array of Word objects that contain an articles property: [request setRelationshipKeyPathsForPrefetching:@[@"articles"]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7619485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Multiplying real matrix with a complex vector using BLAS How can I use Blas to multiply a real matrix with a complex vector ? When I use functions like ccsrgemv() I get type mismatch errors? error: argument of type "float *" is incompatible with parameter of type "std::complex<float> *" A: Use two matrix-vector multiplications (A * (x + iy) = A * x + i A * y). More precisely, consider your complex vector as two entangled real vectors with stride 2. BLAS lets you do this. UPDATE: actually, I did not notice that you were doing Sparse BLAS. For dgemv my trick works, but for csrgemv it doesn't. I'm afraid you have to maintain real and imaginary part separately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to remove all entries in a list that are above some given value? Newbie question: Suppose that in R I have a list with 10'000 entries (numbers). myList <- read.table ("my10000Vaulues") Now I would like to remove all entries that are above some value (say 523.689). The resulting list should not have any white space in it. Thanks for all hints A: I'm guessing that your problem is that 'myList' really is a list -- a special type of list called a data frame -- and you want a numeric vector to work with. One approach might be something like: myNums <- myList[,1] mySmallNUms <- myNums[myNums <= 523.689] A: You can do the following: myListFiltered <- myList[myList <= 523.689] Also have a look at: How can I remove an element from a list?
{ "language": "en", "url": "https://stackoverflow.com/questions/7619498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getting distinct column name and count when based on another table i have the following query: select cc.category from companies c left join categories cc on c.category_id = cc.category_id where company_title like '%gge%'; which return categories with duplicate rows. what i need is to get distinct categories, with the total count of accurences of that category, something like: CATEGORY NAME | XXX ( where XXX is the count ) anyone can help? A: Use this query instead :- select distinct cc.category, count(cc.category) as totalCategoryCount from companies c left join categories cc on c.category_id = cc.category_id where company_title like '%gge%' group by cc.category
{ "language": "en", "url": "https://stackoverflow.com/questions/7619499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I resolve "an enclosing instance that contains X.Y is required"? I am developing a small desktop application in Netbeans. This is my first program and I am facing a very strange type of error. I know I did some thing wrong but unable to trace what I am doing wrong :( Please help me in resolving this error. Description: I have a default package Src and I am creating new Java classes in this package as required. Along with other classes I made a class X like this: public class X { public class Y {//some member functions and variables exist here} public class Z {//some member functions and variables exist here} //some member functions and variables exist here } Now I need to create instance of one of the inner classes in some other class that exists in the same package, like this: public X.Y oY = new X.Y(); but I am getting the following error: an enclosing instance that contains X.Y is required Please help me in resolving this error. A: First of all you have to create an object of X class (outer class) and then use objX.new InnerClass() syntax to create an object of Y class. Try, X x=new X(); X.Y y=x.new Y(); A: You want to declare static inner classes: public static class Y. A: Declare Y as static to avoid creating instance of X. public class X { public static class Y { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7619505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: Precision issue with the Silverlight Slider and it's thumb I have a precision problem with the slider control in Silverlight: I've built some custeom template to slightly modify the visual appreance of the standard Silverlight slider control. My goal is to have a slider that represents it's values as drawn ticks on it's scale. The corresponding thumb is also slightly modified in the form, that it has a 'tip' (or 'peak') at it's very center to point at the current value at the slider. --> Here's a snapshot it: http://www.willzeit.at/sliderThumb.jpg Actually everything works, but I've encountered a very strange behavior of the thumb: The position on the thumb that points to the current value at the slider seems to change from the left-most position on the thumb to the right-most position on the thumb! So in the case the thumb is located at it's left-most position with respect to the slider the point on the thumb pointing to the slider-value is the left_most position on the thumb. Of course the same holds if the thumb is at it's right-most position where the value-indicating position on the thumb is at it's right most position. Of course that makes sense because the thumb won't be able to go beyond the boundaries of it's slider and therefor the 'value-indication' point on the thumb has to range over the whole width of the thumb (in case of an horizontal slider as in my case). BUT: That's a significant loss of precision in the 'syncronization' between thumb and slider (of course only when you want to indicate the exact value of the slider with the thumb. As i said, i need to build a slider that presents values (shown with ticks and labels) and a thumb with a needle. When the user wants to set a particular value with the slider control, he has to move the thumb in the way that it's 'needle' comes to rest beneath this particular value. I hope i could make this issue clear and also my problem :) Does anybody have any ideas ? I guess there must be a way to solve this problem - otherwise the slider control is not intended to be used in such a way - what sounds highly unlikely for me ... I really would appreciate any help :) marc A: Theoretically all you need is to make the Silder control think that its thumb is only 1 pixel wide. You can do this by modifying the Thumb template so that the top element in the template is a Canvas (a Grid clips its contents) and then contain the rest of the content in a Grid that you give a specific size to and then offset its left edge. Use an odd number for the width and set its left position = -1 * (Width -1) / 2. You can do this with margin, canvas left or a render transform. Now I say "Theoretically" because in practice I've come across an anomoly that I just can't explain. No matter how hard I try only the Left hand side of the thumb is active. Silverlight just does not seem to want to recognise the right hand side of the thumb. Ultimately I decided to put this answer out because clearly you are already editing the templates for control and perhaps if you apply it to your own work you won't get this anomoly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: batch rename the files in a folder I have some files (about 10000 files) in bellow format SDEF-2001-23965-236.pdf SlkF-1991-65-123.pdf I want to check if the file name is in wanted format rename it by removing 4 characters from end SDEF-2001-23965-236.pdf >>SDEF-2001-23965.pdf SlkF-1991-65-123.pdf >>SlkF-1991-65.pdf I do not know how should I create a .bat file that can do what I need. A: You need "String Manipulation" in DOS, the following link is useful: http://www.dostips.com/DtTipsStringManipulation.php If you have *.pdf files with format aaaa-bbb-cc-ddd.ext (4 parts + extension) Create a file named rn.bat: @echo off set str=%1 for /f "tokens=1,2,3,4 delims=- " %%a in ("%str%") do set p1=%%a&set p2=%%b&set p3=%%c&set p4=%%d set ext=%str:~-4% set "result=%p1%-%p2%-%p3%%ext%" ren %1 %result% Create a file named rnall.bat: @echo off for %%i in (%1) do rml.bat %%i Then, enter command: rnall *.pdf in commmand line. This is not best code, you can use functions to do it better
{ "language": "en", "url": "https://stackoverflow.com/questions/7619513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make model "hasMany" and "belongsTo"? (Same like cakePHP) I am currently working on my mvc framework (in PHP). I saw that cakePHP has ability to use "belongsTo" and "hasMany" features. I am trying to create my own feature and I hit a problem. Lets say that we have appointment table (id, where, date, year_id) and year table (id, year). I know this example could be done with one table without a problem, but it's just an example. class appointment_model extends model{ public $_belongs_to= array('table'=>'year','field_connector'=>'year_id'); public $one_value; } ...... class year_model extends model{ public $_has_many= array('table'=>'appointment','field_connector'=>'year_id'); public $many_values; } .... class model{ private function select($query=null){ if(!$query)die("Query cannot be null. Line num: " . __LINE__); $results = $this->_db->mysql_select($query); if(count($results)==1){ $one = $this->initialize($results[0]); $this->_do_for_other_tables($one); return $one; }elseif(count($results)>1){ $returns = array(); foreach($results as $result){ $one = $this->initialize($result); $returns[] = $this->_do_for_other_tables($one); } return $returns; }else{ return null; } } private function _do_for_other_tables(&$one, $rec=1){ if(property_exists($this, 'many_values')){ if(!empty($one->many_values))return; $many = functions::load_model($this->_has_many["table"]); $res = $many->find_by($this->_has_many["field_connector"], $one->id); $one->many_values = $res; } elseif(property_exists($this, 'one_value')){ if(!empty($one->_belongs_to))return; $only_one = functions::load_model($this->_belongs_to["table"]); $field = $this->_belongs_to['field_connector']; $res = $only_one->find_by('id', $one->$field); $one->one_value = $res; } } } Basically what happens here is that I enter into infinite loop. Any suggestion how can I fix that? If I need to explain it more, just say it. Thanks :). A: You problem is you treat the properties "hasMany", "belongsTo", "hasOne", "etc" as simple properties instead of treating them as 2way relationships. What i've done in many of my own frameworks is to initialize these properties by hand by the programmer but when the class initializes, you check these properties and generate a single object that links the two together. Create a class like a System_DB_Relationship object and you place the same copy in the two initialized models. If you don't instanciate your models as Factory design pattern, you can use the static $relationship model to store your relationships too. I tend to go for Factory/Active record so it's better to manage these. Now depending on the logic of your model base class, you may want to place a flag in the relationship to say, "hey, this relationship has been used" so you don't pass into it again. Another way is to always work in a descending fashion. That is, disregard the hasMany when it is found and create only a proxy method to load the child elements but load all the belongsTo so that the parent is loaded by default. Note though that this methods can become dangerous if you have a large set of classes, so what i implement in my frameworks is usually a loading parameters that says, load X levels of relationships. And when you want the hasMany, you just use the __call() to intercept a call to "$myobject->subobjects()" and just load them on the fly. There are tons of ways to do it, just take your time to trace your code by hand, look at what doesn't make sense, try out stuff and you'll get to something eventually. But as Francesco said above, it's rarely useful to reinvent the wheel unless you work on really old projects that can't be transformed at once. Take this work you are doing as an opportunity to get better and know how it works under the hood...
{ "language": "en", "url": "https://stackoverflow.com/questions/7619515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How is physical inch related to pixels in css given so many different resolutions? Following code sets the height of two div elements - one in inch and one in pixel. <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>CSS 2</title> <style type="text/css"> .div1{ border:solid 1px red; height:1in } .div2{ border:solid 1px green; height:96px } </style> </head> <body> <div class="div1">This is the content in div 1</div> <div style="clear:both">&nbsp;</div> <div class="div2">This is the content in div 2</div> </body> </html> Now, even on changing the resolution of the screen the height of both the divs always remains same. What I was expecting is that the first div (having height specified in inch) would remain same where as the height of second div (specified in pixels) would change. Due to this behaviour, there are following things which are being unclear: a. When we specify height of an element in 'in' then is it equal to the physical inch? If yes, then when the resolution of the screen is changed, why the height of such an element changes? If not, then what way can we relate the size of an element with the physical world dimensions? b. How are pixel and inch related to each other. Could anyone please guide at this or point to some useful link? Thanks in advance. A: The inch in css is a logical inch and not physical since most browsers cannot determine the physical size of the screen. By default this is set to 96dpi , hence 96px for each inch. Refer here My recommendation would be not to rely on inch/cm units but rather em based layout and use javascript for dynamic resizing as shown here : Dynamically Resizing Text with CSS and Javascript
{ "language": "en", "url": "https://stackoverflow.com/questions/7619524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Options for a file system based Sql database for a multiuser web application that can perform and scale What are my options for a file based sql database (not NoSql) which scales well, performs well, and is designed for handling many hundreds of multiple users (and plays nice with .net)? My requirements I'm accustomed to working with SqlServer, and for this application my needs are simpler (I still need sql though, although other parts of the application will use NoSql). I want something which is embedded mainly because it's just simple and easy to set up, without any major overheads or services or configurations. I'd like to keep it filesystem for as long as I can. However, when the time comes, ideally I'd like a solution which allows me to change the "context"of the database so maybe it is server based. I'd like that option to grow. I'd also like it to be free (at least for small application, or non-commercial applications (although it will become commercial in the future...?)). Does such a database solution exist? Update Sorry guys, I used the wrong terminology and ugh ink we misunderstood each other. Forget I said embedded, I meant file base, like lucene or raven, but relational. A: You ever heard of SQL Server? Like SQL Server EMBEDDED? No install ;) A: You have contradictory requirements. Small and embedded (no server) usually means SQL Server compact or SQLLite. But these are neither multi-user not network aware in practice. Especially whan you say "hundreds of multiple users" So you have to decide what you want to do. A proper, scalable, web based app with correct architecture? Or a a cheap kludgely unworkable unmaintainable mess? SQL Server Compact will scale up of course in future to normal SQL Server with minimum fuss. But I'd start with SQL Server properly now A: You can use FireBird, it can be embedded and scales well and deployment is really easy - an ADO.NET provider is available... see for more information http://www.firebirdsql.org/en/net-provider/
{ "language": "en", "url": "https://stackoverflow.com/questions/7619525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determine which region of the window is clicked This is really sort of a general programming question. I have a window split into 9 even squares. When the user clicks one of those squares, I'd like to know which one. I can get the location of the click via x and y variables. My current approach is xRegion = screenWidth / x and yRegion = screenHeight / y which will give me, for instance, (1,1) for the point (320,240) in a 640x480 window. But that only works for x and y values greater than one third or so of the screen. I know this is probably really simple, but I can't seem to wrap my brain around it. A: xRegion = (x*3) / screenWidth; yRegion = (y*3) / screenHeight; +-----+-----+-----+ | 0,0 | 1,0 | 2,0 | +-----+-----+-----+ | 0,1 | 1,1 | 2,1 | +-----+-----+-----+ | 0,2 | 1,2 | 2,2 | +-----+-----+-----+ If you are ausing a language like js or php, you must floor/trunc the result to get an integer. Add 1 to the results if you want the first region to be (1,1) For results 1 to 9 do this: cell = yRegion*3 + xRegion + 1; 1 2 3 4 5 6 7 8 9
{ "language": "en", "url": "https://stackoverflow.com/questions/7619528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Wikipedia's Random page actual url Possible Duplicate: How to get the URL of a redirect with Python How can I get actual url of this http://en.wikipedia.org/wiki/Special:Random after it redirects on random page(in Python).
{ "language": "en", "url": "https://stackoverflow.com/questions/7619529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight DataGrid to work like Excel In using the Silverlight DataGrid and I wanted it to work like Excel, I assume the best way if I was not using a DomainDataSource was to and was just binding the itemsource to an observablecollection, what would be the best way to add a new row...Should I just temporarily add an item to the observablecollection? Would there be a way to move to that row and place it in edit mode? Thanks A: Datagrid does not support movable rows, so you'll have to implement it by yourself. Have a look on the following project: http://www.codeproject.com/KB/silverlight/DataGridWithMovableRow.aspx You can either use it as is, or use its logic to build something that best suites you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: set + nth element : fast implementation For the following data structure: * *add an element in O(lg(n)) *remove an element in O(lg(n)) *find the k'th element in O(lg(n)) we can use a balanced BST which each node has size of it's subtree, but it needs to implement red-black tree which is not fast to code. any better solution? A: The general type of structure you are looking for is qualified with Indexed or Indexable, that is a structure augmented with count to be able to access elements by indexes. You could use either: * *an Indexed Tree: Binary Search Tree (Red-Black Tree, AVL Tree), B-Tree, Finger-Tree, ... *an Indexed Skip-List (and perhaps a few others :p) I tend to think that Skip-Lists are easier to implement than BST, as you can use a randomized height instead of all the balancing stuff. A: The usual way is to implement your own augmented O(log(n)) data structure that allows rank based inserts/lookups. A balanced BST, skip list, or some modified segment tree or Binary Indexed Tree should work. In Java you can also use TreeList from Apache Commons. If k is fixed and you are using C++, you can use a clever trick you can find at TopCoder (Scroll down to the section titled "Floating Median"). Bascially you use 2 std::multisets, one for the first k elements and another for the last N-k elements. Every time you add/remove something, you update the multisets accordingly. Getting the kth element is simply looking up the last element in the first multiset. A: It appears that AA Trees are easier to implement than RBTs but otherwise are pretty much equivalent to them. A: You could give a shot to skip lists with a randomized node height. It should be able to do what you want. It's a randomized data structure. As an idea is very clean and it's relatively easy to implement. Red-black tries have many special cases. Skip lists have no special cases and are easy to get right. In addition they behave very well in practice - the constant in O() is rather small.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flexible progress bar I have a long pending question about the progress bar in Ajax which I need to clarify. The question is that when we do any action in Facebook and the site is waiting for a response from the server the progress bar appears on different parts of the page.. Facebook couldn't have installed 100's of these progress bars (this what I think). There must be an object created and every time there is a request sent to the server, this object is called. What is the solution, using JavaScript or Ajax or whatnot? A: Start by reading the documentation for jQuery's $.ajax, and especially the global Ajax events. All you really have to do is create a progress bar (can be done easily with jQuery UI) and bind it to the global Ajax events to make it work whenever an Ajax call is being made. With the built in progressbar in jQuery UI you can update the progressbar with the actual percent completed in the Ajax call. The rest is just css placement of the progressbar itself on the page. A: Have you seen the source code for Facebook? They probably have a function in each ajax call that goes over every loading bar placeholder and makes it show the loading bar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Order by one column if the other is empty for each field I have two tables: a Topics tables and a joined Comments tables, both with timestamp columns. I would like to order the topics list so that topics with the most recent comment are at the top. However, if a topic has no comments, I want it to be sorted by the date it was created. In other words I'm trying to order it so that the topics are sorted by the date they were created only if they have no comments – basically like any forum. For example if topic A (empty) was created after topic B (not empty) but topic B has a reply that was most recent the order should be B, A. I don't want all the empty topics at the top if they're old or at the bottom if they're new. I tried the IF ISNULL statement but it applies to the entire column and not each individual row so I end up with the empty threads either stuck at the top or bottom of the feed. I'm guessing I'd have to construct a virtual column with only the most recent comment from each topic...? Here's the full statement: SELECT $showbody, Topics.Title, Topics.id AS tID, Topics.Timestamp, Topics.MemberID, Users.id, Users.FirstName, Users.LastName, GROUP_CONCAT(DISTINCT Tags.Keywords SEPARATOR ', ') AS Tags, COUNT(Comments.id) AS NumberOfComments, ( SELECT COUNT(Comments.id) FROM Comments LEFT JOIN Views ON Comments.TopicID = Views.TopicID WHERE Comments.Timestamp > Views.Visited ) AS NewComments FROM Topics LEFT JOIN Users ON Topics.MemberID = Users.ID LEFT JOIN Comments ON Topics.id = Comments.TopicID LEFT JOIN Tags ON Topics.id = Tags.TopicID WHERE Topics.id NOT IN ( SELECT Tags.TopicID FROM Tags WHERE Keywords IN ( SELECT Tag FROM Filters WHERE MemberID = '$_SESSION[SESS_MEMBER_ID]' ) GROUP BY Tags.TopicID ) GROUP BY Topics.id ORDER BY Comments.Timestamp, Topics.Timestamp DESC LIMIT $plim Any help would be greatly appreciated A: Use a left join for the comments, group on the topics, use max to get the time of the last comment, and use coalesce (or isnull) to sort on the comment date if it's there and the creation date otherwise. Example: select t.Title, t.CreatedDate, max(c.CreatedDate) as LastComment from Topics t left join Comment c on c.TopicId = t.TopicId group by t.Title, t.CreatedDate order by coalesce(max(c.CreatedDate), t.CreatedDate) desc A: Solution 1 (demo): -- Test initialization CREATE TABLE Question ( QuestionID INT AUTO_INCREMENT PRIMARY KEY ,Content NVARCHAR(100) NOT NULL ,CreateDate DATETIME NOT NULL -- DEFAULT NOW() ); CREATE TABLE QuestionComment ( QuestionCommentID INT AUTO_INCREMENT PRIMARY KEY ,QuestionID INT NOT NULL REFERENCES Question(QuestionID) ,Content NVARCHAR(100) NOT NULL ,CreateDate DATETIME NOT NULL -- DEFAULT NOW() ); INSERT Question(Content, CreateDate) SELECT 'Question 1','2011-01-01 01:00:00' UNION ALL SELECT 'Question 2','2011-01-01 02:00:00' UNION ALL SELECT 'Question 3','2011-01-01 03:00:00'; INSERT QuestionComment(QuestionID, Content, CreateDate) SELECT 1,'Comment 1.1','2011-01-01 01:30:00' UNION ALL SELECT 2,'Comment 2.1','2011-01-01 02:30:00' UNION ALL SELECT 1,'Comment 1.2','2011-01-01 02:40:00' UNION ALL SELECT 2,'Comment 2.2','2011-01-01 02:30:00' UNION ALL SELECT 1,'Comment 1.3','2011-01-01 03:30:00'; -- End of Test initialization -- Solution SELECT * FROM Question q LEFT JOIN ( SELECT qc.QuestionID, MAX(qc.CreateDate) LastCreateDate FROM QuestionComment qc GROUP BY qc.QuestionID ) qc ON q.QuestionID=qc.QuestionID ORDER BY IFNULL(qc.LastCreateDate, q.CreateDate) ASC; -- End of Solution -- By, by DROP TABLE QuestionComment; DROP TABLE Question; Results: 2 Question 2 2011-01-01 02:00:00 2 2011-01-01 02:30:00 3 Question 3 2011-01-01 03:00:00 1 Question 1 2011-01-01 01:00:00 1 2011-01-01 03:30:00 Solution 2: SELECT * FROM Topics t LEFT JOIN ( SELECT c.TopicID, MAX(Timestamp) LastTimestamp FROM Comments c GROUP BY c.TopicID ) c ON t.id = c.TopicID ORDER BY IFNULL(c.LastTimestamp, t.Timestamp) ASC
{ "language": "en", "url": "https://stackoverflow.com/questions/7619544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Not able to retrive and update data in same struts action class I am new to struts and currently working on a project. In one page I want to populate some data from database and there is a submit button is available in my from which will submit the data. My struts action class is: public class BookreturnAction extends org.apache.struts.actions.DispatchAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { BookreturnForm bookreturnForm = (BookreturnForm) form; System.out.println("in the from" + bookreturnForm.toString()); HttpSession session = request.getSession(true); List bookreturncollectionlist = new ArrayList(); List<StudentSessionObjectStore> list = new ArrayList<StudentSessionObjectStore>(); int studentid = 0; if (session.getAttribute("getsessionObject") != null) { list = (ArrayList) session.getAttribute("getsessionObject"); for (StudentSessionObjectStore store : list) { studentid = store.getId(); System.out.println("the student id" + studentid); } bookreturncollectionlist = BookreturnDAO.getBookReturn(studentid);//use to papulate data request.setAttribute("collectionreturn", bookreturncollectionlist); } return mapping.findForward(Constants.ACTION_FORWARD_SUCCESS); } public ActionForward inserted(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { BookreturnForm bookreturnForm = (BookreturnForm) form; boolean isInserted = BookreturnDAO.bookReturn(bookreturnForm);//use to insert data if (isInserted) { request.setAttribute("msg", "Your Request Succesfully Submitted"); } else { request.setAttribute("msg", "Try again"); } return mapping.findForward(Constants.ACTION_FORWARD_SUCCESS); } } Struts configution: <action name="BookreturnForm" parameter="inserted" path="/bookreturn" scope="request" validate="false" type="com.rec.bookbank.action.BookreturnAction"> <forward name="success" path="/jsp/Student/bookReturn.jsp"/> </action> the link of my jsp page is <html:link page="/bookreturn.do?parameter=inserted"> Books Return</html:link> A: When asking questions, please describe what actually happens, and what steps are being taken to get to the bits that don't work. Is there an exception? Is the incorrect method being called? Is no method being called? Is there no data in the form? And so on. It looks like you're clicking the link and expecting something to happen other than going to a new page. All you're showing is clicking a link--not submitting a form. Anything touching the action form isn't going to do what you think it is. In order to get form data, you must submit a form. On the code itself What is the loop over StudentSessionObjectStore doing? If there's only one item in the list then it's fine, but misleading: if there's a single student, keep it in session as a single student, not a list. If there is more than one, then you'll always be returning the book returns for the last student (?) in the list. That's not necessarily wrong, but it seems like it should be wrong. Consider using method and variable names to describe functionality, rather than comments. For example: boolean isInserted = BookreturnDAO.bookReturn(bookreturnForm); // use to insert data This contains a couple of suspicious names, indicated by the necessity of the comment. Instead do this: boolean wasReturned = BookReturnDao.returnBook(bookReturnForm); Methods should generally be named as a verb indicating what the method does on a conceptual level. The action doesn't need to know implementation details; it doesn't matter if the book return process is handled with an insert, and it might change (setting a flag, deleting a record, etc.) Individual system components should know as little as possible about implementation details. Similarly, don't pass Struts-specific classes, like an ActionForm, to the data layer. This ties the underlying code to the Struts framework, and makes testing more complicated without a good reason. Use something domain-specific, not framework-specific, instead, such as a book ID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Katta vs Lucene + Infinispan Lucene can work with disturbed infinispan cache. I'm wondering what is the moment to move from lucene + infinispan to Katta based on hadoop? When I'll be more effective to use Katta and when Lucene+infinispan? I've read that hadoop is not suitable for real-time systems, but what with Katta? A: What are your requirements? I would estimate that 99% of people on SO who ask for ultra-scalable Lucene find that Solr (or even out of the box Lucene) more than meets their needs. If you are one of the rare people having thousands of queries per second over petabytes of data, LinkedIn uses a Lucene+Hadoop based solution (zoie) for their realtime searches. I'm not sure where you read that Hadoop "isn't suitable for real-time systems" - no doubt there are certain systems in which its framework isn't ideal, but there are tons of real-time apps running on Hadoop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XMPP Logout (Smack API) without disconnecting with the server I am using smack API to connect to Openfire server. Am able to create user, login and exchange message. After logout I want my activity to be finished( user has to come to home screen) without disconnecting with the server. Any one have used Smack API for this kind of scenario? A: If you are using smack on Android then you should consider running the connectivity part of your application as a service which can be flexible and run in the background. You will be disconnected from the server if your activity goes to the onStop() or onDestroy() state. Logging out can be done by YourConnection.disconnect. If you don't want to disconnect from the server you will have to change your presence instead. A: I not found any solutions in the Smack documentation. If you make connect(), after disconnect() you will be authinticated again, and login throw AlreadyAuthanticated exception. But, after disconnect, you can destroy XMPPConnection obect and create new one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django custom order_by I've got a model eg. Car with a foreign key eg. Owner, which may or may not be blank. The Car has a creation_date. I would like to order these cars by date, but if the car has an owner, the date of birth of the owner must be taken instead of the creation_date of the car. Is this possible? A: This is possible by falling back to SQL: Car.objects.filter(...).extra(select={'odate': ''' if(owner_id, (select date_of_birth from owner_table where id=owner_id), creation_date ) '''}).order_by('odate') if function is MySQL-specific. In case of SQLite or Postgres you should use case statement. A: Have a look at this similar question: Good ways to sort a queryset? - Django You can't use the model's Meta ordering as it only accepts one field https://docs.djangoproject.com/en/dev/ref/models/options/#ordering You can't use the query order_by('creation_date', 'birthdate') as it only sorts by birthdate if they have the same creation_date So, you could write a custom manager to do incorporate a custom sort for you. import operator class CarManager(models.Manager): def get_query_set(self): auths = super(CarManager, self).get_query_set().all().order_by('-creation') ordered = sorted(auths, key=operator.attrgetter('birthday')) return ordered class Car(models.Model): sorted = CarManager() so now you can query: Car.sorted.all() to get all a queryset of sorted car's A: You could write a method that returns the appropriate date (if car has owner return birthday else return creation_date) and then order your model based on this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: error: 'IOCTL_STORAGE_QUERY_PROPERTY' was not declared in this scop I've included winioctl.h and there is no #define for IOCTL_STORAGE_QUERY_PROPERTY in that file !! http://www.osronline.com/ddkx/storage/k307_8z3m.htm Says Its in ntddstor.h But I cannot find any ntddstor.h on my Windows XP. HoweverIOCTL_STORAGE_QUERY_PROPERTY mentions its supposed to work with Windows XP (I dont need > Vista Specifc Queries) and It mentions to include winioctl.h only ! (I am not using Visual C++, I an using Qt with MinGW) A: I see IOCTL_STORAGE_QUERY_PROPERTY definition in WinIoCtl.h, and it compiles without any #ifdef conditions. What is your version of this file, how is it installed? I use WinIoCtl.h from VC++ 2010. Maybe you need to install Windows SDK. Possibly your WinIoCtl.h comes from old Visual Studio or SDK. Install newest Visual Studio version, if this is impossible - install latest Microsoft Windows SDK and ensure that its include directory is listed first in your compiler. A: I have used MinGW to compile these kind of programs. It may not be so easy to find, because frankly, the MinGW site is quite a mess, but they provide a lot of DDK header with no pain. Then I simply copy/paste the structs and defines I need and that I cannot find in the SDK headers. The macros, I define them conditionally, to avoid conflicts, just in case. For example, your IOCTL_STORAGE_QUERY_PROPERTY is in mingw/include/ddk/ntddstor.h #define IOCTL_STORAGE_QUERY_PROPERTY \ CTL_CODE(IOCTL_STORAGE_BASE, 0x0500, METHOD_BUFFERED, FILE_ANY_ACCESS) So I add in my projects: #ifndef IOCTL_STORAGE_QUERY_PROPERTY #define IOCTL_STORAGE_QUERY_PROPERTY \ CTL_CODE(IOCTL_STORAGE_BASE, 0x0500, METHOD_BUFFERED, FILE_ANY_ACCESS) #endif That's particularly useful if you intend to publish your code, as most people don't have the DDK headers, and they insist on using VisualStudio instead of MinGW.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Intercept an ABase class while a Child class implementing the base class namely A and an independent interface namely IC is used in binding Intercept an ABase class while a Child class implementing the base class namely A and an independent interface namely IC is used in binding. Bind<IC>().To<A>(); Problem rises when I have a property in A which will be set to null in proxified object, while in the Instance of the proxified object has the right value for that prop in debug view . ((Ninject.Extensions.Interception.Wrapper.StandardWrapper) (((DistributorServiceProxy)(distributorService)).__interceptor)).Instance To be exact I add the link to a gist https://gist.github.com/424637484504b89789d6 containing the actual code. I will be very grateful if anyone can help me. Cheers, Jani A: It Just need the Repository property to be public, that's it;
{ "language": "en", "url": "https://stackoverflow.com/questions/7619564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: linux system(3) call fails - how to know the errno-like error code? When I call the system(char* Command) with some command and it fails, I should like to know the error code (and not to parse text output). For example, I run system("rm file") and 'file' does not exist - how can I receive ENOENT into my application? A: You can only do this is the command explicitly returns that status. rc = system(...); if (rc != -1 && WIFEXITED(rc)) printf("Terminated with status %d\n", WEXITSTATUS(rc)); The value returned is -1 on error (e.g. fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). But if the command simply returns 1 when something goes wrong it's hard for the caller to tell the actual reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing string for no content I want to send a message to a ruby string object that tests for no_content: "".content? => false # same as .empty? " ".content? => false # same as .blank? "\n\t".content? => false # new feature Specifically, content? would pass true if there is anything a person could read there. I am going to monkey patch the String class to do this with a regular expression. "\n\t\n\n".gsub(/[\n|\t]/,'').empty? This gets me close, but I might be re-inventing the wheel and would like a more complete solution. A: Check out present? in ActiveSupport. A: strip it before checking. "\n\t".strip.empty? A: Something like this? class String def content? self !~ /\A\s*\z/ end end "".content? #=> false " ".content? #=> false "\n\t".content? #=> false "foo".content? #=> true
{ "language": "en", "url": "https://stackoverflow.com/questions/7619574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: cakephp 1.3: find conditions Array ( [0] => Array ( [DebateComment] => Array ( [id] => 126 [user_id] => 17 [debate_id] => 32 [debate_comment_title] => hiiiiiii [debate_comments] => gfdfg dfg . [debate_type] => against [total_postive_counts] => 1 [total_negative_counts] => 0 [accept_challenges] => Enable [status] => Active [modified] => 2011-08-19 11:12:59 [created] => 2011-08-18 17:50:53 ) [User] => Array ( [id] => 17 [group_id] => 3 [fb_user_id] => 0 [username] => xyz [email] => [email protected] [password] => 077dadf3cc9c5fcb95dfacc3d8ff5049123b2d89 [status] => 1 [verify_code] => [signup_ip] => [is_verified] => 1 [user_comment_warn_status] => 0 [user_ip_address] => [referred_by_user_id] => 0 [twitter_user_id] => 0 [twitter_access_key] => [twitter_access_token] => [modified] => 2011-05-05 10:43:15 [Userdetail] => Array ( [id] => 14 [user_id] => 17 [firstname] => xyz [lastname] => [about_me] => [tagline] => [visible_status] => Online [show_welcome_message] => Yes [created] => 2011-05-05 10:43:15 [modified] => 2011-05-05 10:43:15 ) ) ) Above array describe relation with eachother. I write this query but dosent get output. $arr = $this->DebateComment->find('all',array( 'conditions'=>array('User.Userdetail.visible_status'=>'Online'), 'recursive'=>3)); My Question : I want to find all DebateComment .but conditions is that visibale_status => online in Userdetails. A: $users = $this->DebateComment->User->Userdetail->find('list',array( 'fields'=>array('user_id'), 'conditions'=>array('Userdetail.visible_status'=>'Online') )); $arr = $this->DebateComment->find('all',array( 'conditions'=>array('DebateComment.user_id'=>$users) )); You can use either containable or recursive to get the related data in the second query. A: Sorry if it is the comment but i dont see any option to comment on your question in my interface.I assume this is a result of a JOIN have you implemented BELONGSTO association here or any one else?Have you tried mentioning the visibale_status ONLINE in the JOIN condition?Did it worked then?Also there is another way to get recursive data.try $this->DebateComment-recursive = 3 I am not sure of level of recursion here.Please check it. A: $arr = $this->DebateComment->find('all',array('joins' => array(array('table' => 'userdetails','alias' => 'Userdetail','type' => 'INNER','foreignKey' => false,'conditions' => array('DebateComment.user_id = Userdetail.user_id','Userdetail.visible_status'=>'Online'))), 'recursive'=> 2));
{ "language": "en", "url": "https://stackoverflow.com/questions/7619579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to implement translation on a existing web project? I've rescued an old project that was originally writted only for spanish audience and now I have to internationalize it. This project has 3 kinds of text strings: * *Strings written from PHP: For example: echo "Hello world" *Short strings in database fields: database fields that contain text, for example, country names lists. *HTML embedded strings (static files): For example a static file containing an HTML file: <html>...<body>...<p>Hello world</p>... *HTML embedded strings (database): Same as above, but HTML file is inserted on a text field in the database. First is not a problem, because there are really few strings and very localized. The second case is also very localized so it's not really a big problem. But last 2 cases are unmanegeable: hundreds of HTML files (static + database) with hundreds of strings inside. So, I'm looking for an automatized method to extract all strings into a recognizable format, give it to translators and then have my pages in other languages. Does exist something similar or should I create a custom solution? In this case, any idea? A: Ok. The I18n (Internationalization) is a quite strange thing. You have to make many many changes to your code in order to make it multilingual. For me, the best solution is to move it on CakePHP that already support the I18n in many layers. But this solution will make you spend a lot of time. So .... A fast method for translating internal texts like echo "Hello World" or <p>Hello World</p> Is to create an appropriate language file with php extension for each language (ie: es.php, el.php, en.php, an so on) that will contain an array with keys and values that will looks like that : $l = array( 'WEB_TITLE' => 'My web site title', 'GEN_HELLO' => 'Hello World', 'MENU_HOME' => 'Home', 'MENU_PRODUCTS' => 'Products', ... ); Then into your web site you have to load the appropriate language file at the very beginning of each page and into your page you have to do something like that: echo $l['GEN_HELLO']; and <p><?php echo $l['GEN_HELLO']; ?></p> That is the front end side of your application. Now to make your data multilingual you have to change the database structure in some how. Lets say you have that table ARTICLES id Title Content Date Active In the above structure you have to make Title and Content I18n compatible. In order to translate that columns you have to create another table called in example ARTICLES_L that will looks like that ARTICLES_L ID POST_ID COLUMN LANGUAGE CONTENT In the above table you have to store the article id, the column that the translation belongs (ie: title) the language, and the translated content. So if you have that records in ARTICLES ARTICLES id Title Content Date Active 1 Title 1 This is content 1 2011-10-01 13:28:45 1 2 Title 2 This is content 2 2011-10-01 13:28:45 1 3 Title 3 This is content 3 2011-10-01 13:28:45 1 The table ARTICLES_L will contain that records ARTICLES_L ID POST_ID COLUMN LANGUAGE CONTENT 1 1 title es_ES Título 1 2 1 content es_ES Este es el contenido 1 3 1 title el_GR Τίτλος 1 4 1 content el_GR Αυτό είναι το περιεχόμενο 1 5 2 title es_ES Título 2 6 2 content es_ES Este es el contenido 1 .... In reality there are many many other tasks you have to do, but this is the idea behind the solution I am giving to you :) Good Luck PN : Even better for the front end of your application is to use that http://php.net/manual/en/book.gettext.php This way is the way that used from WordPress and CakePHP, but in very low level :? Just take a look. This will be better than creating files for each language.
{ "language": "en", "url": "https://stackoverflow.com/questions/7619582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }