text
stringlengths
8
267k
meta
dict
Q: Performing Wifi scanning at regular interval, using AsyncTask/Handler in android I wish to perform Wifi scanning at regular interval between 0-10sec as the time can be set by user. However, i am not sure whether to use AsyncTask or Handler to do so or even combining both to achieved the task. And also, while the timer is running, user might change the time and so the program would have to change accordingly. A: The TimerTask already runs on it's own thread, so you don't need to use an AsyncTask just put the code you want to run in the TimerTask.run() method. All The Best
{ "language": "en", "url": "https://stackoverflow.com/questions/7618195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does this keep recreating my database? I am using fluent nhibernate and have this line private static void BuidSchema(NHibernate.Cfg.Configuration config) { new SchemaExport(config).Execute(false,true,false); } now this keeps on recreating my database. Am I misunderstanding the parameters? documentation script true if the ddl should be outputted in the Console. export true if the ddl should be executed against the Database. justDrop true if only the ddl to drop the Database objects should be executed. format true if the ddl should be nicely formatted instead of one statement per line. I thought setting the justDrop to false would stop my db from being recreated if it exists. A: If you set export to true it will drop a recreate your database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to init slug mongoid_slug for generated model in Rails 3? I have a project and everything is near complete! I've just used mongoid_slug for my project to make readable link! In my model, i have 2 more lines: "include Mongoid:slug" and "slug :title" and in my controller I call *.find_by_slug(params[:id]) but the result is always is null! After finding for a while, I find out that my old models does't load the slug!! I know that I have to init my slug for my model first, and I have to write a rake tastk in db.rb! However, I dont' know how to write it!! Is there any suggestion? Thanks you! A: Are you using inherited resources? if so yo will need to override the definitions of collection and resource to use find by slug.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I save the previous text in textarea I am using a button to input text from a text input and displaying it in a text area using following code. public function sendMessage():void { mytextarea.text = textinput.text; textinput.text = ""; } The problem I am facing is , whenever I add new line or others it replaces the previous text, I want the previous text in text area to stay there. Any hints how to do that? A: Instead of setting the text, append new text with the previous texts. mytextarea.text += textinput.text; A: Building on @taskinoor 's answer, you should try use appendText() where possible over the += operator. From documentation for flash.text.TextField: Appends the string specified by the newText parameter to the end of the text of the text field. This method is more efficient than an addition assignment (+=) on a text property (such as someTextField.text += moreText), particularly for a text field that contains a significant amount of content. Parameters newText:String — The string to append to the existing text. So your code would be: mytextarea.appendText(textinput.text);
{ "language": "en", "url": "https://stackoverflow.com/questions/7618208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search By Seconds Not Minutes I have a batch file that works pretty well. I originaly set it up to search for files that are a minute or less old. I need to go down further and search for files that are 15 seconds old. I hope thats quick enough, I might have to adjust it later. In any case can anyone help me get it down to the seconds range. Thank you. Your help is appreciated. @echo off cd "C:\Users\DS\Downloads" setlocal call :DateToMinutes %date:~-4% %date:~-10,2% %date:~-7,2% %time:~0,2% %time:~3,2% NowMins set flag=0 for /f "delims=" %%a in ('dir *.jpg *.zip *.txt /a-d /b') do call :CheckMins "%%a" "%%~ta" if %flag% EQU 1 ( msg * "Good-Bye!" ) set flag=0 goto :EOF :CheckMins set File=%1 set TimeStamp=%2 call :DateToMinutes %timestamp:~7,4% %timestamp:~1,2% %timestamp:~4,2% %timestamp:~12,2% %timestamp:~15,2%%timestamp:~18,1% FileMins set /a MinsOld=%NowMins%-%FileMins% if %MinsOld% leq 1 del %file% if %MinsOld% leq 1 set flag=1 goto :EOF :DateToMinutes setlocal set yy=%1&set mm=%2&set dd=%3&set hh=%4&set nn=%5 if 1%yy% LSS 200 if 1%yy% LSS 170 (set yy=20%yy%) else (set yy=19%yy%) set /a dd=100%dd%%%100,mm=100%mm%%%100 set /a z=14-mm,z/=12,y=yy+4800-z,m=mm+12*z-3,j=153*m+2 set /a j=j/5+dd+y*365+y/4-y/100+y/400-2472633 if 1%hh% LSS 20 set hh=0%hh% if /i {%nn:~2,1%} EQU {p} if "%hh%" NEQ "12" set hh=1%hh%&set/a hh-=88 if /i {%nn:~2,1%} EQU {a} if "%hh%" EQU "12" set hh=00 if /i {%nn:~2,1%} GEQ {a} set nn=%nn:~0,2% set /a hh=100%hh%%%100,nn=100%nn%%%100,j=j*1440+hh*60+nn endlocal&set %6=%j%&goto :EOF A: I didn't know a simple batch way to get the seconds, but you can get them via WMIC. WMIC DATAFILE WHERE Name="C:\\windows\\DirectX.log" GET lastmodified,Lastaccessed The format of the output is a bit odd, but it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing EJB with embedded container. How can I log in? I'm trying to test my EJBs with the embedded container. container = EJBContainer.createEJBContainer(); But I have some of my methods that are restricted to some roles. So, my question is. How can I log into the container so I can test these methods simulating the user that will call the Session Bean ? Thanks A: I found a post in Oracle blog answering my question to whoever needs as well. The answer is to use ProgrammaticLogin. You can find more information here. http://blogs.oracle.com/nithya/entry/running_a_secure_application_using
{ "language": "en", "url": "https://stackoverflow.com/questions/7618212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: html5 canvas images dont show or image not loaded i remove the link for copyright reason !.. sorry ! When you are in Firefox, the images at the left (all the mockup) is loaded, after a few refresh, in chrome and safari, it NEVER show I think it's a image not loaded in memory problem, but i cant know when image are all loaded, i event put the script at the end, but no luck So the question, what should do to make sur the images are loaded.. of is there and error in the JavaScript code ? n.b. i have tough about encoding the images as base64 for canvas display... is it possible or intelligent to do that ? A: Actually, you can determine when all the images have finished loading. In order to do this, you just need to specify a callback function for the onload property of the image object. So, you would end up with something like this (in addition to the code you already have in canvas.js): var loaded_images = 0; var image_objects = []; // This is called once all the images have finished loading. function drawOnCanvas() { for (var i = 0; i < image_objects.length; ++i) { ctx.drawImage(image_objects[i], 0, 0); } } function handleLoadedImage() { ++loaded_images; // Check to see if all the images have loaded. if (loaded_images == 7) { drawOnCanvas(); } } document.ready = function() { for (var i=0;i<myimages.length;i++) { var tempimage = new Image(); tempimage.src= myimages[i]; tempimage.onload = handleLoadedImage; image_objects[i] = tempimage; } } The key concept is that you are keeping track of the number of images that have finished loading. Once all of the images are done loading, you know you can draw on the canvas.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: why "Single-quoted string preferred over double-quoted string." in js? While using gjslint, I got a hint: "Single-quoted string preferred over double-quoted string". So why? I'm a little confused with this. Why single-quoted preferred? Hope to get some help. Thanks all. A: It's just somebody's opinion. Lots of people do prefer singe-quotes, but lots of other people prefer double-quotes. I tend to use double-quotes just out of habit from other languages, but I don't have a strong preference: I'm willing to change if I hear of a compelling reason why single-quotes are better, but to date I've not even heard a good reason, let alone a compelling reason. Even the Google JavaScript Style Guide says that single-quotes are preferred without giving a good reason: "For consistency single-quotes (') are preferred to double-quotes ("). This is helpful when creating strings that include HTML" (It then goes on to give a very short example of a string that doesn't even include HTML.) A lot of people seem to believe XHTML is only valid with double-quotes, but that is not true: the XHTML spec allows either. (Having said that, 98% of the XML I've run across, including XHTML, does use double-quotes.) Within any one source file I try to stick to one or the other, but if a line of code in the middle needed a lot of embedded quotes I'd be happy to change for just that line to avoid lots of escaping in that line. UPDATE: Just remembered that JSON is only valid with double-quotes. Obviously JSON is not JavaScript, but still that's a reason why (a) some might prefer double-quotes in their JavaScript so that object literals look like JSON, and (b) some might prefer single-quotes so that they can manually encode JSON without having to escape the double-quotes. (No, I don't recommend manually encoding JSON, but I've seen it done.) A: My keyboard has a '/" key so I can easily type a single quote but need to press shift for the double quote. :) As for the JSLint warnings its just trying to enforce an arbitrary standard in order to promote a more consistent coding style, just like how it does on other spacing and indentation issues. A: If you use single quotes, you do not have to escape the double quotes in your html. For example... With single quotes you can do this var a = '<a href="something.html" rel="yes" title="whatever">a link/a>'; with double quotes you would need to escape those inside double quotes, like so var a = "<a href=\"something.html\" rel=\"yes\" title=\"whatever\">a link/a>"; Much more work, more difficult to maintain, and easier to commit errors. A: In terms of performance, according with http://jsperf.com you get almost the same performance for both in some browsers, in others you get the same performance. There's a lot of tests in jsperf and all of them get almost the same result: * *http://jsperf.com/double-or-simple-quote *http://jsperf.com/quotes-compare *http://jsperf.com/jquery-double-vs-single-quotes *http://jsperf.com/search?q=quote In conclusion I think using single or double quotes is just a matter of taste and not a matter of performance. Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Parent div to match tallest child div's height? I'm making a website with a "page" div, and inside that contains the left div "navigation" and the right div "content". I want to make the height of the "page" div (so the background matches) equal to the height of the tallest div, either "navigation" or "content". How would I go about doing this? A: write like this html: <div class="page"> <div class="navigation"></div> <div class="content"></div> </div> css: page{overflow:hidden} .navigation, content{float:left} A: I'm guessing you're floating the other divs, otherwise this would always be the case. You can either float the parent div as well, or add a <div style='clear: both'></div> just before the end of the parent div. Either of these techniques will cause the parent div to be as big as its children. EDIT: whoops, missed the end tag :) A: This will help you HTML <div class="page"> <div class="navigation">i am navigation</div> <div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est maiores, ex? Mollitia assumenda veniam aliquid commodi ex, libero in quia perspiciatis sint voluptatibus soluta exercitationem quas quos repudiandae deserunt obcaecati.</div> </div> CSS .page { background-color: #000; } /* for clearfix*/ .page:after{ content: ""; display: table; clear: both; } /* for clearfix end*/ .navigation,.content { float: left; } .navigation { width: 20%; background-color: #cd6a51; } .content { width: 80%; background-color: #4CAF50; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ruby Time.zone.now.zone bug What I mean is that there are different timezones with the same name, like CST (-06:00 in US and +09:30 in Australia). Accordingly conversion to utc gives wrong results for Adelaide. Any elegant way to solve this? A: an easy way would be that you use the other nomenclature of naming time zones.. e.g. for UTC+9:30 intstead of using CST, you can use "Australia/Adelaide" tz = TZInfo::Timezone.get("Australia/Adelaide") t = Time.now # you could also get the UTC time here with Time.now.utc t.zone => "PDT" t.utc_offset => -25200 t.in_time_zone(tz) # this is a Rails extension of the Time class => Sat, 01 Oct 2011 14:31:05 CST +09:30 t.in_time_zone(tz).zone => "CST" t.in_time_zone(tz).utc_offset => 34200 See: http://api.rubyonrails.org/classes/Time.html http://tzinfo.rubyforge.org/doc/ http://en.wikipedia.org/wiki/List_of_tz_database_time_zones do a "gem install activesupport", and in your script: require 'rubygems' require 'tzinfo' require 'active_support'
{ "language": "en", "url": "https://stackoverflow.com/questions/7618221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make derived class function be executed? We have a base class: Filter. DistrFilter and ReportFilter inherit from Filter. In another class, FilterService.cs, we have two functions that accept these three class types. FilterService operates on Filter objects but it does not inherit from anything. public class FilterService { public string GetDesc(List<T> filters) where T : Filter { if(filters.Count == 0) return String.Empty; StringBuilder s = new StringBuilder("<ul>"); foreach (T f in filters) s.AppendFormat("<li>{1}</li>", GetFilterText(f)); s.Append("</ul>"); return s.ToString(); } public string GetFilterText(Filter f) { return "filter"; } public string GetFilterText(DistrFilter f) { return "distr filter"; } public string GetFilterText(ReportFilter f) { return "report filter"; } } public static void main(string[] args) { List<DistrFilter> distrFilters = new List<DistrFilters>(); distrFilters.Add(new DistrFilter()); distrFilters.Add(new DistrFilter()); distrFilters.Add(new DistrFilter()); FilterService fs = new FilterService(); Console.WriteLine(fs.GetDescription(distrFilters)); } Then it prints: * *filter *filter ... How do I get it to print this instead? * *distr filter *distr filter ... A: Add a virtual method to the Filter class, called GetName() or something similar, and implement it as return "distr filter"; in DistrFilter and as return "report filter"; in ReportFilter. Then just call f.GetName() in GetDesc(). Alternatively, you could use checks like if (f is DistrFilter) in GetDesc(), but that sort of structure, explicitly checking for specific derived classes and handling them differently, is generally considered poor design. A: Implement a pattern that does something like this: public class Filter { public virtual string GetDescription() { return "filter"; } } public class DistrFilter : Filter { public override string GetDescription() { return "distr filter"; } } public class ReportFilter : Filter { public override string GetDescription() { return "report filter"; } } public class FilterService { public string GetDescription<T>( List<T> filters ) where T: Filter { if ( filters.Count == 0 ) return String.Empty; StringBuilder s = new StringBuilder( "<ul>" ); foreach ( T f in filters ) s.AppendFormat( "<li>{0}</li>", f.GetDescription() ); s.Append( "</ul>" ); return s.ToString(); } } A: Either implement GetFilterText() as a virtual method in Filter: class Filter { // Can be converted into a property as well. public virtual string GetFilterText { return "filter"; } } class DistrFilter : Filter { public override string GetFilterText { return "distr filter"; } } Then do this: StringBuilder s = new StringBuilder("<ul>"); foreach (T f in filters) s.AppendFormat("<li>{0}</li>", f.GetFilterText()); Or if you want to separate the concern of specifying the filter text from the Filter classes, use double dispatch (visitor pattern). This is useful if you can have different types of filter services. This can be done this way: interface IServiceAcceptor { string Accept(FilterService service); } public class Filter : IServiceAcceptor { string IServiceAcceptor.Accept(FilterService service) { return service.GetFilterText(this); } } public class DistrFilter : Filter, IServiceAcceptor { string IServiceAcceptor.Accept(FilterService service) { return service.GetFilterText(this); } } public class ReportFilter : Filter, IServiceAcceptor { string IServiceAcceptor.Accept(FilterService service) { return service.GetFilterText(this); } } Then in your service: public string GetDesc<T>(List<T> filters) where T : IServiceAcceptor { if(filters.Count == 0) return String.Empty; var s = new StringBuilder("<ul>"); foreach (T f in filters) s.AppendFormat("<li>{0}</li>", f.Accept(this)); s.Append("</ul>"); return s.ToString(); } Some references: Double dispatch, Visitor Pattern
{ "language": "en", "url": "https://stackoverflow.com/questions/7618225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: d3 + Backbone: updating elements for which data has changed I'm using d3 with Backbone.js models. When the model attributes change, an event is fired and the model is marked with a hasChanged() flag and it returns a changedAttributes() hash. I understand how to use d3's enter() and exit() to handle models that have either been created or removed. What I am having trouble figuring out is how I can modify the respective DOM elements based on model attributes changing. I can use the Backbone helpers to figure out what to modify, but what is the next step with d3? A: I got some helpful responses on the d3 mailing list: http://groups.google.com/group/d3-js/browse_thread/thread/65c4c8ffb5515ab2 And my solution, based on that advice, is at: https://gist.github.com/1257765
{ "language": "en", "url": "https://stackoverflow.com/questions/7618226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can I combine my code into some kind of "global activity"? Is there any global activity on Android such that I put my code in that one activity, and it affects all activities in my project? This occurs to me because the same code is written in multiple activities like KeyEvent.KEYCODE_BACK For example here I use: public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { try { final Intent itnt_BackServices = new Intent(this, BackServices.class); AlertDialog.Builder alertbox = new AlertDialog.Builder(this); alertbox.setTitle("Touch signs"); alertbox.setMessage("Do you want to quit!"); alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { stopService(itnt_BackServices); mPlayer.stop(); finish(); } }); alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); alertbox.show(); } catch (Exception e) { // TODO: handle exception } } return false; } I copy and paste this in each activity, and I would rather use some kind of global activity. A: You can create a class that extends Activity and then extend the CustomActivity to all the Activity Class like this. public abstract class CustomActivity extends Activity{ public abstract void initComponents(); // you can create a abstract method public abstract void addListner(); // you can create a abstract method @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { // your stuff here.... } return true; } } Now you can extend this class where you want to extend any class with Activity. A: Take your first main activity write code there, and simply after that extend all the other activity with this activity.....e.g. MainActivity is your first and main activity then write this code there, and after that simply take an activity say it First then extend it with MainActivity rather than Activity...!! and That's it.......... A: I would suggest extending activity as @Lalit Poptani suggested. Since that is been said i could provide an alternative way for this to work. You can create an interface that you implement in your activity including public boolean onKeyDown(int keyCode, KeyEvent event) (just to keep you a reminder you have to implement the code to your activity) Create a global (static) class/function that performs the onKeyDown operations. public class ButtonHandler{ public static boolean handleButton(Context context,int keyCode, KeyEvent event){ ..... your code here } } and just call return ButtonHandler.handleButton(getApplicationContext(),keycode,event) to your onKeyDown methods. But still .. overriding activity is the best way to go. If for some reason you don't want to extend this is the way to go
{ "language": "en", "url": "https://stackoverflow.com/questions/7618227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What mechanism do async tasks use in ASP.Net MVC 4.0? What is the mechanism behind async tasks in MVC 4? How is it related to normal threading? Please provide detail. A: If you are interested in async and await keywords, you might find this Channel 9 interview with Anders Hejlsberg interesting. Also, take a look at: this PDC video. A: As already indicated before, async keyword is part of .Net. For better implementation of asynchronous programming, Microsoft has released several CTPs for this and it will be out of the box on .Net 4.5 AFAIK. Below article is helpful as well : http://www.juliencorioland.net/Archives/en-aspnet-mvc-4-asynchronous-controllers A: Normally, a single ASP.NET page request is handled by a single thread. After the thread sends the response, it returns to the ASP.NET thread pool. When you use async/await (or asynchronous pages), the thread handling the request marks the request as incomplete and then returns to the ASP.NET thread pool. When the awaitable completes later, an ASP.NET thread is assigned to run the rest of the method. More specifically, async/await by default use SynchronizationContext. See my MSDN article for more details. A: Async Tasks is a feature of .NET, not of ASP.NET MVC 4. They work the same in ASP.NET as they do elsewhere within .NET.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: separating string of characters and int from a input string in c++ I am trying to sort integers and strings from an input string. #include <stdio.h> #include <time.h> #include <stdlib.h> #include <string.h> int main(){ char x[10]; int y; printf("string: "); scanf("%s",x); y=atoi(x); printf("\n %d", y); getchar(); getchar(); } suppose the input is 123abc1 using atoi i could extract 123 from the input string, my question now is how do i extract abc1? I want to store abc1 on a separate character variable. input: 123abc1 output: x = 123, some char variable = abc1 I appreciate any help. A: If you wish to use the C programming language concepts, then consider using strtol intead of atoi. It will let you know what character did it stop at: Also, never use %s in a scanf, always specify the buffer size (minus one, since %s will add a '\0' after storing your input) #include <stdio.h> #include <stdlib.h> int main(void) { printf("string: "); char x[10]; scanf("%9s",x); char *s; int y = strtol(x, &s, 10); printf("String parsed as:\ninteger: %d\nremainder of the string: %s\n",y, s); } test: https://ideone.com/uCop8 In C++, if that tag was not a mistake, there are simpler approaches, such as stream I/O. For example, #include <iostream> #include <string> int main() { std::cout << "string: "; int x; std::string s; std::cin >> x >> s; std::cout << "String parsed as:\ninteger: " << x << '\n' << "remainder of the string: " << s << '\n'; } test: https://ideone.com/dWYPx A: If that's the way you want to go, then after extracting the number convert it back to its textual representation and that string length will tell you were to find the start of the string. So for your particular example: char* x = "123abc1" atoi( x ) -> 123; itoa/sprintf( 123 ) -> "123", length 3 x + 3 -> "abc1" Can't you just do it with a single scanf? scanf( "%d%s", &y, z );
{ "language": "en", "url": "https://stackoverflow.com/questions/7618235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In cmd can I dir /s but only to n sub directories? In the Windows command shell, cmd, is there a way to C:> dir /s but only to n sub directories? Seems to me that I have made this work in the past, though I may have corrupted that sector in my brain with certain cell damaging liquids... :P I guess I could redirect the output into a log and then skim it with findstr or qgerp but it seems like there should be a cleaner way. A: "Cleaner way"? With DOS commands like "dir"? You've got a dry sense of humor, there ;) You can do a "dos /?" to query available options. "limit recursion to 'n' directores with /s" is definitely not one of them. If you want to do that, you'd need to write your own program ... or redirect to a text file and parse the file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Android support slow-motion video playback? I need to make video player on Android that is able to play in slow motion and with different playback speeds. I still cannot find a native API or some code to do this. Does Android 2.2 - 2.3 support to video slow-motion and can we control the video playback speed? A: Yes, from API 23 android has PlaybackParams class .It supports adjustment of playback speed of video briefly given here . A: You can try exploring libVLC for this. VLC player for Android is almost due. Check their website. Check this thread that discusses how you do it.. http://forum.videolan.org/viewtopic.php?f=14&t=89296 libVLC developer documentation here with normal playback sample. You need to modify this sample to play the video frame by frame or slow down the frame rate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Inserting the elements in grid column wise and creating different controls I am new to Asp.net and C#.I am working in a project where I need to create GridView.Now I wanted to bind this column wise with the data.Like the column1 in the grid is "Category" in the table of database and so on. I also want to create the Hyperlink on the basis of the content in database for example I want to show the text of Hyperlink as "This is Java program" and URL specifies as "http://blogs.article?id=1".Please tell me that how I can do that.Currently I am able to bind the all three columns in the table to the three columns in the grid. A: Take a look at the HyperLinkField class. This should provide exactly what you're looking for. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlinkfield.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7618245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to parse the xml using nsxmlparser with same names of multiple nodes in iphone programming? How can I parse using NSXMLParser if I need all the images, <title>Title</title> <description>my description is here </description> <images> <image>http://www.sosmoths.com/mothImages/800px-Tineola.bisselliella.7218.jpg</image> <image>http://www.sosmoths.com/mothImages/800px-Tineola.bisselliella.mounted.jpg</image> <image>http://www.sosmoths.com/mothImages/800px-XN_Tineola_bisselliella_1.jpg</image> <image>http://www.sosmoths.com/mothImages/Tineola_bisselliella.JPG</image> </images> There are more nodes like title, description, so how to parse such xml, I am confused about image nodes, I am thinking to use NSMutableArray for this, but still not clear to do code? A: - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:"<image>"]) { [imagearray addObject:imageurl]; } } Before this you need to find the element name is and then do above code.This may help you. A: use this it work -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{ NSLog(@"%@",elementName); if([elementName isEqualToString:@"moths"]){ mytblarray=[[NSMutableArray alloc] init]; } else if([elementName isEqualToString:@"moth"]){ tmpdic=[[NSMutableDictionary alloc] init]; } else if([elementName isEqualToString:@"images"]){ imgArray=[[NSMutableArray alloc] init]; } } -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ if(tmpstr!=nil && [tmpstr retainCount]>0){ [tmpstr release]; tmpstr=nil; } tmpstr=[[NSString alloc] initWithString:string]; } -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ if([elementName isEqualToString:@"moth"]){ [mytblarray addObject:tmpdic]; [tmpdic release]; }if([elementName isEqualToString:@"images"]){ [tmpdic setValue:imgArray forKey:elementName]; } else if([elementName isEqualToString:@"image"]){ [imgArray addObject:tmpstr]; } } A: * *take dictionary in initWithData: methode *Take values as key like title, description *in didStartElement method, in images tag alloc image_array *in didEndElement method, in image tag add your data(here your image link) to image_array *now in didEndElement method, in images tag add that array to your main dictionary as key images that's all.....
{ "language": "en", "url": "https://stackoverflow.com/questions/7618247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Secure a Cocoa Touch Library with Remote Server, Local Script, and License-Key Background I want to create a Cocoa Touch library where others will be limited to a finite number deployment builds using said library. However, there should be no limitations on the number of development builds. I was considering a remote server which generates license-keys each associated with the library and a number of permitted deployment builds on the library. When the user of the library builds for deployment, I need to check against the keys on the remote server. Question Does this seem like a sound approach for what I want to accomplish? If so, how does one check only for deployment builds while preventing the user from tampering with the script/binary that does the checking? If not, what would make it a sound approach? A: Imagine the joy and rapture if every library you used was making calls to some random server, affecting your customers, hurting their experience. Making your development of your product a living hell for testing and distribution. Yea, that'd be a hoot. Get a lawyer, get a solid contract, reserve the right to audit their sales, etc. Companies have had such arrangements for years, and actually abide by them with little more than a piece of paper and couple of signatures.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone:Convert NSMutableArray to NSData with stored & retrieved issue I am facing a problem, that is to convert NSMutableArray into NSData and stored & retrieved that array into rootviewcontroller so please give me idea. Here is the code I'm working with: appDelegate = (FindNearMeAppDelegate *)[[UIApplication sharedApplication]delegate]; appDelegate.isCategoryCell = TRUE; appDelegate.isButton = NO; NSString *categoryStr = categoryName.text; NSLog(@"Category Name:--->%@",categoryStr); appDelegate.categoryData = [NSMutableDictionary dictionaryWithObjectsAndKeys: categoryStr, @"name",image ,@"image", nil]; [appDelegate.categories addObject:appDelegate.categoryData]; NSLog(@"Category Data:--->%@",appDelegate.categories); I am initialize nsmutablearray (appDelegate.categories) and nsmutabledictionary in appdelegate. Thanks in advance. A: From what I understand, you want to save your images and retrieve them. You can convert your image to NSData using one of the 2 methods, UIImagePNGRepresentation or UIImageJPEGRepresentation depending on the type of the image. You can then save this data- NSData* imageData = UIImagePNGRepresentation(image); [imageData writeToFile:imagePath atomically:YES]; //imagePath is where you want to save it. Most likely it contains the value of the name key in your dictionary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript is cached in development mode with asset pipeline I recently upgraded my application to rails 3.1 and generally everything seems to be working but one thing is driving me insane. I have 2 main js files, we'll call them, application.js and main.js. application.js has my manifest stuff in it and is loading in main.js. That's working fine. My problem is when i'm in development mode and i make a change to main.js, then refresh the page the site doesn't pick up the change. In order to pull in the change I have restart the rails server. I have debug mode turned on in development, but I'm wondering if there's another setting i'm missing? Anyone run into this before? A: I had the same issue and found that removing the asset digests in development fixed the issue. Make sure you set it to false in developmen.rb: config.assets.digest = false A: I had the same problem, and I finally stumbled across something in my development.rb. I had config.action_controller.perform_caching set to true, and changing it to false solved the problem. A: Opening Chrome in incognito mode worked best for me. No need to open and close a tab. In incognito mode, chrome doesn't cache javascript. A: Also note that if you enable config.threadsafe, it will turn cache_classes on. So if your config/environments/development.rb file contains the following: config.cache_classes = false config.threadsafe! Then you are turning off cache_classes and then turning it right back on. You will need to either comment out config.threadsafe (if you don't need it) like this: config.cache_classes = false # config.threadsafe! Or, if you need threadsafe, reverse the order of these two configurations so that config_classes is really turned off: config.threadsafe! config.cache_classes = false For more information, see http://tenderlovemaking.com/2012/06/18/removing-config-threadsafe.html A: I had the same issue, but config.action_controller.perform_caching was already set to false. For me and another guy I was working with, the problem was that Chrome was caching the page despite the settings in Rails. To fix it, we just closed the tab, opened a new tab, and visited the site again. A: Have a look at your development log and see what it says when the application.js is served. It should look something like this for a normal request (you browsed to a page): Started GET "/assets/application.js" for 127.0.0.1 at Fri Sep 30 12:13:27 +1300 2011 Served asset /application.css - 304 Not Modified (2ms) If not you may have not set the pipeline options correctly. One of the production settings might be in the wrong place. Section 9 of the asset pipeline guide has a checklist of correct settings for a migrated app. A: I had the same issue, config.action_controller.perform_caching set properly. I also use Heroku and precompile assets for the Push to Heroku using: RAILS_ENV=production bundle exec rake assets:precompile After the push, when I started new work, I forgot to remove the precompiled assets using: sudo rm -r public/assets/* So, no matter what I did to any of my .js files, they changes were not showing up. A: If above mentioned answers fail in your context.. make sure the caching is done by rails.. some times it does not detect changes in asset and serve the older cached version.. use rails c >> Rails.cache.clear or simply delete the caches in tmp dir [project_dir/tmp/cache/assets"]
{ "language": "en", "url": "https://stackoverflow.com/questions/7618254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: php script now receiving errors under php 5.3? I am getting the following response in ssh when trying to run this php script... it worked fine under php 5.2 and now with 5.3 installed I am running into trouble. I cannot see what is wrong. The errors : line 1: ?php: No such file or directory line 2: syntax error near unexpected token `0' line 2: `set_time_limit(0) ;' Here is the script. <?php set_time_limit(0) ; $arr = explode("/",$_SERVER['SCRIPT_FILENAME']); $ct = count($arr); unset($arr[$ct-1]); $path=implode("/",$arr); $path=$path."/"; if(is_file($path."state.txt")) { $lines = file($path."state.txt"); if($lines) { foreach($lines as $line) { if($line) { $state = trim($line); if(!is_dir($path.$state)) { @mkdir($path.$state,0777); if(is_file($path."copieble/state/index.php")) { $from = $path."copieble/state/index.php"; $to = $path.$state."/index.php"; @copy($from,$to); } } } } } } @chdir($path); $handle=opendir('.'); while (($file = readdir($handle))!==false) { @chdir($path); if (($file != ".") && ($file != "..")) { if(is_dir($file) && $file != "copieble" && $file !="_vti_cnf") { if(is_file($path.$file.".txt")) { $lines = file($path.$file.".txt"); if($lines) { foreach($lines as $line) { if($line) { $city = trim($line); @chdir($path.$file); if(!is_dir($city)) { @mkdir($city,0777); if(is_file($path."copieble/city/index.php")) { $from = $path."copieble/city/index.php"; $to = $path.$file."/".$city."/index.php"; @copy($from,$to); } } } } } } } } } closedir($handle); include("reflect_changes.php"); ?> A: I'm guessing that you're running it like this: ./my_script.php Try running it like this: php my_script.php The reason the first would error is that when you try to run it like an executable, the shell first looks to see if there's a hashbang. If so, it runs it with that interpreter. If not (like in your case), it tries to run it as an executable. That, too, fails, so it resorts to trying to execute it as a shell script. <?php in a shell script would try to start reading from a file called ?php and pipe that into a command that follows, but there's no file called ?php to read from. Thus, it errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: send SMS- pending intent/put extras? i'm using the code private void sendSms(String phoneNo, String message){ PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, MainScreen.class), 0); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNo, null, message, pi, null); } i have utilized the onSaveInstanceState to save values such as text and spinner position, which will keep things saved and consistent while receiving intents, navigating away from the activity, etc not sure if i can put extras in the pending intent, so that when it starts my main activity, i can use those extras. because somehow, when the pending intent goes through, i need it to restore to the way it was before the intent was called A: You can.. but you must clear the previous pending intent or use the one shot flag while constructing your pending intent.. like this Intent sentIntent = new Intent(SENT_SMS_ACTION); sentIntent.putExtra(MESSAGE_ID_TAG, messageId); PendingIntent sentPendingIntent = PendingIntent.getBroadcast(this, 0, sentIntent, PendingIntent.FLAG_ONE_SHOT);
{ "language": "en", "url": "https://stackoverflow.com/questions/7618261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Freeze last frame of animation new code? I'm trying to freeze the last frame of an animation. The following code used to work, however after an update to iOS it no longer works. How can I write this code so that the last image stays on the screen? animation.animationImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"watermelondrop2.png"], [UIImage imageNamed:@"watermelondrop4.png"], [UIImage imageNamed:@"watermelondrop6.png"], [UIImage imageNamed:@"watermelondrop8.png"], [UIImage imageNamed:@"watermelondrop10.png"], [UIImage imageNamed:@"watermelondrop12.png"], [UIImage imageNamed:@"watermelondrop14.png"], [UIImage imageNamed:@"watermelondrop15.png"], nil]; animation.animationDuration = .8; animation.animationRepeatCount = 1; [animation startAnimating]; [self playwatermelondropsound]; [self.view addSubview:animation]; animation.image = [UIImage imageNamed:@"watermelondrop16.png"]; A: I spend 40 my minutes to resolve your problem, and it was just so simple: There are two way you can achieve what you want: * *Set the image you want on your screen as default image. *or just do this, //make your last line to first line. animation.image = [UIImage imageNamed:@"watermelondrop16.png"]; animation.animationImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"watermelondrop2.png"], [UIImage imageNamed:@"watermelondrop4.png"], [UIImage imageNamed:@"watermelondrop6.png"], [UIImage imageNamed:@"watermelondrop8.png"], [UIImage imageNamed:@"watermelondrop10.png"], [UIImage imageNamed:@"watermelondrop12.png"], [UIImage imageNamed:@"watermelondrop14.png"], [UIImage imageNamed:@"watermelondrop15.png"], nil]; animation.animationDuration = .8; animation.animationRepeatCount = 1; [animation startAnimating]; [self playwatermelondropsound]; [self.view addSubview:animation]; And guess what it'll start working, as I have tested it. :) A: [self cleanStance]; NSArray *imageArray = [[NSArray alloc] initWithObjects: [UIImage imageNamed:@"jump1.png"], [UIImage imageNamed:@"jump2.png"], nil]; self.player.animationImages = imageArray; self.player.animationDuration = 0.3; //self.player.contentMode = UIViewContentModeBottomLeft; [self.view addSubview:self.player]; [self.player startAnimating]; - (void)cleanStance { [self.player setImage:nil]; self.player.animationImages = nil; } This is the example to show the image jumping i thick this may help u A: Your code looks fine to me, except when I do it, I usually set the .image property of the UIImageView BEFORE I tell the UIImageView to start animating. Also, add [UIImage imageNamed:@"watermelondrop16.png"] to the end of your .animationImages array. Maybe that will fix your problem. Hope that Helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7618262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: troubleshooting "pseudo-hashes are deprecated" while using xml module I am just learning how to use perl hashes and ran into this message in perl. I am using XML::Simple to parse xml output and using exists to check on the hash keys. Message: Pseudo-hashes are deprecated at ./h2.pl line 53. Argument "\x{2f}\x{70}..." isn't numeric in exists at ./h2.pl line 53. Bad index while coercing array into hash at ./h2.pl line 53. I had the script working earlier with one test directory and then executed the script on another directory for testing when I got this message. How do I resolve/workaround this? Code that the error references: use strict; use warnings; use XML::Simple; use Data::Dumper; #my $data = XMLin($xml); my $data = XMLin($xml, ForceArray => [qw (file) ]); my $size=0; if (exists $data->{class} and $data->{class}=~ /FileNotFound/) { print "The directory: $Path does not exist\n"; exit; } elsif (exists $data->{file}->{path} and $data->{file}->{path} =~/test-out-00/) { $size=$data->{file}->{size}; if ($size < 1024000) { print "FILE SIZE:$size BYTES\n"; exit; } } else { exit; } print Dumper( $data ); Working test case, data structure looks like this: $VAR1 = { 'recursive' => 'no', 'version' => '0.20.202.1.1101050227', 'time' => '2011-09-30T02:49:39+0000', 'filter' => '.*', 'file' => { 'owner' => 'test_act', 'replication' => '3', 'blocksize' => '134217728', 'permission' => '-rw-------', 'path' => '/source/feeds/customer/test/test-out-00', 'modified' => '2011-09-30T02:48:41+0000', 'size' => '135860644', 'group' => '', 'accesstime' => '2011-09-30T02:48:41+0000' 'modified' => '2011-09-30T02:48:41+0000' }, 'exclude' => '' }; recursive:no version:0.20.202.1.1101050227 time:2011-10-01T07:06:16+0000 filter:.* file:HASH(0x84c83ec) path:/source/feeds/customer/test directory:HASH(0x84c75d8) exclude: Data structure with seeing error: $VAR1 = { 'recursive' => 'no', 'version' => '0.20.202.1.1101050227', 'time' => '2011-10-03T04:49:36+0000', 'filter' => '.*', 'file' => [ { 'owner' => 'test_act', 'replication' => '3', 'blocksize' => '134217728', 'permission' => '-rw-------', 'path' => '/source/feeds/customer/test/20110531/test-out-00', 'modified' => '2011-10-03T04:47:46+0000', 'size' => '121406618', 'group' => 'feeds', 'accesstime' => '2011-10-03T04:47:46+0000' }, Test xml file: <?xml version="1.0" encoding="UTF-8"?><listing time="2011-10-03T04:49:36+0000" recursive="no" path="/source/feeds/customer/test/20110531" exclude="" filter=".*" version="0.20.202.1.1101050227"><directory path="/source/feeds/customer/test/20110531" modified="2011-10-03T04:48:19+0000" accesstime="1970-01-01T00:00:00+0000" permission="drwx------" owner="test_act" group="feeds"/><file path="/source/feeds/customer/test/20110531/test-out-00" modified="2011-10-03T04:47:46+0000" accesstime="2011-10-03T04:47:46+0000" size="121406618" replication="3" blocksize="134217728" permission="-rw-------" owner="test_act" group="feeds"/><file path="/source/feeds/customer/test/20110531/test-out-01" modified="2011-10-03T04:48:04+0000" accesstime="2011-10-03T04:48:04+0000" size="127528522" replication="3" blocksize="134217728" permission="-rw-------" owner="test_act" group="feeds"/><file path="/source/feeds/customer/test/20110531/test-out-02" modified="2011-10-03T04:48:19+0000" accesstime="2011-10-03T04:48:19+0000" size="125452919" replication="3" blocksize="134217728" permission="-rw-------" owner="test_act" group="feeds"/></listing> A: The "Pseudo-hashes are deprecated" error means you're trying to access an array as a hash, which means that either $data->{file} or $data->{file}{path} is an arrayref. You can check the data type by using print ref $data->{file}. The Data::Dumper module may also help you to see what is in your data structure (perhaps while setting $Data::Dumper::Maxdepth = N to limit the dump to N number of levels if the structure is big). UPDATE Now that you are using ForceArray, $data->{file} should always point to an arrayref, which may possibly have multiple references to path. Here is a modified segment of your code to handle that. But note that the logic of the if-then-exit conditions may have to change. if (defined $data->{class} and $data->{class}=~ /FileNotFound/) { print "The directory: $Path does not exist\n"; exit; } exit if ! defined $data->{file}; # filter the list for the first file entry named test-out-00 my ( $file ) = grep { defined $_->{path} && $_->{path} =~ /test-out-00/ } @{ $data->{file} }; exit if ! defined $file; $size = $file->{size}; if ($size < 1024000) { print "FILE SIZE:$size BYTES\n"; exit; } A: When using XML::Simple, the ForceArray option is one of the most important to understand, especially in cases when your input data has nested elements that can occur 1 or more times. For example: use XML::Simple; use Data::Dumper; my @xml_snippets = ( '<opt> <name x="3" y="4">B</name> <name x="5" y="6">C</name> </opt>', '<opt> <name x="1" y="2">A</name> </opt>', ); for my $xs (@xml_snippets){ my $data = XMLin($xs, ForceArray => 0); print Dumper($data); } Output: $VAR1 = { 'name' => [ # Array ref because there are 2 <name> elements. { 'y' => '4', 'content' => 'B', 'x' => '3' }, { 'y' => '6', 'content' => 'C', 'x' => '5' } ] }; $VAR1 = { 'name' => { # No intermediate array ref. 'y' => '2', 'content' => 'A', 'x' => '1' } }; By activating the ForceArray option, you can direct XML::Simple to produce consistent data structures that always use the intermediate array reference, even when there is only 1 of a particular nested element. You can activate the option globally or for specific tags, as illustrated here: my $data = XMLin($xs, ForceArray => 1 ); # Globally. my $data = XMLin($xs, ForceArray => [qw(name foo bar)]); A: First, I recommend that you use ForceArray => [qw( file )] as previously discussed. That will cause an array to be returned for file, whether there's one or more file element. This is easier to handle than having two possible formats. As I previously indicated, the problem is that you made no provision for looping over multiple file elements. You said you wanted to exit if the file doesn't exist, so that means you want my $found; for my $file (@{ $data->{file} }) { if ($file->{path} =~ m{/test-out-00\z}) { $found = $file; last; } } die("Test file not found\n") if !$found; ... do something with file data in $found ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7618269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to add a Ymail/Gmail share button in android app? hi friends i have a custom list coming from server and i want to add two share buttons for Gmail and Ymail resp. in that , its like when i click the Ymail share button it asks for username and password and then redirects me into the compose message section with message body as the link of the respective list and then i can access my contacts to send it to anyone i like. 1. please tell me how to do this?? 2. is there any sdk available for Ymail/gmail please suggest something..thanks in advance A: to share text you don't pick the app you want to use. You pick the type of app you want to use. You can simply start an ACTION_SEND intent. public void help() { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send."); sendIntent.setType("text/plain"); String s = getString(R.string.sharesubject); shareIntent.putExtra(Intent.EXTRA_SUBJECT, s); startActivity(sendIntent); } (source: android.com) How about a share action provider its brand new. my 1st app has a share action provider and it looks a little like this. Basically you just fill up a share intent with the message and attach the intent to the share menu item. search for share action provider example Good Luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7618280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: :dependency => :destroy not working as planned? I currently have a School model, and a Student model. On Student, I have belongs_to :school, :dependent => destroy. However, upon deleting a school, the students whose ID is associated with that school are not deleted. In School, I also have has_many :students. Is there any reason why this is not working? There is a destroy method in the Student model, but it seems like nothing happens to the Student when its School is destroyed. Hoping someone can shed some light on this - perhaps I'm missing something major. A: The :dependent option needs to be given for the has_many relationship in the school class... class School has_many :students, :dependent => :destroy end You will also want to remove the destroy option on your belongs_to association, currently you will delete the associated school record when destroying a student... class Student belongs_to :school end
{ "language": "en", "url": "https://stackoverflow.com/questions/7618285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Difference between nice and setpriority in unix I'm trying to implement a different flavor of the 'nice' command of unix in C. I have seen the definitions of nice() system call and setpriority() call. The nice() call only increments/decrements the priority of the process. If I want to set the priority of a process to a particular value, can't I use the nice() call? Basically, other than how the priority is modified, is there any difference between nice() and setpriority() ? A: It's historical. nice() was introduced long before setpriority(). For backwards compatibility, the nice function was retained. A: nice sets your own priority (the niceness of the current process). setpriority lets you set the niceness of other processes (or process groups or users). Think of it as renice. man 3p nice int nice(int incr); man 3p setpriority int setpriority(int which, id_t who, int value); A: nice() modifies the nice value of the current process relative to its current nice value, so the process doesn't need to know about its starting nice value, it only cares that it should be nicer to the system (e.g: a process launches a child who does some background processing, the child sets itself to be nice). setpriority() use case is the user explicitly setting absolute nice values to specific processes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Nested attributes with polymorphic has_many model I am trying to figure out what is the best way to go about creating a model like "Article" and another model that is a polymorphic model called "comment". The reason I want to do this is so I don't have duplicate models for comments. So at this point I have the polymorphic model up and running and working with the article model. The problem is I want everything to be on one form. The Ability to edit the article and post a comment. Any suggestions would help me out with this dilemma. A: This can be achieved using form_tag <%= form_tag :url => , :html => {:id=> , :method => , :class => ""} do %> <% text_field_tag <id>, <default_value>, :name=>"article[title]" %> <% text_field_tag <id>, <default_value>, :name=>"article[content]" %> <% text_area_tag <id>, <default_value>, :name=>"comment[id]" %> <% text_area_tag <id>, <default_value>, :name=>"comment[id+1]" %> <%= submit_tag 'save' %> <% end %> the params will then nicely be grouped in a hash like {'article' => {'title' => , 'content' => }, 'comment' => {'1' => , '2' => . . .}} which you can parse to update both the models.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error Code 1005 in mysql while applying Foreign key to a table I am having two tables tbluserlogindetail and tblRoles. tbluserlogindetail is as follows CREATE TABLE `tbluserlogindetail` ( `LoginID` varchar(45) NOT NULL, `Name` varchar(45) DEFAULT NULL, `Password` varchar(45) DEFAULT NULL, PRIMARY KEY (`LoginID`), UNIQUE KEY `LoginID_UNIQUE` (`LoginID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ EDIT doratesting.tbluserlogindetail; and my second table tblRoles is as follows CREATE TABLE `tblroles` ( `RoleID` int(11) NOT NULL, `LoginID` varchar(45) NOT NULL, PRIMARY KEY (`RoleID`,`LoginID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$ I tried the the following to assign a primary key for the column LoginID in tblroles table but i don't know where i went wrong can any one help me. I have gone through the documentation but unable to rectify the error so please help me ALTER TABLE tblroles ADD FOREIGN KEY (loginid) REFERENCES tbluserlogindetail(loginid) A: The referenced columns must be unique in the referenced table. Try one of these options: * *The primary key on tbluserlogindetail is (ID, loginid) so you could use that as your foreign key instead of (loginid). This will require you to add a column tbluserlogindetail_ID to tblroles. *Try adding a unique index to the LoginID column of the tbluserlogindetail table. This is only possible if it is actually unique. Also, why is your primary key on tbluserlogindetail defined as PRIMARY KEY (ID, LoginID)? The ID field is an auto-increment field and is already unique. So why do you also include the LoginID as part of the primary key? I think you need to go back to your table design and rethink which columns to choose as your primary keys. A: this is just guess/ assumption ,i like to share here, PRIMARY KEY (ID,LoginID) in tbluserlogindetail are considered as surrogate key, when we execute the child table,That is tblroles, child table expected primary key in parent table, but actually we created the surrogate key, due to this reason, i alter query failed, ALTER TABLE tblroles ADD FOREIGN KEY (LoginID) REFERENCES tbluserlogindetail(LoginID) This is my assumption, give feedback for my answer, I did following changes to execute the Alter table command: 1.tblroles create with given Create query command, after created i manually deleted the LoginID primary key in tblroles table, * *Changed varchar to int in LoginID, *in tbluserlogindetail, deleted the ID AUTO_INCREMENT,Pk. *Check i updated ALTER query
{ "language": "en", "url": "https://stackoverflow.com/questions/7618296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding cookies in jQuery .slideToggle I have a simple .slideToggle function in my project, which is: $(document).ready(function() { $('.example5').show().before('<a class="blocks-hide">Show/Hide</a>'); $('div.blocks-hide').click(function() { $('.example5').slideToggle(250); $('div.blocks-hide').toggleClass('blocks-show'); return false; }); }); And now I want to use cookies plugin with this function. I want the browser to remember whether I had clicked the ".blocks-hide" link when I visited the webpage previously, and collapse/expand ".example5" accordingly. But heck, I don't know how to use cookies plugin.. Please help me guys. I'm very new to JS. A: Check for blocks-show class after click event(at the end) : Edit : Typo - changed block-show to blocks-show if($('.blocks-hide').hasClass('blocks-show')){ $.cookie('toggleState', 'open'); } else { $.cookie('toggleState', 'close'); } after this, just check for cookie content at $(document).ready() by : if($.cookie('toggleState') == 'open') { $('.example5').show(); } and, since I figured out you haven't configured blocks-hide/blocks-show to appear when they should(when blocks-show is true, there is no category viw, which should be the opposite), a better if-else check would be: if($('.example5').css('display') != 'none){ $.cookie('toggleState', 'open'); } else { $.cookie('toggleState', 'close'); } Use the one checking for CSS property display.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Database transactions in Zend Framework: Are they isolated? Using Zend Framework, I need to (1) read a record from a MySQL database, and (2) immediately write back to that record to indicate that it has been read. I don't want other processes or queries to be able to read from or write to the same record in between steps (1) and (2). I was considering using a transaction for these steps. If I use the following methods, will that fulfil my requirements? Zend_Db_Adapter_Abstract::beginTransaction() Zend_Db_Adapter_Abstract::commit() Zend_Db_Adapter_Abstract::rollBack() A: Presupposing you are using the InnoDB engine for tables that you will issue transactions on: If the requirement is that you first need to read the row and exclusively lock it, before you are going to update it, you should issue a SELECT ... FOR UPDATE query. Something like: $db->beginTransaction(); try { $select = $db->select() ->forUpdate() // <-- here's the magic ->from( array( 'a' => 'yourTable' ), array( 'your', 'column', 'names' ) ) ->where( 'someColumn = ?', $whatever ); $result = $this->_adapter->fetchRow( $select ); /* alter data in $result and update if necessary: */ $db->update( 'yourTable', $result, array( 'someColumn = ?' => $whatever ) ); $db->commit(); } catch( Exception $e ) { $db->rollBack(); } Or simply issue 'raw' SELECT ... FOR UPDATE and UPDATE SQL statements on $db of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Can I get public/private key pair from a key container in smartcard? Can I get the public/private key pair from a key container inside a smartcard using PKCS #11 or CryptoAPI? A: I'm no expert in this, but I think the whole point of a smartcard is that you can't extract the private key. You send the data to the card instead, and let it do the crypto operations on its own processor. A: It depends. Both CryptoAPI (well the CSP for the smart card) and PKCS#11 allows you to have exportable key pairs. However it's common to use non exportable private keys to use the smart card strength to its full potential. So if you're writing an application it becomes your choice. Otherwise someone else already made that choice for you ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7618301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How might I add an attribute with TextBoxWatermarkExtender? How might I approach adding an attribute with a text box which is associated with TextBoxWatermarkExtender (Ajax toolkit) in ASP.NET?
{ "language": "en", "url": "https://stackoverflow.com/questions/7618302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need suggestion in creating android string matching patterns to validate my text fields I have 4 text fields in my android app. Those are Name, email, phone number and password. I want to validate the input fields after user enters the details in text fields. Can anybody help me in writing the string matching patterns (compiled regular expressions) for these 4 text fields. The criteria is as follows * *Name field should contain FirstName and LastName separated with white space. *Email : as simple like normal should contain sometext@sometext.sometext *Phone number : should check for numbers with length 12 numbers *password : should contain only alphanumeric characters and should be of length min 6 and max 8. Please help me in this. I am stuck with my project for this problem. A: Please see this site, they have tons of known regular expressions listed. Also here, and here
{ "language": "en", "url": "https://stackoverflow.com/questions/7618304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving Object to IsolatedStorage in WP7 with XNA 4.0 How can I go about saving an object of type GameSettings to IsolatedStorage on a Windows Phone 7 application made with XNA 4.0? From what I can tell, you can't flag a class as serializable and ByteFormatter isn't available. I haven't come across a good way to convert an object to a byte array and write the array to the storage. And going beyond that, I have no idea how to go about converting said byte array back into an object. Any help would be greatly appreciated! A: There is no built in binary formatter on the platform but it does support XML and JSON serialization using the DataContractSerializer and DataContractJsonSerializer classes. You can configure what is serialized via the DataContract and DataMember attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript change input type dynamically doesnt work on IE8 i have a input field for entering password in a webpage: <input name="txtPassword" type="text" class="input2" id="txtPassword" value="Password" onfocus="txtOnFocus2('txtPassword','Password');" onblur="txtOnBlur2('txtPassword','Password');" /> in the initial state the usershould read "password" as the initial value and when he starts typing a password, the field should change to type password. Also when he sets it back to blank or initial value the field should change type to "text" and show password. I wrote code an got it working on Firefox, Chrome, and safari and its not changing the type to password on IE 8. this is the js code i made by editing an existing function code: function txtOnFocus2(elementId, defaultText) { if (document.getElementById(elementId).value == defaultText) { document.getElementById(elementId).value = ""; document.getElementById(elementId).type = "password"; } } function txtOnBlur2(elementId, defaultText) { var textValue = document.getElementById(elementId).value; if (textValue == defaultText || textValue.length == 0) { document.getElementById(elementId).type = "text"; document.getElementById(elementId).value = defaultText; } } This is working fine in Firefox,chrome and safari but doesn't change field type on IE 8. A: An alternative solution would be to change your approach altogether. The following technique degrades gracefully, is more accessible, and less JavaScript-dependant: HTML <div><label for="email">Email</label> <input type="text" name="email" id="email" /></div> <div><label for="password">Password</label> <input type="password" name="password" id="password" /></div> JavaScript $('input') .focus(function() { $(this).css('background-color', 'white'); }) .blur(function() { if($.trim($(this).val()) == '') { $(this).css('background-color', 'transparent').val(''); } }); CSS input { background-color: transparent; padding: 2px; } label { color: gray; padding: 2px 4px; position: absolute; z-index: -1; } Live demo: http://jsfiddle.net/rjkf4/ A: I tried that before. There is no way to do this in IE. This is an security thing. But still you can set the value of a password input in IE. So you can remove the text input and replace it with a password input and then set the value of new input. function replaceInput(input){ var val = input.value, passwordInput = document.createElement('input'); passwordInput.setAttribute('type', 'password'); passwordInput.value = val; input.parentElement.appendChild(passwordInput); input.parentElement.removeChild(input); }; JSFIDDLE A: Instead of: foo.type = 'password'; try: foo.setAttribute('type', 'password'); More info: http://www.javascriptkit.com/dhtmltutors/domattribute.shtml A: In IE 6 and 7 (at least) you can't change the type of an input that's already in the document. You must create a new input, set its type, then replace the one that's in the document, e.g. var el = document.createElement('input'); el.type = 'password' var oEl = document.getElementById(elementId); el.id = oEl.id; // and so on for other properties that should be copied oEl.parentNode.replaceChild(el, oEl); A: Something ugly that however should work (I don't have IE8 handy to test it) would be placing your field in a div and replacing the whole thing with container.innerHTML = "<input ...>" when needed. A: try this http://www.electrictoolbox.com/jquery-toggle-between-password-text-field/ A: As an option you could just fake having a visible text in the password field by using a background image with that text on it. $(".password").focus(function(){ $(this).css("background-image", 'url(regular_bg.png)') }) $(".password").blur(function(){ if ($(this).val() == ""){ $(this).css("background-image", 'url(bg_with_password_label_on_it.png)') } })
{ "language": "en", "url": "https://stackoverflow.com/questions/7618306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Drag and drop in QML How can I develop drag and drop functionality in QML? I want to drag and drop one image to another. A: At this point in time, you will probably need to use C++, especially if you want to accept drops from outside the QML application (e.g. the user drags a file from a file manager to your app). Here's an example component class to implement a DropArea item: DropArea.h: #ifndef DropArea_H #define DropArea_H #include <QDeclarativeItem> /** An oversimplified prototype Item which accepts any drop that includes data with mime type of text/plain, and just emits the text. */ class DropArea : public QDeclarativeItem { Q_OBJECT Q_PROPERTY(bool acceptingDrops READ isAcceptingDrops WRITE setAcceptingDrops NOTIFY acceptingDropsChanged) public: DropArea(QDeclarativeItem *parent=0); bool isAcceptingDrops() const { return m_accepting; } void setAcceptingDrops(bool accepting); signals: void textDrop(QString text); void acceptingDropsChanged(); protected: void dragEnterEvent(QGraphicsSceneDragDropEvent *event); void dragLeaveEvent(QGraphicsSceneDragDropEvent *event); void dropEvent(QGraphicsSceneDragDropEvent *event); private: bool m_accepting; }; #endif DropArea.cpp: #include <QGraphicsSceneDragDropEvent> #include <QMimeData> #include "DropArea.h" DropArea::DropArea(QDeclarativeItem *parent) : QDeclarativeItem(parent), m_accepting(true) { setAcceptDrops(m_accepting); } void DropArea::dragEnterEvent(QGraphicsSceneDragDropEvent *event) { event->acceptProposedAction(); setCursor(Qt::DragMoveCursor); } void DropArea::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) { unsetCursor(); } void DropArea::dropEvent(QGraphicsSceneDragDropEvent *event) { emit textDrop(event->mimeData()->text()); unsetCursor(); } void DropArea::setAcceptingDrops(bool accepting) { if (accepting == m_accepting) return; m_accepting = accepting; setAcceptDrops(m_accepting); emit acceptingDropsChanged(); } your QML: DropArea { onTextDrop: ... } And you can implement a DragSourceArea similarly. A: I know it's been a while but I struggled so much with this I wanted to share the Qt5 version: Based on ecloud an Michael's example: DropArea.h: #ifndef DropArea_H #define DropArea_H #include <QQuickItem> /** An oversimplified prototype Item which accepts any drop that includes data with mime type of text/plain, and just emits the text. */ class DropArea : public QQuickItem { Q_OBJECT Q_PROPERTY(bool acceptingDrops READ isAcceptingDrops WRITE setAcceptingDrops NOTIFY acceptingDropsChanged) public: DropArea(QQuickItem *parent=0); bool isAcceptingDrops() const { return m_accepting; } void setAcceptingDrops(bool accepting); signals: void textDrop(QString text); void acceptingDropsChanged(); protected: void dragEnterEvent(QDragEnterEvent *event); void dragLeaveEvent(QDragLeaveEvent *event); void dropEvent(QDropEvent *event); private: bool m_accepting; }; #endif DropArea.cpp: #include <QGraphicsSceneDragDropEvent> #include <QMimeData> #include "DropArea.h" DropArea::DropArea(QQuickItem *parent) : QQuickItem (parent), m_accepting(true) { setFlag(QQuickItem::ItemAcceptsDrops, m_accepting); } void DropArea::dragEnterEvent(QDragEnterEvent *event) { event->acceptProposedAction(); } void DropArea::dragLeaveEvent(QDragLeaveEvent *event) { unsetCursor(); } void DropArea::dropEvent(QDropEvent *event) { qDebug() << event->mimeData()->text(); unsetCursor(); } void DropArea::setAcceptingDrops(bool accepting) { if (accepting == m_accepting) return; m_accepting = accepting; setFlag(QQuickItem::ItemAcceptsDrops, m_accepting); emit acceptingDropsChanged(); } Qml: Drop2 { id: myDropArea }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add a object's field in another Object to display it in jsp I am getting a UserList by following List<User> UserList=usersService.findUsers(); than am iterating over this list and based on id getting another object UserActivity, and want UserActivity object's field LastSeen_time. Iterator<User> iterator = UserList.iterator(); while(iterator.hasNext()){ User user= iterator.next() ; System.out.println("userA"+user.getId()); UserActivity userActivity = userActivityService.findUser(user.getId()); System.out.println("userActivity"+userActivity.getLastSeen_time()); } Now i want to pass User and UserActivity.LastSeen_time to a jsp page, where i will display it as User.name User.id UserActivity.LastSeen_Time(corresponding time for each id) How can i do it, Please suggest A: Just put the necessary information in the request scope. For user activities, easiest is to have a Map<Long, UserActivity> userActivities with user ID as key. You can then access it in EL using ${userActivities[user.id]}. E.g. List<User> users = userService.list(); Map<Long, UserActivity> userActivities = new HashMap<Long, UserActivity>(); for (User user : users) { userActivities.put(user.getId(), userActivityService.findByUser(user)); } request.setAttribute("users", users); request.setAttribute("userActivities", userActivities); and then in JSP <table> <tr> <th>User name</th> <th>User ID</th> <th>Last seen time</th> </tr> <c:forEach items="${users}" var="user"> <tr> <td><c:out value="${user.name}" /></td> <td>${user.id}</td> <td><fmt:formatDate value="${userActivities[user.id].lastSeen}" pattern="yyyy-MM-dd HH:mm:ss" /></td> </tr> </c:forEach> </table> (I'm assuming that getLastSeen() returns a Date)
{ "language": "en", "url": "https://stackoverflow.com/questions/7618318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trac plugin to send email number of new and closed tickets and their details based on define schedule I am looking for a way or a plugin so that trac sends me email about the number of new or closed tickets (and some information about these tickets also ) for a specific duration lets say for the last three days. Basically I need to know how many tickets have been created in last week and how many of them have been closed at the end of week. Of course the email only should be sent to the admin and not to all the users. A: For additional Trac funcionality we have Trac plugins, yes. And the first place to look for them is trac-hacks.org . The excellent TagsPlugin in use overthere already delivers some hints on resources tagged with notification or notifications. The most comprehensive and mature solution is certainly TracAnnouncer with a just reworked configuration interface providing a highly sophisticated opt-in and opt-out subscription system. Unfortunately digest notification are not integrated today. Still there are other plugins, that fill in the gap, i.e. check the XMailPlugin. It claims to do configurable instant, daily and weekly notifications, so this may be for you. Since this is a relativly new plugin, you should expect some pending issues, but the author might be very open to your suggestion. If you're becoming a heavy user giving valuable test feedback and a bit lucky too, asking kindly could be enought to make things happen. A: There's a slightly different way to solve this problem that doesn't require any plugins. First, create a custom "timeline" view that displays the information that you want. In your example, this would be all "opened and closed tickets" starting from "today" and going back three days. When viewing this custom view, you should see a link at the bottom of the page that says "RSS Feed" (on my system, the resulting URL looks something like this: http://myserver/timeline?ticket=on&max=50&authors=&daysback=3&format=rss). Click on this link to subscribe to the feed using your web browser, email client, or other program capable of reading feeds. Now, you can view the results live at any time. What you can do at this point is only limited by the capabilities of your feed reader app, but most can at least be configured to notify you when the feed is updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linq self-join query I need some help with Linq self-join. I have the following classs: public class Owner { public string OwnerId {get;set;} public string Name {get;set;} public string Area {get;set;} public string City {get;set;} public string Sex {get;set;} public List<Dog> dog {get;set;} } And table.... ID OwnerId OwnerName TypeId TypeName TypeValue TypeCodeId 1 1 John 1 Area United States 440 2 1 John 2 City Los-Angeles 221 3 1 John 3 Sex Female 122 4 2 Mary 1 Area Mexico 321 4 2 Mary 2 City Cancun 345 ............................................................ I need to parse results of table1 into list of owners the fastest way possible. Note: Type can be null, but I still need to show that owner (So, I assume left join should work). Here's What I do. (owners is a webservice class that contains table1 results) public IEnumerable<Owner> GetOwners() { return (from owner in owners join area in owners into owner_area from oa in owner_area.DefaultIfEmpty() join City in owners into owner_city from oc in owner_city.DefaultIfEmpty() join sex in owners into owner_sex from os in owner_sex.DefaultIfEmpty() where oa.TypeId == 1 && oc.TypeId ==2 && os.TypeId ==3 select new Owner() {OwnerId = owner.OwnerId, Name = owner.Name, Area = oa.TypeValue, City = oc.TypeValue, Sex = os.TypeValue}).Distinct(); } This query has several issues: * *It returns multiple results and distinct does not work as expected *I've tried to use GroupBy but it says that cannot implicitly convert Owner into IEnumerable <int, Owner> *It is super slow How can I get distinct record with self join and improve performance? Thanks UPDATE: Thank you guys for your ansewers, testing now, but I figured out that I forgot to supply one more thing. I've added a new column called TypeCodeId to the table layout(see above) User can filter values based on their selection. So, I have TypeCodeId + TypeValue dictionaries for Area, City and Sex. All of those parameters are optional (If the user didn't select any, I just show them all records. So, Assume that the user has selected filter Area: Unites States and filter City: Los Angeles them my query would look like this: Select Projects where Area equals United States(440) and City equals Los Angeles(221) If Only Area:Mexico was selected then my query would read something like this: Select Projects where Area equals Mexico(321) I'm not sure how to do optional where clauses with what you've provided in the examples. A: Since the table isn't normalized we need to get the distict users from the objects/table. This can be accomplished with: owners.Select(o => new { o.OwnerId, o.OwnerName }).Distinct() And then we need to join the "types" with two matching values, one for the ownerId and another for the specific type. var ownerQuery = from o in owners.Select(o => new { o.OwnerId, o.OwnerName }).Distinct() join area in owners on new { o.OwnerId, TypeId = 1 } equals new { area.OwnerId, area.TypeId } into areas from area in areas.DefaultIfEmpty() join city in owners on new { o.OwnerId, TypeId = 2 } equals new { city.OwnerId, city.TypeId } into cities from city in cities.DefaultIfEmpty() join sex in owners on new { o.OwnerId, TypeId = 3 } equals new { sex.OwnerId, sex.TypeId } into sexes from sex in sexes.DefaultIfEmpty() select new { owner = o, Area = (area != null) ? area.TypeValue : null, City = (city != null) ? city.TypeValue : null, Sex = (sex != null) ? sex.TypeValue : null, }; You may need to change the projection in the above example. A: For best performance if think this is the way to do it. public IEnumerable<Owner> GetOwners(IEnumerable<Tuple<int, int>> filter) { var q = (from o in owners join f in filter on new {o.TypeId, o.TypeCodeId} equals new {TypeId = f.Item1, TypeCodeId = f.Item2} select o).ToList(); var dic = q.ToDictionary (o => new {o.OwnerId, o.TypeId}, o => o.TypeValue); foreach (var o in q.Select(o => new { o.OwnerId, o.OwnerName }).Distinct()) { var owner = new Owner() { OwnerId = o.OwnerId, Name = o.OwnerName }; string lookup; if(dic.TryGetValue(new {o.OwnerId, TypeId = 1}, out lookup)) owner.Area = lookup; if(dic.TryGetValue(new {o.OwnerId, TypeId = 2}, out lookup)) owner.City = lookup; if(dic.TryGetValue(new {o.OwnerId, TypeId = 3}, out lookup)) owner.Sex = lookup; yield return owner; } } To get even a little more performance you can write an IEqualityComparer class that only compares int OwnerId and send it into the Distinct function
{ "language": "en", "url": "https://stackoverflow.com/questions/7618322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery - how to listen for the mouse leaving an area of the screen In the application I'm working on, I use span tags in long paragraphs to provide both: * *A clickable link, handled with Javascript, and *On mouseover, an "edit this" button displayed to the side of the link (with different functionality from the click). Placing and showing the "edit this" button on mouseover is relatively easy. What I'm trying to figure out is, how can I properly hide the button on mouseleave? See my working example: http://jsfiddle.net/nrabinowitz/6uKk8/4/ The problem: * *I can't just use the mouseleave event on the span, because that would hide the button before it can be clicked. *I can't use a transparent div sized to include both the span and the button, because if the div is above the span, it blocks the click event, and if I use the z-index to place the div below the paragraph, it doesn't seem to receive the mouseleave event at all. I could probably cludge something together with mousemove on the entire paragraph, but that seems really ugly. I don't think I can use some kind of coordinated event handling to check mouseleave on both the span and the button, because there's space between them. My desired behavior is to have a (DOM-based or calculated) invisible box that includes both the span and the button, and to listen for the mouse leaving that box, at which time I can hide the button. What's the right way to do this? A: You could put the hiding on a timer and start the timer when the mouse leaves your <span>: var timer = null; $('span.editable').mouseleave(function() { if(timer) clearTimeout(timer); timer = setTimeout(function() { $('#edit-this').hide(); timer = null; }, 2000); }); And then cancel the timer when the mouse enters #edit-this and set up a one-time event handler to hide #edit-this when the mouse leaves it: $('#edit-this').mouseover(function() { if(timer) clearTimeout(timer); timer = null; var $this = $(this); $this.one('mouseleave', function() { $this.hide(); }); }); You'll also want to clear the timer in your mouseover for the span (thanks for catching this): $('span.editable').mouseover(function(e) { if(timer) clearTimeout(timer); timer = null; // ... }); Demo: http://jsfiddle.net/ambiguous/pBtG8/2/ A: If all you want is edit this to show until they mouseout of edit-this, this code will do the trick: $('div.#edit-this').mouseleave(function(){ $('#edit-this').hide(); }); http://jsfiddle.net/MarkKramer/6uKk8/12/ Also, I set it to use the jQuery timers plugin so when you scroll over, a timer will start and if the edit this button isn't scrolled over after two seconds, it will hide itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Enabling button of one form another forms button click I have form1 and form2 running at the same time . The flow is as below 1) Click form1 button 2) disable form1 button 3) show form2 ( form 1 is not closed) 4) click form 2 button 5) close form 2 6) enable form1 button I have done till 5th step . Couldn't do 6th . Can anyone help ? A: You're right - creating another copy of Form1 is not the right way to go. It's not very clear from your question, but it sounds like you want to re-enable the same button that you disabled before opening Form2. In that case, you can listen to Form2's FormClosed event and handle it in Form1: public class Form1 : Form { public void ShowForm2() { myButton.Enabled = false; var f2 = new Form2(); f2.FormClosed += HandleForm2Closed; f2.Show(); } private void HandleForm2Closed(Object sender, FormClosedEventArgs e) { myButton.Enabled = true; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fastest way of getting a character inside a string given the index (PHP) I know of several ways to get a character off a string given the index. <?php $string = 'abcd'; echo $string[2]; echo $string{2}; echo substr($string, 2, 1); ?> I don't know if there are any more ways, if you know of any please don't hesitate to add it. The question is, if I were to choose and repeat a method above a couple of million times, possibly using mt_rand to get the index value, which method would be the most efficient in terms of least memory consumption and fastest speed? A: To arrive at an answer, you'll need to setup a benchmark test rig. Compare all methods over several (hundreds of thousands or millions) iterations on an idle box. Try the built-in microtime function to measure the difference between start and finish. That's your elapsed time. The test should take you all of 2 minutes to write. To save you some effort, I wrote a test. My own test shows that the functional solution (substr) is MUCH slower (expected). The idiomatic PHP ({}) solution is as fast as the index method. They are interchangeable. The ([]) is preferred, as this is the direction where PHP is going regarding string offsets. <?php $string = 'abcd'; $limit = 1000000; $r = array(); // results // PHP idiomatic string index method $s = microtime(true); for ($i = 0; $i < $limit; ++$i) { $c = $string{2}; } $r[] = microtime(true) - $s; echo "\n"; // PHP functional solution $s = microtime(true); for ($i = 0; $i < $limit; ++$i) { $c = substr($string, 2, 1); } $r[] = microtime(true) - $s; echo "\n"; // index method $s = microtime(true); for ($i = 0; $i < $limit; ++$i) { $c = $string[2]; } $r[] = microtime(true) - $s; echo "\n"; // RESULTS foreach ($r as $i => $v) { echo "RESULT ($i): $v \n"; } ?> Results: RESULT (PHP4 & 5 idiomatic braces syntax): 0.19106006622314 RESULT (string slice function): 0.50699090957642 RESULT (*index syntax, the future as the braces are being deprecated *): 0.19102001190186
{ "language": "en", "url": "https://stackoverflow.com/questions/7618333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to implement code for get the xml data and save inot xml file? How to implement code for below xml file <root> <keys> <key> <Question>Is the color of the car</Question> <Ans>black?</Ans> </key> <key> <Question>Is the color of the car</Question> <Ans>black?</Ans> </key> <key> <Question>Is the news paper </Question> <Ans>wallstreet?</Ans> </key> <key> <Question>fragrance odor</Question> <Ans>Lavendor?</Ans> </key> <key> <Question>Is the baggage collector available</Question> <Ans></Ans> </key> </keys> </root> Display on the screen as: List form Is the color of the car black? Check box Is the baggage collector available? Check box If the check box is checked - Yes otherwise value is no. On save button: we need to save it into a xml file. So any one help me to solve the problem. A: By your question it appears you want to fetch contents of XML. For that you need to parse the XML. Create an XMLClass.java public class XMLfunctions { public final static Document XMLfromString(String xml){ Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = db.parse(is); } catch (ParserConfigurationException e) { System.out.println("XML parse error: " + e.getMessage()); return null; } catch (SAXException e) { System.out.println("Wrong XML file structure: " + e.getMessage()); return null; } catch (IOException e) { System.out.println("I/O exeption: " + e.getMessage()); return null; } return doc; } /** Returns element value * @param elem element (it is XML tag) * @return Element value otherwise empty String */ public final static String getElementValue( Node elem ) { Node kid; if( elem != null){ if (elem.hasChildNodes()){ for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){ if( kid.getNodeType() == Node.TEXT_NODE ){ return kid.getNodeValue(); } } } } return ""; } public static String getXML(int s, int y){ String line = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); String link = "//YOUR URL HERE" add LIMITS IF ANY for ex: String link = "www.ab.com/index.php?action=gq&start="+s+"&limit="+y; // it will give you values from 1 to 10 or 1 to 50 whatever you mention HttpPost httpPost = new HttpPost(link); System.out.println("Httppost="+httpPost); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); System.out.println("HttpEntity="+httpEntity); line = EntityUtils.toString(httpEntity); System.out.println("Line="+line); } catch (UnsupportedEncodingException e) { line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; } catch (MalformedURLException e) { line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; } catch (IOException e) { line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; } return line; } Then in other class call this getXML function declare int s and int y with some value String xmls = XMLfunctions2.getXML(loginid); Document docs = XMLfunctions2.XMLfromString(xmls); NodeList node = docs.getElementsByTagName("start"); for (int i = 0; i < node.getLength(); i++) { org.w3c.dom.Element e = (org.w3c.dom.Element)node.item(i); if(i==0) { quest= XMLfunctions.getValue(e, "Question"); ans=XMLfunctions.getValue(e, "Answer"); key=XMLfunctions.getValue(e, "key"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: asyncsocket accepts socket but doesn't connect to host I've just started running (what I thought was) a basic asyncsocket in my objective-c app and I'm getting the didAcceptNewSocket: message when connecting with telnet, but then I'm abruptly disconnected ("Connection closed by foreign host") without reaching the didConnectToHost: message. It works fine in the example and I've tried to replicate everything I see there to no avail. Is there some simple pitfall I should be avoiding? Any other way I can debug this problem? A: In this case, I was using the wrong delegate methods copied/pasted from some other site. Always check your headers!
{ "language": "en", "url": "https://stackoverflow.com/questions/7618337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to figure out regex pattern I have a string with some custom formula like FVAL("A")+FVAL(B). I want to figure out all string inside FVAL() which does not have quotes around it. So basically I want to extract out B because it does not have quotes around it. A: Use FVAL\(([^")]*)\) This matches FVAL(, followed by any number of characters except quotes or closing parentheses, followed by ). Another possibility (where the match would be in $0 instead of $1: (?<=FVAL\()[^")]*(?=\)) This matches a non-quote/non-parenthesis-string that is surrounded by FVAL( and ). In VB.net: Dim RegexObj As New Regex("FVAL\(([^"")]*)\)", RegexOptions.IgnoreCase) Dim MatchResult As Match = RegexObj.Match(SubjectString) While MatchResult.Success ResultList.Add(MatchResult.Groups(1).Value) MatchResult = MatchResult.NextMatch() End While or Dim RegexObj As New Regex("(?<=FVAL\()[^"")]*(?=\))", RegexOptions.IgnoreCase) Dim MatchResult As Match = RegexObj.Match(SubjectString) While MatchResult.Success ResultList.Add(MatchResult.Value) MatchResult = MatchResult.NextMatch() End While A: You'll want an expression something like "FVAL\\(([^\"]+)\\)" which includes a set of parentheses for the capture group.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make a JTable row to an "unselected" state after selected any row in that table? I'm developing a Java Swing application which contains a JTable. By default, while launching the application for the first time, the call to the method jtable.getSelectedRow() or jtable.getSelectedColumn() returns -1, which means that no row selected at that moment. After user clicked any row or column, the call to the method jtable.getSelectedRow() or jtable.getSelectedColumn() returns the appropriate values of selected rows & columns. What I actually need is that I want to set the selected row or column to -1 i.e. "no row or column selected state". How can I do this? A: The JTable method clearSelection will do what you want -- clear the selection of all the table's selected rows and columns. The JTable API is the place to look for methods such as these.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: jQueryUI range slider showing progress I have a range: true slider and want to show progress like the progress bar between the two handles of the slider. Kind of like this, http://jsfiddle.net/cG8qB/, except this will be happening in between the two handles of my slider instead of the whole slider like in that example and I only need the color updating instead of a slider handle. So basically, I want to change the color of the part in between the two slider handles to something like the behavior of a range: min slider where the "min" is the left handle of my slider and the handle of this range: min slider is hidden. A: You can simply hide the handle by add the following css rule: .ui-slider-handle { display: none } Then you may want to disable the slider to prevent it from being changed by the user, i.e. adding disabled: true to the initiation. See this in action: http://jsfiddle.net/william/cG8qB/8/. A: Turns out the answer was in the original jsfiddle the whole time This does the trick. $("#slider").find('.ui-widget-header').css('width', x + '%'); This also works. $("#slider div").css('width', x + '%');
{ "language": "en", "url": "https://stackoverflow.com/questions/7618347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to override superclass' s NSNotificationCenter listener method? Say I have superclass which listens to a notification: @implementation SuperClass - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo:) name:@"bar" object:nil]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:self name:@"bar" object:nil]; } - (void)foo:(NSNotification *)notification { //do something } Now in a subclass, I want to do something different with that notification. The first thing I tried is to override foo: @implementation SubClass - (void)foo:(NSNotification *)notification { //do something different } This does not work since the listening selector still points to superclass's method. Then I tried to remove superclass's listener and add from subclass: @implementation SubClass - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:(SuperClass *)self name:@"bar" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo2:) name:@"bar" object:nil]; } - (void)foo2:(NSNotification *)notification { //do something different } This doesn't work either, with or without cast/override. The notification event is still handled by superclass. I'm not sure how NSNotificationCenter handles observers from same address but of different pointer type. And I don't want to touch superclass. Can anyone please help? A: Would this work? [[NSNotificationCenter defaultCenter] removeObserver:[self superclass] name:@"bar" object:nil]; A: Close this question by answering myself. The problem description should have stated clearly how NSNotificationCenter works with subclasses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PhoneGap Android Plugin: ContactView error I'm using PhoneGap + jQuery Mobile for a new mobile app. This plugin is used to call native contact view of Android so you don't have to inject contacts in HTML. https://github.com/phonegap/phonegap-plugins/tree/master/Android/ContactView I've followed the instructions properly but it doesn't work for me, whenever I try to run (after all the initialization routine) this JS on Android: window.plugins.contactView.show( function(contact) { console.log(contact); }, function(fail) { console.log(fail); } ); It shows this error: Error: Status=2 Message=Class not found Can anyone help? Note: I haven't used any PhoneGap plugin before. A: http://simonmacdonald.blogspot.com/2011/05/installing-childbrowser-plugin-on.html The issue has been described here in details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get height and Width attribute with php? <img src="......" width="....." height="...."/> If I have a function generating the above code, how can I get the width and height attributes with php? A: You can use getimagesize() <?php list($width, $height, $type, $attr) = getimagesize("http://example.com/image.gif"); ?> <img src="..." width="<?= $width ?> height="<?= $height ?>" /> A: Do you mean something like this ? So you would need to use preg_match_all('/(alt|title|src)=("[^"]*")/i',$img_tag, $img[$img_tag]); And then foreach them to array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: dynamically loading different layouts of choice into another layout I'll get to the point. I have this class in its own file, DynamicMapLoader.java: public class DynamicMapLoader extends Activity{ public void Load(int mapInt) { int mapArr[] = { R.id.map1, R.id.map2 //TODO:expand }; int mapToLoad = mapArr[mapInt]; FrameLayout flContainer = (FrameLayout) findViewById(R.id.frameLayout3); LinearLayout flContent = (LinearLayout) findViewById(mapToLoad); flContainer.addView(flContent); } } I have this code, calling DynamicMapLoader in the main activity: DynamicMapLoader ml = new DynamicMapLoader(); ml.Load(0); frameLayout3 is in the main.xml: <FrameLayout android:layout_width="wrap_content" android:id="@+id/frameLayout3" android:layout_below="@+id/editText1" android:layout_alignParentLeft="true" android:layout_height="350dp"> </FrameLayout> and map1 is the parent LinearLayout in its own .xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map1" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <HorizontalScrollView android:id="@+id/scrollView1" android:layout_height="match_parent" android:layout_width="match_parent"> <LinearLayout android:orientation="horizontal" android:layout_height="match_parent" android:layout_width="match_parent"> <ImageView android:id="@+id/imageView1" android:src="@drawable/map_1_road" android:layout_width="wrap_content" android:layout_height="match_parent" /> <ImageView android:id="@+id/imageView2" android:src="@drawable/map_1_road" android:layout_width="wrap_content" android:layout_height="match_parent" /> </LinearLayout> </HorizontalScrollView> </LinearLayout> when i start it in my AVD, LogCat shows a FATAL EXCEPTION: main and points to ml.Load(0); in the main activity, as shown below: 10-01 06:20:36.891: ERROR/AndroidRuntime(992): FATAL EXCEPTION: main 10-01 06:20:36.891: ERROR/AndroidRuntime(992): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cep/com.cep.MapricotActivity}: java.lang.NullPointerException 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.os.Handler.dispatchMessage(Handler.java:99) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.os.Looper.loop(Looper.java:123) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.app.ActivityThread.main(ActivityThread.java:3683) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at java.lang.reflect.Method.invokeNative(Native Method) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at java.lang.reflect.Method.invoke(Method.java:507) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at dalvik.system.NativeStart.main(Native Method) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): Caused by: java.lang.NullPointerException 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.app.Activity.findViewById(Activity.java:1647) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at com.cep.DynamicMapLoader.Load(DynamicMapLoader.java:31) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at com.cep.MapricotActivity.onCreate(MapricotActivity.java:207) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 10-01 06:20:36.891: ERROR/AndroidRuntime(992): ... 11 more Any suggestions? Thanks in advance. A: You have to setContentView(R.Layout. the layout file ) before calling findViewByID() Or inflate the layout to a view and then view.findViewByID() to get the desired view A: instead of int mapArray[]... try Integer mapArray[]... Also please post the full output under FATAL EXCEPTION: main so that we may see what went wrong at a more detailed level
{ "language": "en", "url": "https://stackoverflow.com/questions/7618359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selecting exercises that include the same muscles as the specified exercise (two tables) two tables: Exercises --------- Exercise ID 1 ExerciseTargettedMuscles ------------------------ exerciseID muscleID 1 10 1 20 1 30 I need to grab exercises that include all of the muscles it targets. so, if exercise a has exerciseID=1 and has muscleIDs=10,20, and 30, then the result of the query should be exercises with (at least) muscleIDs=10,20, and 30. What confuses me is the multiple-to-multiple row comparing. The way that works in my head is to just make sure that there doesn't exist a muscle in the main exercise that is not present in the selected exercise(s). How do you loop through every one to see if it is not in the selected exercise? A: Using HAVING to filter your results to only include those with at least the desired muscles: select exerciseID from ExerciseTargettedMuscles where muscleID in (10, 20, 30) group by exerciseID having count(muscleID) = 3 The 3 should match the number of muscles. The WHERE gives you the exercises that have any of the desired muscles. Then they are grouped into one group for each exercise. Finally the HAVING is used to include only those groups that have all (rather than just some) the muscles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't load xml within jquery submit function with Firefox, Ok with Chrome The following works on Chrome but not Firefox ... $('#foo').submit(function () { $.get('externals/xml/college.xml', function(d){ With firebug I can see the Get but it does not return any response and is highlighted red with a red X. There are no other console error messages. I open the same file on document ready so the submit results in a re-read of the xml. The initial .get at document ready works with all browsers. Any thoughts on what could be causing this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7618367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with ModalPopup in asp.net/C# I have used modalpopup control in my web application and after open it when i click on ok button i have make call to WCF function to deal with some functional requirement. Currently the behavior like , when i will click on OK button ModalPopup remained open until my WCF operation is completed and when it will completed it will be closed because i write down logic to hide in code behind file and my code as per below <asp:Panel ID="PanelCheck" runat="server" CssClass="modalPopup" SkinID="Custom"> *Panel content here..* <asp:Button ID="OkButton" runat="server" Text="Create" OnClientClick="return ValidateSeconds();" OnClick="OkButton_Click" /> </asp:Panel> <cc1:modalpopupextender id="MPE" runat="server" targetcontrolid="lnkTemp" popupcontrolid="PanelCheck" backgroundcssclass="modalBackground" /> code behind protected void OkButton_Click(object sender, EventArgs e) { if (Page.IsValid) { try { MPE.Hide(); *Logic to deal with WCF call..* } } catch (Exception ex) { throw ex; } timerInstance.Enabled = true; } } Now what i require is i need to close modalpopup first and then asynchronously it should make WCF call I could not find any ways to do that, please anyone help me if this question make any sense. Thanks in Advance A: I believe you can hide ModalPopupExtender on the client side right after clicking the “Create” button: <asp:Button ... OnClientClick="return ValidateSeconds();" /> function ValidateSeconds() { //your code $find('MPE').hide(); //your code } See Also: How to Show / Hide a ModalPopupExtender using Javascript
{ "language": "en", "url": "https://stackoverflow.com/questions/7618369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bresenham's circle algorithm I have the following code for drawing a circle : #include<stdio.h> #include<conio.h> #include<graphics.h> #include<math.h> void main() { int xc, yc, x, y, p[100], r, k; int gdriver=DETECT, gmode, errorcode; printf("\nEnter the center point(xc,yc): "); scanf("%d%d", &xc, &yc); printf("\nEnter the radius: "); scanf("%d", &r); printf("\nPlotting...\n"); sleep(5); clrscr(); initgraph(&gdriver, &gmode, ""); p[0]=1-r; x=0; y=r; for(k=0;k<=y;k++) { putpixel(xc+x, yc+y, 9); putpixel(xc-x, yc-y, 9); putpixel(xc+x, yc-y, 9); putpixel(xc-x, yc+y, 9); putpixel(xc+y, yc+x, 9); putpixel(xc-y, yc-x, 9); putpixel(xc+y, yc-x, 9); putpixel(xc-y, yc+x, 9); if(p[k]>0) { p[k+1]= p[k]+ 2*(x+1)+1-2*(y+1); x++; y--; } else { p[k+1]=p[k]+2*(x+1)+1; x++; } } getch(); } This part of code : putpixel(xc+x, yc+y, 9); putpixel(xc-x, yc-y, 9); putpixel(xc+x, yc-y, 9); putpixel(xc-x, yc+y, 9); putpixel(xc+y, yc+x, 9); putpixel(xc-y, yc-x, 9); putpixel(xc+y, yc-x, 9); putpixel(xc-y, yc+x, 9); Is mainly for plotting the points with respect to the circle, and it works because of the symmetric property of circle. But I couldn't figure out what this part of code is exactly doing ; if(p[k]>0) { p[k+1]= p[k]+ 2*(x+1)+1-2*(y+1); x++; y--; } else { p[k+1]=p[k]+2*(x+1)+1; x++; } Can anyone explain me what it does? Thanks in advance. A: The update formulae look a little weird, and I will give what I think are the correct steps below: You are starting from the topmost point in the circle and rotating clockwise until the angle reaches 45 degrees. Now, the points on the circle roughly satisfy (x^2 + y^2 = r^2). The idea is to draw one pixel at a time, moving in the positive x direction. If you find that the next point (without shifting down) is too far from the center of the circle, then that point should be drawn one unit lower. For example, if you look at pixellated circles, you will see that they can be essentially broken down into a series of horizontal lines and pixels. Each end of the horizontal line marks a point where extending the line would be too far from the circle, and hence you see a drop. Note that there is some element of discretion here regarding which points you choose. There are 3 circle drawing disciplines: * *Inner circle: Choose points such that no point is drawn outside of the circle (so that x^2 + y^2 < (r+1)^2 for each point r -- note that its r+1 here and not r) *Outer circle: Choose points such that no point is drawn inside of the circle (so that x^2 + y^2 > (r-1)^2 for each point r -- note that its r-1 here and not r) *Middle circle: Choose points that minimize abs(x^2 + y^2 - r^2). You can choose any of these disciplines in the algorithm. The methods are identical except for that code block (and the changes there are minor). In each case, you have to calculate how far each point deviates from the circle. This requires knowing x^2 + (y-1)^2 - r^2. Let's call that sequence p[k]. If x^2 + (y-1)^2 - r^2 <= 0, then moving down would show the point too close to the center of the circle, so the next point should be (x+1, y). In that circumstance, then the next deviation will be: p[k+1] = (x+1)^2 + (y-1)^2 - r^2 = x^2 + (y-1)^2 - r^2 + 2x + 1 = p[k] + 2*(x + 1) - 1 If x^2 + y^2 - r^2 > 0, then the next point should be (x+1,y-1), so that p[k+1] = (x+1)^2 + (y-2)^2 - r^2 = x^2 + (y-1)^2 - r^2 + 2x + 1 - 2y + 3 = q[k] + 2*(x + 1) - 2*(y - 1) = p[k] + 2*(x+1) - 2 * (y + 1) These formulae change based on whether you are interested in finding the outer circle (pixels are never too close), inner circle (pixels are never too far), or center circle (roughly in line), but this is the essential idea. A: The section of the program that you are asking about is the core of the circle drawing algorithm, and it computes the x, y coordinates for one octant of the circle (the eight putpixel() calls mirror this octant into the other seven to complete the circle). The algorithm is explained in detail in this article.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Initializing array of pointers I have a Deck object (deck of cards) which is a double-ended queue implemented as a doubly-linked list. I would like to be able to shuffle the queue at will, but the way I would go about it is beyond me. So instead I've opted to pre-shuffle an array a pointers to the cards and enqueue them after the fact. Problem is, the code I have now doesn't seem to be initializing the pointers at all. void BuildDeck(Deck* deck) { Card** cards = new Card*[20]; const size_t MAX_INTEGER_LENGTH = sizeof(int) * 4; char szPostfix[] = "_Card.bmp"; for(int i = 1; i < 21; i++) { char path[MAX_INTEGER_LENGTH + sizeof(szPostfix) + 1]; sprintf(path,"%d%s",i, szPostfix); cards[i-1] = new Card(i,path); } ShuffleArray(cards); for (int i = 0; i < 20; i++) { deck->PushTop(cards[i]); } } void Swap(Card* a, Card* b) { Card temp = *a; *a = *b; *b = temp; } void ShuffleArray(Card** cardArray) { srand(dbTimer()); for (int i = 0; i < 20; i++) Swap(cardArray[i],cardArray[rand()%20]); } I think where I screwed up is in the card[i] = new Card(...) line, but it somehow looks right to me. Any suggestions would be appreciated. DISCLAIMER: I know I should be using the standard library for most of this stuff, but I'm trying to teach myself the hard stuff first. It's just the way I learn. EDIT: I fixed the index problem. Now I've just gotta figure out why some image aren't drawing now... :/ Thanks for the help! A: In the first for loop your starting index is 0, while in the second for loop the starting index is 0. That could be the problem. A: Your code has many problems * *You are looping with 1 <= i <= 20 but for an array of 20 elements indexing goes from 0 <= index <= 19. You need to use cards[i-1] = new Card(i,path); *You are allocating the array of pointers cards but you are not deallocating it (memory leak). Either deallocate it with delete[] cards; once you are done or just use a stack based array with Card *cards[20]; instead of allocating it with new. *The way you compute MAX_INTEGER_LENGTH shows you don't really understand what sizeof does. *This is the reason for which the cards don't get shuffled. You wrote a function that swaps two pointers, but the pointers it is swapping are local variables (parameters) of the function, not the elements of the array. One solution is to pass the parameters as pointer references by declaring swap with void Swap(Card *& a, Card *& b), another solution would be passing pointers to pointers (but this would require a more complex syntax of the implementation because of the double indirection and would also require a change in the way you call the function). A: Your code: for(int i = 1; i < 21; i++) { char path[MAX_INTEGER_LENGTH + sizeof(szPostfix) + 1]; sprintf(path,"%d%s",i, szPostfix); cards[i] = new Card(i,path); } Here the loop should start from 0 to 20 as: for(int i = 1 ; i < 21; i++) //incorrect - original code for(int i = 0 ; i < 20; i++) //correct - fix And after the fix, you could use i+1 instead of i in : sprintf(path,"%d%s",i+1, szPostfix); cards[i] = new Card(i+1,path); if that is required.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nested curly brackets {{ }} in WPF/XAML What is the meaning of nested curly brackets in attribute values in WPF/XAML markup? As in the following example: <ListBox ItemsSource="{Binding Source={StaticResource pictures}}"> A: That binds the ItemsSource of the list box to a StaticResource called pictures. It's simply nesting one markup extension in another. Read about markup extensions in XAML here: http://msdn.microsoft.com/en-us/library/ms747254.aspx A: Nesting of multiple markup extensions is supported by WPF, and each markup extension will be evaluated deepest first. <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" /> In this usage, the x:Static statement is evaluated first and returns a string. That string is then used as the argument for DynamicResource. so here <ListBox ItemsSource="{Binding Source={StaticResource pictures}}"> it will assign the pictures (may be collection) to the itemsource of the listbox please have look at this http://msdn.microsoft.com/en-us/library/ms747254.aspx#Nesting
{ "language": "en", "url": "https://stackoverflow.com/questions/7618376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How am I able to pass a var into MeCab for Python? The code is: import MeCab m = MeCab.Tagger("-O wakati") text = raw_input("Enter Japanese here: ") print m.parse(text) The problem is that after entering the string into the raw_input it gives an error in IDLE: Traceback (most recent call last): File "C:\Users\---\Desktop\---\Python\japanesetest.py", line 5, in <module> print m.parse(text) File "C:\Users\---\Desktop\---\Python\lib\site-packages\MeCab.py", line 220... def parse(self, *args): return _MeCab.Tagger_parse(self, *args) TypeError: in method 'Tagger_parse', argument 2 of type 'char const *' If I do this however: import MeCab m = MeCab.Tagger("-O wakati") print m.parse('なるほど、マルコフ辞書のキーはタプルにしたほうがスッキリしますね。') I get the proper result: なるほど 、 マルコフ 辞書 の キー は タプル に し た ほう が スッキリ し ます ね 。 Things I have tried are unicode tags at the beginning, writing to a textfile in unicode and parsing the text, and a few other million things. I'm running Python 2.7 and MeCab 0.98. If this can't be answer, even a little light shed on the error would be appreciated. A: I am able to run your snippet successfully using Python 2.7 and MeCab 0.98 in both IDLE and IPython command line. import MeCab m = MeCab.Tagger("-O wakati") text = raw_input("Enter Japanese here: ") Enter Japanese here: 私の車はとても高いです。 print m.parse(text) 私 の 車 は とても 高い です 。 However, when reading from a UTF file I will get errors when trying to parse the text. For those cases I explicitly encode the text to shift-jis. You might try this technique. Below is an example. rawtext = open("UTF.file", "rb").read() tagger = MeCab.Tagger() encoded_text = rawtext.encode('shift-jis', errors='ignore') print tagger.parse(encoded_text).decode('shift-jis', errors='ignore') A: This is my current workaround, and should help people coming across the same issue: import MeCab import codecs write_to = codecs.open("pholder.txt", "w", "utf-8") text = raw_input("Please insert Japanese text here: ") write_to.write(text) write_to.close() read_from = open('pholder.txt').read() mecab = MeCab.Tagger("-Owakati") print mecab.parse(read_from) The deal-breaker here is adding .read() to the open func. Why? Maybe you can tell me. :/
{ "language": "en", "url": "https://stackoverflow.com/questions/7618379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I prevent focus stealing, but still get focus when returning to my app using Alt+Tab? Following MS guidelines, my WPF application's App constructor includes the following code for proper focus behavior: HwndSource.DefaultAcquireHwndFocusInMenuMode = false; Keyboard.DefaultRestoreFocusMode = RestoreFocusMode.None; As explained in this article, these settings prevent focus stealing. However, setting DefaultRestoreFocusMode to None has a bad side effect. When using Alt+Tab to leave a WPF application and then return to it, the WPF application doesn't get focus. However, if I don't set DefaultRestoreFocusMode to none, it does get focus as expected. Is there a way to prevent focus stealing but have focus still set when returning to a WPF application via Alt+Tab? -Craig A: I prevent my wpf window from getting focus by doing the below and i can still activate it by using ALT-TAB or clicking on it's taskbar item. Here you change the window styles on your window so that it has no activate. var yourWindow = new YourWindowType(); //set the windowstyle to noactivate so the window doesn't get focus yourWindow.SourceInitialized += (s, e) => { var interopHelper = new WindowInteropHelper(yourWindow); int exStyle = User32.GetWindowLong(interopHelper.Handle, (int)WindowLongFlags.GWL_EXSTYLE); User32.SetWindowLong(interopHelper.Handle, (int)WindowLongFlags.GWL_EXSTYLE, exStyle | (int)WindowStylesEx.WS_EX_NOACTIVATE); //If you have trouble typing into your form's textboxes then do this ElementHost.EnableModelessKeyboardInterop(yourWindow); }; This is something i added as an extra precaution, plus it lets you drag your window around if it is borderless: private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { //don't activate the window when you click on it. case WindowMessage.WM_MOUSEACTIVATE: handled = true; return (IntPtr)MouseActivate.MA_NOACTIVATE; //For Borderless Windows: occurs while dragging. it reports new position before it has been finalized. //otherwise you wont see the window moving while you're dragging it case WindowMessage.WM_MOVING: RECT rect = (RECT)Marshal.PtrToStructure(lParam, typeof(RECT)); User32.SetWindowPos(new WindowInteropHelper(this).Handle, Hwnd.HWND_TOPMOST, rect.Left, rect.Top, rect.Width, rect.Height, SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOSIZE); break; } return IntPtr.Zero; } These add a hook so that WndProc is actually called in WPF: private void Window_Loaded(object sender, RoutedEventArgs e) { HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); if (source == null) return; source.AddHook(WndProc); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); if (source == null) return; source.RemoveHook(WndProc); } Just an FYI.. this still works even though you don't get focus: private void WpfPillForm_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { this.DragMove(); } Here's the Win32 API declarations so you don't have to look them up: [StructLayout(LayoutKind.Sequential)] public struct WINDOWPOS { public IntPtr hwnd; public IntPtr hwndInsertAfter; public int x; public int y; public int cx; public int cy; public int flags; } [StructLayout(LayoutKind.Sequential)] struct RECT { public int left, top, right, bottom; } public static class MouseActivate { public const int MA_ACTIVATE = 1; public const int MA_ACTIVATEANDEAT = 2; public const int MA_NOACTIVATE = 3; public const int MA_NOACTIVATEANDEAT = 4; } public enum WindowLongFlags : int { GWL_EXSTYLE = -20, GWLP_HINSTANCE = -6, GWLP_HWNDPARENT = -8, GWL_ID = -12, GWL_STYLE = -16, GWL_USERDATA = -21, GWL_WNDPROC = -4, DWLP_USER = 0x8, DWLP_MSGRESULT = 0x0, DWLP_DLGPROC = 0x4 } public const int WM_MOVING = 0x0216; public const uint WS_EX_NOACTIVATE = 0x08000000, [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int GetWindowLong(IntPtr hwnd, int index);
{ "language": "en", "url": "https://stackoverflow.com/questions/7618395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how to stop infinite loop threads from android service? i am working with threads in sample application.In my application i have used 3 threads are running in infinite loop.These 3 threads are used in android service class.when i am starting these threads then the threads are running and UI is not allowing until completion of infinite loop.but how can i stop the threads and how can i handle UI? i have written a service class as follows: ServiceApp.java public class ServiceApp extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); while(true) { Thread child1=new Thread(new Runnable() { @Override public void run() { try { function1(); } catch (InterruptedException e) { e.printStackTrace(); } } }); child1.start(); Thread child2=new Thread(new Runnable() { @Override public void run() { try { function2(); } catch (InterruptedException e) { e.printStackTrace(); } } }); child2.start(); Thread child3=new Thread(new Runnable() { @Override public void run() { try { function3(); } catch (InterruptedException e) { e.printStackTrace(); } } }); child3.start(); Toast.makeText(ServiceApp.this, "All threads started", Toast.LENGTH_SHORT).show(); } } public void function1() throws InterruptedException { Generic generic=new Generic(); //this for connect to web services String add=generic.getAdd(10,20); Log.v("function1", "addition from service"+add); Thread.sleep(1000); } public void function2() throws InterruptedException { Generic generic=new Generic(); //this for connect to web services String sub=generic.getSub(34,20); Log.v("function2", "subtraction from service"+sub); Thread.sleep(1000); } public void function3() throws InterruptedException { Generic generic=new Generic(); //this for connect to web services String mul=generic.getMul(4, 6); Log.v("function3", "multipicationn from service"+mul); Thread.sleep(1000); } } how can i stop child1,child2,child3 threads from activity class? please any body help me? A: Service.onCreate() is executed inside the UI thread. You have an infinite loop there, that continuously creates more and more threads, so UI doesn't get a chance to respond to user's actions. If you actually intend to have so many threads, you need to create another thread that would start the original three. Activity can communicate with the service either via Binder (you'll need to return an actual implementation instead of null there) or by sending intents, which you can capture and process in Service.onStart()
{ "language": "en", "url": "https://stackoverflow.com/questions/7618397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to: Override Metadata for a Dependency Property how to override default dependency property metadata. for example ;Text property for textbox. i use this code class UCTextBox : TextBox { public UCTextBox() { var defaultMetadata = TextBox.TextProperty.GetMetadata(typeof(TextBox)); TextBox.TextProperty.OverrideMetadata(typeof(UCTextBox), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, defaultMetadata.PropertyChangedCallback, new CoerceValueCallback(CoerceText) )); } private static object CoerceText(DependencyObject d, object value) { return value.ToString().Replace(",",""); } but this In both runs(get,set) No one can help me!!!:((( A: Here is an example of a class derived from TextBox overriding the metadata for the Text property: using System.Windows; using System.Windows.Controls; using System.Windows.Data; public class MyTextBox : TextBox { static MyTextBox() { TextBox.TextProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, null, /* property changed callback */ null, /* coerce value callback */ true, /* is animation prohibited */ UpdateSourceTrigger.LostFocus)); } } Notice that the override is place in the static constructor, not the ordinary constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: java.lang.UnsatisfiedLinkError in HDFView Whenever HDFView opens an hdf file which is created by a user or by an application, it shows the following error (I am using Red Hat linux). java.lang.UnsatisfiedLinkError: /dwr2/com/lib/libjhdf.so: /lib/tls/libc.so.6: version `GLIBC_2.4' not found (required by /dwr2/com/lib/libjhdf.so) at java.lang.ClassLoader$NativeLibrary.load(Native Method) at java.lang.ClassLoader.loadLibrary0(Unknown Source) at java.lang.ClassLoader.loadLibrary(Unknown Source) at java.lang.Runtime.loadLibrary0(Unknown Source) at java.lang.System.loadLibrary(Unknown Source) at ncsa.hdf.hdflib.HDFLibrary.<clinit>(HDFLibrary.java:245) at ncsa.hdf.object.h4.H4File.isThisType(H4File.java:170) at ncsa.hdf.view.DefaultTreeView.openFile(DefaultTreeView.java:1328) at ncsa.hdf.view.HDFView.actionPerformed(HDFView.java:1016) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour ce) at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) A: Looks like you are missing a SO file, perhaps you have the wrong binary or a broken symlink, also take a look at: http://www.unidata.ucar.edu/support/help/MailArchives/gempak/msg05278.html This might be related to your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Comments Moderation I've successfully added a comment box as described at the social plugins page: I also included the following metatags: <meta content='XXX' property='fb:app_id'/> <meta content='YYY' property='fb:admins'/> <meta content="YYY" property="fb:moderator"/> Nothing seems to make a difference! EDIT: yes, the values are ok, I had the older version and everything used to work. Thanks! A: Is it just broken in IE? If so, maybe you forgot to add the fb namespace to your html tag: <html xmlns:fb="http://www.facebook.com/2008/fbml">
{ "language": "en", "url": "https://stackoverflow.com/questions/7618408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: set list view adapter in a fragment in android I want a custom row, so I am using a List View in an xml and inflating into a fragment. I am very confused of how to set the adapter for the list View. I created a new adapter which extends Base Adapter. In the getView method, I really don't know what context to pass while inflating the row.xml layout. How do I set the adapter for the list view and where? public class ResultsFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.results_layout, container, false); listView = (ListView)v.findViewById(R.id.results); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); loadPage(dataBean.getWhat(), dataBean.getWhere(), dataBean.getPageStart()); //resultsAdapter.setRssData(rssData); //setListAdapter(resultsAdapter); } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); Context context = getActivity().getApplicationContext(); resultsAdapter = new ResultsAdapter(context); } /** * Set List Adapter */ private void setAdapter(){ if(listView.getAdapter() == null){ listView.setAdapter(resultsAdapter); } else{ resultsAdapter.notifyDataSetChanged(); } } } A: You must extend Listfragment (instead of Fragment), and using its ListFragment.setListAdapter to set your adapter. In the adapter getView() inflate your row.. that s all A: If you do not want to change your extended class, you should use listview.setAdapter(...) method. As you see in my example : ListView productList= (ListView) getActivity().findViewById(R.id.product_list); SampleAdapter adapter = new SampleAdapter(getActivity()); adapter.add(new SampleItem( "Sunny LCD TV 2\" SN022L66-T1 Full HD", R.drawable.product_sample_pic); productList.setAdapter(adapter);
{ "language": "en", "url": "https://stackoverflow.com/questions/7618409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: An array for data of dropdown menu There are some ideas for creating a dropdown menu from data populated from xml or json. But how can I do this purely with php? A possible method is to create a multi-level array. But what is the best way to create it from mysql data (having parent id for sub-menus), and how to effectively read the array (via a foreach loop?)? A: for php side, lets assume you retrieve using that query what is in the table in an array of format: $menu = array( 'page/1' => 'about', 'page/2' => 'photos', 'menu-title' => array('page/4' => 'sub-menu-1','page/5' => 'sub-menu-2') ); echo '<ul>'; foreach($menu as $key => $value){ if(is_string($value)){ echo '<li><a href="'.$key.'">'.$value.'</a></li>'; } if(is_array($value)){ echo '<ul>'; echo '<li><a href="#">'.key($value).'</a></li>'; foreach($value as $sub_key => $sub_value){ echo '<li><a href="'.$sub_key .'">'.$sub_value.'</a></li>'; } echo '</ul>'; } } echo '</ul>'; for mysql database, have a column of "parent_id" if it is null then it would be a root level, other than that, it would be a sub there, another column of "path" and "title,you can add a "weight" column as well to order them. NOTE: this is untested code A: I like to loop through the rows that are pulled from mysql and create an array where the key is the value for the input and the value is the text. So, if you wanted to create a dropdown like: <input value="UT">Utah</input> <input value="VT">Vermont</input> <input value="NV">Nevada</input> <input value="CA">California</input> I would create an array that looked like this: array( "UT" => "Utah", "VT" => "Vermont", "NV" => "Nevada", "CA" => "California", ) It's very easy to translate the array into the html using a foreach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Object-Oriented JS - without global variables? I am taking an object-oriented approach to building a Javascript app. For starters, I am creating a Game object and a Timer object. Here's my current implementation: The Timer object has the following methods: setTimerValue() start() stop() getTimeLeft() timeExpired() The Game object has the following methods: reset() run() ... Timer.start() uses window.setInterval() to start the countdown. When the countdown gets to zero, it calls Timer.timeExpired(). Timer.timeExpired() announces that the game is over and should call Game.reset() and Game.run() to restart the game. But how can this be done when the Timer object doesn't know anything about the Game object? Does the Game object need to be a global variable for this to work? Also, the Game object currently has a Timer object as one of its properties. This allows the Game object to call the Timer methods. But unclear on how Timer methods can call the Game object. I have a nagging suspicion that I am creating too many dependencies between the objects and could use some suggestions on how to architect this better. Thanks everyone. A: Use an event driven approach or the observer design pattern. Javascript has one of the flexible event driven implementation from my experience. So you have the Timer object which doesn't really have to know about any other objects. When you call Timer.start(), the object should emit a custom event, like "timerStarted", likewise for the other methods: Timer.stop() - > emits "timerStoped" Timer.timeExpired() -> emits "timerExpired" For every event raised by the Timer, there should be an event handler, which will be called when the coresponding event is fired. If you use jquery, handling events should be trivial: var $ = jQuery.noConflict(); var timer = new Timer(); var game = new Game(); $(timer).bind('timerStarted', function(e) { game.doSomething(); }); in the Timer::start() you should write: start: function() { $(this).trigger('timerStarted'); } Another approach is using callbacks: If you want something to be done when the timer starts, you could pass a lambda function to the start method of the timer: // timer method start: function(callback) { if(typeof(callback) == 'function') { callback(); } } // main logic var timer = new Timer(); var game = new Game(); timer.start(function() { game.doSomething(); }); I hope you get the ideea
{ "language": "en", "url": "https://stackoverflow.com/questions/7618419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to update Java constructors,equals,hash,etc. in eclipse? I wanted to know if anyone knows about a good way to update,constructors, equals,hash,to string, etc. generated by eclipse in Java. Lot's of time, after I use the auto-generated code-stubs, I add a member variable to the class, and then I need to delete the auto-generated code, and do it all over again. Is there a way to cause eclipse to add the new variable to the auto-generated code-stubs ? edit: ok deleting is not essential, however I still have to go and generate each on of them, I'm looking for an automatic solution. A: This isn't exactly a solution to your question, but I no longer use the Eclipse auto-generated methods, I use the Apache commons lang EqualsBuilder and HashCodeBuilder: So, for instance you can do: import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; public class EqualsTest { private String foo; private int bar; // getters and setters @Override public String toString() { return ReflectionToStringBuilder.toString(this); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } } This uses reflection, and doesn't need changing when you add a field. However, there are other options where you can specify the fields to use, and if you want to take into account the hashCode of the superclass as well. EDIT: As has been pointed out, the reflection aspect of this may have some performance penalties associated. Personally, I don't use the reflection HashCodeBuilder or EqualsBuilder in production code, I use the toHashCode (as below). I do however use the ReflectionToStringBuilder for logging and such like. Here is an example which doesn't use reflection, but requires you to add another line when you add a field: public int hashCode() { // you pick a hard-coded, randomly chosen, non-zero, odd number // ideally different for each class return new HashCodeBuilder(17, 37). append(foo). append(bar). toHashCode(); } For more discussion about hashCodeBuilder, see apache commons equals/hashcode builder A: Take a look at www.projectlombok.org as an alternative to writing these methods yourself. In particular the @Data annotation seems to fit your need, see http://www.projectlombok.org/features/Data.html. A: Iv'e created a project of my own with one field and asked eclipse to generate all the base methods. After that I added a new field, I asked it to generate these methods again (source -> generate...), it prompted me about replacing the old ones, I clicked 'yes' and the updated methods were displayed. Hope it helped
{ "language": "en", "url": "https://stackoverflow.com/questions/7618424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How we can set the font for all applications according to selected font type in one application Suppose I have an "apk" file. In this app, we can set the font. My question is how we can set that selected font for all applications. A: You can't. What would be the point of me being able to define fonts in my application if you were going to override them?
{ "language": "en", "url": "https://stackoverflow.com/questions/7618425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unexpected result from "stringWithFormat:" What would be the expected result from the following Objective C code? int intValue = 1; NSString *string = [NSString stringWithFormat:@"%+02d", intValue]; I thought the value of string would be "+01", it turns out to be "+1". Somehow "0" in format string "+01" is ignored. Change code to: int intValue = 1; NSString *string = [NSString stringWithFormat:@"%02d", intValue]; the value of string is now "01". It does generate the leading "0". However, if intValue is negative, as in: int intValue = -1; NSString *string = [NSString stringWithFormat:@"%02d", intValue]; the value of string becomes "-1", not "-01". Did I miss anything? Or is this a known issue? What would be the recommended workaround? Thanks in advance. A: @Mark Byers is correct in his comment. Specifying '0' pads the significant digits with '0' with respect to the sign '+/-'. Instead of '0' use dot '.' which pads the significant digits with '0' irrespective of the sign. [... stringWithFormat:@"%+.2d", 1]; // Result is @"+01" [... stringWithFormat:@"%.2d", -1]; // Result is @"-01" A: NSString *string = [NSString stringWithFormat:@"+0%d", intValue]; NSString *string = [NSString stringWithFormat:@"-0%d", intValue];
{ "language": "en", "url": "https://stackoverflow.com/questions/7618430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ActivityManager.getRecentTasks() returns 0 results update I've tried this on a 1.6 AVD and a real Droid Incredible. Both have the same issue. I need to get a list of recent tasks, but ActivityManager.getRecentTasks() always returns 0 results and can't figure out why. ActivityManager result = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); ArrayList<RecentTaskInfo> apps = (ArrayList<RecentTaskInfo>) result.getRecentTasks(10, ActivityManager.RECENT_WITH_EXCLUDED); I've set android.permission.GET_TASKS in the manifest but apps is always 0. Anyone have insight in to why? I'm stumped. A: Apparently it was that I needed to clean the project. Once I cleaned the project, it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Scan multiple file headers I have a java program in a certain directory. I would like to make it find a list of all files that end with .dat or .DAT in the same directory as the program. Then I need to look at the first couple of lines of each file and parse a title string. The program should return an array of the file names, and an array of the first three lines of each file. I am pretty new to IO stuff, can anyone help? Example: C:/my_directory/ Files: Program.class, FOO.DAT (starts with "Lorem\nipsem\n$$0"), bar.dat (starts with "ipsem\nLorem\n$$0") Return: ["FOO.DAT","bar.dat"] and ["Lorem\nipsem\n","ipsem\nLorem\n"] Thanks in advanced! A: The following code snippet prints out all the files that have .dat or .DAT file extensions in a given directory. Try to figure out how you can read first three lines from a file. That must be fairly straightforward File tmp = new File( "/tmp"); List<String> fileList = new ArrayList<String>(); if( tmp.isDirectory()) { for( File f : tmp.listFiles()) { if( f.isFile() ) { if((f.getName().endsWith( ".dat") || f.getName().endsWith(".DAT"))) { fileList.add( f.getName() ); } } } for( String fileName : fileList) { System.out.println( fileName); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7618442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i logout from android application I am new to android. I want code for logout from my application .I use shared preferences in my application. I want to put logout facility in my appplication. A: Yuu can clear the SharedPreference on Logout which you have set during login. OnClick of Logout: SharedPreferences sf = getSharedPreferences("UserLogin", MODE_WORLD_WRITEABLE); SharedPreferences.Editor edt = sf.edit(); edt.putString("UserName", ""); edt.putString("PassWord", ""); edt.commit(); Hope this will help you...
{ "language": "en", "url": "https://stackoverflow.com/questions/7618449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Java: How to merge the keys of two maps? I am working in Java, and have declared two maps as follow: private Map<MyCustomClass, Integer> map1, map2; map1 = new HashMap<MyCustomClass, Integer>(); map2 = new HashMap<MyCustomClass, Integer>(); //adding some key value pair into map1 //adding some key value pair into map2 private ArrayList<MyCustomClass> list = new ArrayList<MyCustomClass>(); Now i want to insert the keys of both map in the above declared ArrayList. Is there any built-in method exist for this or i need to writes some custom code? A: To add everything: list.addAll(map1.keySet()); list.addAll(map2.keySet()); To add only unique keys: Set<MyCustomClass> keys = new HashSet(map1.keySet()); keys.addAll(map2.keySet()); list.addAll(keys); References: List.addAll(Collection c); HashMap.keySet() A: list.addAll(map1.keySet()); list.addAll(map2.keySet()); keySet() gets all the keys from the map and returns them as a set. The addAll then adds that set to your list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to select an element by distance when it isn't a parent or child I'm working on editing a tooltip plugin (TooltipsY) to use a div instead of the title element for the content of the tooltip. I'm doing this for a multitude of reasons, the primary one being so I can have HTML in my tooltips without causing validation errors. The problem I'm having is that when changed the content of the tooltip to be the div instead of the title attribute, every link with a tooltip shows the same tooltip content. That's because The div's aren't related to the links in any way so I can't use "this" to select them. It would work if I knew some way to change $('div.showtip').html(); to this.closest($('div.showtip').html()); (that method won't work because the div isn't a parent or a child of the link) so how can I make the tooltip content the closest div to the link that's being hovered over? Here is my example: http://jsfiddle.net/sgCCD/2/ Note: The only thing that should need to be changed is the value of the variable showtip. Also, I don't want a suggestion for a different tooltip plugin, I'm doing this just as much for my own personal experience as I am to improve the functionality of the plugin. A: Hope this is what you're looking for: http://jsfiddle.net/sgCCD/3/ changed this line: var showtip = $('div.showtip').html(); to this: var showtip = $(el).next().html();
{ "language": "en", "url": "https://stackoverflow.com/questions/7618459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can i know whether i am using a snapshot version or not I have created my own repository under my hard disk using Apache Server and provided username and password under settings.xml file under the M2_HOME And when i am running mvn deploy under command prompt its displaying BUILD ERROR saying this <distributionManagement> <!-- use the following if you're not using a snapshot version. -- <repository> <id>repo</id> <name>Repository Name</name> <url>scp://host/path/to/repo</url> </repository> <!-- use the following if you ARE using a snapshot version. --> <snapshotRepository> <id>repo</id> <name>Repository Name</name> <url>scp://host/path/to/repo</url> </snapshotRepository> </distributionManagement> Please tell me how can i know whether i am using a snapshot version (I have imported an existing Maven project into Eclipse , i dont know about maven ) A: You just have to check in the same pom.xml file of the project whether the <version \> tag includes the -SNAPSHOT suffix. If the ${project.version} is not defined, look for the same tag under the <parent \> tag. Anyway, you are going to have some hard time setting up deployment with no previous knowledge of Maven. I suggest you take a look at this free PDF guide, which is a pretty good introduction to the tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Break the linked list into smaller linked lists I need to break a singly linked list into smaller linked lists after every 2 nodes . The approach I thought was, * *create an array containign head pointers of n/2 objects *Link hop the linked list and store the address in the array after every 2 nodes are encountered. Can there be a better approach for this? Thanks. A: That seems like a good approach. You also need to remember to set the next member of the 2nd, 4th, etc... elements to null to break the long list into smaller pieces. Remember to store the old value before you overwrite it as you will need to use it while you iterate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically add subdir in a Qt Project File? I need to dynamically add folders into $SUBDIRS , just scan for some folders , and: for file in plugin_dir if folder name ~ "^plugin-[A-Z]+$" SUBDIRS += $name fi But how can i implement this in a .pro file ? A: We do this by using qmake's system command. Where we need non-trivial commands to be run, we write a script (we use Python, but any language would do) that we pass info into via command-line options, and that writes out the desired values we want out into a qmake variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you make this batch file work in vista? Oo so I have created a batch file. it works fine in windows 7 but when i tested in vista it still works but it skips the :DELETE label it will go straight to :BEGIN label help please? , thanks for your time. :: Batch file Created By Ookami :: :: Copyright (c) 2011 NearFang™ :: :: Facebook: http://www.facebook.com/00k4MI :: :MAIN @ECHO OFF mode con:cols=43 lines=10 color 5B title MCTool echo %~n0%~x0 started from Directory: %~d0%~p0 > nul %~d0 cd %~d0%~p0 :Menu echo MC Batch Tool Copyright (c) 2011 Ookami. echo ----------------------------------------- echo [OPTIONS]: echo ========================================= echo [1]Run minecraft installer echo [2]Restore .minecraft echo ========================================= set /p choice=Enter Option: if %choice% == 1 goto 1 if %choice% == 2 goto 2 GOTO Menu :1 IF NOT EXIST .minecraft GOTO ERROR2 IF NOT EXIST %APPDATA%\.minecraft GOTO BEGIN IF EXIST %APPDATA%\.minecraft GOTO DELETE IF EXIST .minecraft GOTO BEGIN :BEGIN XCopy ".minecraft" "%appdata%\.minecraft" /S /E /I /Y cls echo Pre-Modded minecraft installed... echo. pause EXIT :DELETE cls echo An existing .minecraft folder was found! echo. echo Create backup, before deletion? SET /P input=Yes or No (Y/N): IF '%input%' == 'Y' ( GOTO BACKUP ) IF '%input%' == 'y' ( GOTO BACKUP ) IF '%input%' == 'N' ( GOTO DELNOW ) IF '%input%' == 'n' ( GOTO DELNOW ) ELSE ( GOTO ERROR ) :BACKUP IF EXIST mcbak\.minecraft RD mcbak\.minecraft /S /Q XCopy "%appdata%\.minecraft" "mcbak\.minecraft" /S /E /I /Y /Q cls echo Copied Folder To: echo. echo %~d0%~p0 echo. echo successfully completed! echo. pause cls echo starting deletion process... RD /S /Q "%APPDATA%\.minecraft" echo. echo .minecraft folder has been Deleted echo. pause cls echo Now installing Pre-Modded minecraft folder XCopy ".minecraft" "%appdata%\.minecraft" /S /E /I /Y /Q echo. echo successfully completed... echo. pause EXIT :DELNOW cls echo Starting Deletion Process... RD /S /Q "%APPDATA%\.minecraft" echo. echo .minecraft folder has been Deleted echo. pause cls echo Now installing Pre-Modded minecraft folder XCopy ".minecraft" "%appdata%\.minecraft" /S /E /I /Y /Q echo. echo successfully completed... echo. pause EXIT :ERROR echo. echo Your input was invalid echo. PAUSE GOTO DELETE :ERROR2 cls echo .minecraft folder was not found! echo. echo Note: mctool must be next to .minecraft echo. PAUSE EXIT :2 IF NOT EXIST mcbak\.minecraft GOTO noget IF NOT EXIST %APPDATA%\.minecraft GOTO nowget IF EXIST %APPDATA%\.minecraft GOTO DELNOW IF EXIST mcbak\.minecraft GOTO nowget :nowget XCopy "mcbak\.minecraft" "%appdata%\.minecraft" /S /E /I /Y cls echo Minecraft has been Restored successfully echo. pause exit :DELNOW cls RD /S /Q "%APPDATA%\.minecraft" GOTO nowget :noget cls echo No backups found or have been created echo. echo Note: mctool must be next to mcbak folder echo. pause exit A: Try to put %appdata inside quotes, like this: IF EXIST "%APPDATA%"\.minecraft GOTO DELETE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I setup nhibernate to handle this? I currently have this code. tableB = new TableB { TableA = tableA, }; List<TableC> tableC = locations.Select(location => new TableC { TableB = tableB }).ToList(); tableB.TableC = tableC; tableA.TableB.Add(tableB); nhibernate.Create(a); nhibernate.Commit(); The above code works but I find it kinda weird that I have do it like this. I would like to do something like tableB = new TableB { TableA = tableA, TableC = MakeAllTableCs() }; tableA.TableB.Add(tableB); nhibernate.Create(a); nhibernate.Commit(); The collection of tableC's is being made in memory and and when I try to do a create I get not-null property references a null or transient value It seems that it want's a reference to TableB for each one in the collection of TableC. It seems kinda odd to do this seeing that I am sticking in the TableB object. I would have hoped that it would have figured that out and used it as a reference. Is there anyway that I can do it so I don't need to have a reference of TableB in each of my TableC objects? Edit Mapping public class TableAMap : ClassMap<TableA> { public TableAMap() { Id(x => x.Id).GeneratedBy.GuidComb(); HasMany(x => x.).Cascade.All().Inverse(); } } public class TableBMap : ClassMap<TableB> { public TableBMap () { Id(x => x.Id).GeneratedBy.GuidComb(); References(x => x.TableA).Not.Nullable(); HasMany(x => x.TableC).Cascade.All().Inverse(); } } public class TableCMap : ClassMap<TableC> { public TableCMap () { Id(x => x.Id).GeneratedBy.GuidComb(); References(x => x.TableB).Not.Nullable(); } } A: Hard to say without your mappings and real NHibernate code (where you call session.Save()) but most likely you are not saving the new TableB objects and also don't have any cascade setting on TableA.b (you need one of those).
{ "language": "en", "url": "https://stackoverflow.com/questions/7618479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get data from database. Ok, I am able to connect to the mysql database from my iPhone app, I have set it up in a tableview. So when I call the didSelectRow method it stores the users Id number, not the indexRow number. My question is how can I use that stored id to retrieve the rest of the information, so when the row is pressed it brings up the rest of that users particular Information. I know I am not showing any code here that is because I'm writing this from my iPad, so I hope you cam follow what im trying to do and help. Thanks. A: I can help u in one way that u have to store the array coming from the data base in an array in appdel u can call that array at any time where we want sample code is here this is the array in appdb NSMutableArray *fruit_details; call one method in Appdb [self readStudentFromDatabase]; then write the code here in that method NSArray *documentpaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDir = [documentpaths objectAtIndex:0]; databasePath = [documentDir stringByAppendingPathComponent:databaseName]; fruit_details=[[NSMutableArray alloc]init]; //open the database from the users filesystem if(sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK) { // Setup the SQL Statement and compile it for faster access const char *sqlStatement ="select * from stu"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement , NULL)== SQLITE_OK) { // Loop through the results and add them to the feeds array while (sqlite3_step(compiledStatement)==SQLITE_ROW) { NSString *aName =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,0)]; NSString *amarks=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,1)]; NSString *arank =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,2)]; NSString *aaddr =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,3)]; NSString *aemail =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,4)]; NSString *aphno =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,5)]; NSString *aage =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,6)]; NSString *asex =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,7)]; NSString *adate =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,8)]; NSString *aimage=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)]; // // Create a new animal object with the data from the database //animal *animal_object=[[animal alloc]initWithName:aName description:arollNO url:amarks]; //add the animal object to the animal ar //[animals addObject:animal_object]; temp=[[NSMutableArray alloc]init]; [temp addObject:aName]; [temp addObject:amarks]; [temp addObject:arank]; [temp addObject:aaddr]; [temp addObject:aemail]; [temp addObject:aphno]; [temp addObject:aage]; [temp addObject:asex]; [temp addObject:adate]; [temp addObject:aimage]; [fruit_details addObject:temp]; } } sqlite3_finalize(compiledStatement); } sqlite3_close(database); I think this may help u..... A: Is stored id what you get from the db? My understanding is that when user select a row, you want to go to a new view and fetch the corresponding information from the db using that stored id.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I access sessions in background thread? How can i access my project sessions in background thread in my c#.net webapplication? it gives me session value = null. Any idea? A: Threads in the thread pool are managed by the system. These threads are not bound to the current request. Therefore, Session is not available for them. session lost when multithreading though A: You have to be very careful about using background threads with ASP.NET. By the time the thread executes, the "current" request will probably be over. This means you can't access the page, or the request, or anything interesting. A: You can't access the session but you could share your data the same way, using: HttpRuntime.Cache There are a few things to keep in mind though: unlike session, cache do expire. Also the cache is shared between all web users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to "link" to an already open Excel.Application with Interop c# I can create an instance of Excel using: Microsoft.Office.Interop.Excel.Application gXlApp = new Microsoft.Office.Interop.Excel.Application(); gXlWb= gXlApp.Workbooks.Add(Missing.Value); gXlApp.Visible = true; gXlApp.DisplayAlerts = false; BUT is there a way to "point" gXlApp at an instance of Excel that is already open? Currently I have to start Excel from c# then open the workbook and run my code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to refer objects on the stage? I have an object created visually. How should I refer to it from classes of other objects? MovieClip(this.root).someObj or stage.someObj or MovieClip(this.root).stage.someObj? And moreover, if I want to see which frame is current on the main timeline, why I cannot just check stage.currentFrame? Why there is no such property of the stage, currentFrame? It has timeline, right? A: root is the timeline, so MovieClip(root).someObj would do it. This should be pretty trivial to test for yourself :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7618490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find Duplicates in an array in O(N) time Is there a way to find all the duplicate elements in an array of N elements in O(N) time? Example: Input: 11, 29, 81, 14, 43, 43, 81, 29 Output: 29, 81, 43 Sorting the input and doing a linear scan to detect duplicates destroys the order and gives the output: 29,43,81. Sorting-by-key another array of indices {0,1,...N-1} according to the given array to get {1,4,2} and then sorting the resultant set of indices to get {1,2,4} will give us {29,81,43}, but this takes O(N logN) time. Is there an O(N) algorithm to solve this problem? P.S. I forgot to add: I dont want to use hash tables. I am looking for a non-hash solution. A: If your inputs are all small integers you can use a counting sort which runs in O(n) time and requires O(m) space where m is the size of the range of possible inputs. As a space optimization it is enough to use a bit array and use a single bit (rather than a count) to store whether you have seen that item before or not. A: It sounds like you're adverse to allocating any additional space. Nonetheless, a hash table is still the right solution for speed. Honestly, most hash table implementations for simple data such as integers are so overweight from their one-solution-fits-all nature that I just roll my own depending on what I need. It can turn slow code into fast code when you need it for relatively little work. Also, if your objection to hash tables is that they destroy order then perhaps you may want to use them a little differently to obtain expected O(n) while maintaining order: Create a hash table that maps your array elements to two bits as a counting field from zero to three, and thirty bits as an index into the array of elements. Unless you've got over a billion values in your array, thirty bits is enough. That way your hash values are just a single 32-bit word. Go through the elements in the array. If an element isn't in the table, insert the value into the hash table and set the count field to zero. It doesn't matter what the index portion is when you store it. If the element is in the table and the count field is zero, bump it up to 1 and store the element index with the new count field value. If the count field is already one or greater, set it to two and don't touch the stored index -- leave it as it is. Go through the elements in the array again. Look up each element and if its index is the one stored and the associated count field is more than zero, print it out. This should yield you what you want in the proper order with O(n) time. But, it uses hash tables which aren't desired for an unknown reason. I highly recommend you either accept a solution such as this one or explain the limitations so that you'll get a more accurately targeted solution. A: I believe a good solution (decent memory usage, can be used to immediately determine if an entry has already been seen thus preserving order, and with a linear complexity) is a trie. If you insert the elements into the trie as if they were a string with each digit (starting from the MSD) in each node, you can pull this off with a complexity of O(m N) where m is the average length of numbers in base-10 digits. You'd just loop over all your entries and insert them into the trie. Each time an element already exists, you skip it and move on to the next. Duplicates in this (unlike in my previous answer of a Radix Sort) will be found immediately instead of in the last iteration or what not. I'm not sure if you would benefit from using a suffix tree here, as the "base" of the characters being entered into the trie is only 10 (compared to the base-128 for ANSI strings), but it's possible. A: If you know the max value you can do like this, have a separate array with the length as the max value int[max] secondarray; for(int i=o;i<arrayFirst.length;i++){ if(secondarray[arrayFirst[i]]==0){ secondarray[arrayFirst[i]]==arrayFirst[i]; }else{ result.add(arrayFirst[i]); } } A: You can do this in O(n), this would however require the array to be integer. The space required for this can be though of the order size -2^32 to 2^32. What you'd need to do is find the max and min of the original array (arrayorig). Then make two arrays (arraynew+) and (arraynew-) . The size of (arraynew+) will be max(arraorig)-min(arrayorig) if all values in arrayorig are +, else the size of (arraynew+) will be max(arrayorig). The size (arraynew-) will be zero if all values are positive, else they will be equal to absolute value of min(arrayorig). Then you can iterate over the arrayorig and increment the value by 1 of (arraynew-) or (arraynew+) at the index corresponding to the value of arraorig,if the value is positive increment should be done to (arraynew+) else if its negative increment should be done to (arraynew-) at the index of (arraynew-) which is equal to absolute value of arrayorig. Then all the indexes of (arraynew+) and ((arraynew-) with value >1 are the distinct values of arrayorig. A: void printRepeating(int arr[], int size) { int i; printf("The repeating elements are: \n"); for (i = 0; i < size; i++) { if (arr[abs(arr[i])] >= 0) arr[abs(arr[i])] = -arr[abs(arr[i])]; else printf(" %d ", abs(arr[i])); } } A: Finding duplicates is just as hard as sorting. Your best bet is exploiting some property of your input in order to get a O(N) sort.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Keeping Track of Dynamic Programming Steps I'm teaching myself basic programming principles, and I'm stuck on a dynamic programming problem. Let's take the infamous Knapsack Problem: Given a set of items, each with a weight and a value, determine the count of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. Let's set the weight limit to 10, and let's give two lists: weights = [2,4,7] and values = [8,4,9] (I just made these up). I can write the code to give the maximum value given the constraint--that's not a problem. But what about if I want to know what values I actually ended up using? Not the total value--the individual values. So for this example, the maximum would be the objects with weights 2 and 7, for a total value of 8 + 9 = 17. I don't want my answer to read "17" though--I want an output of a list like: (8, 9). It might be easy for this problem, but the problem I'm working on uses lists that are much bigger and that have repeat numbers (for example, multiple objects have a value of 8). Let me know if anyone can think of anything. As always, much love and appreciation to the community. A: Consider each partial solution a Node. Simply add whatever you use into each of these nodes and whichever node becomes the answer at the end will contain the set of items you used. So each time you find a new solution you just set the list of items to the list of items of the new optimal solution and repeat for each. A: A basic array implementation can help you keep track of what items enabled a new DP state to get it's value. For example, if your DP array is w[] then you can have another array p[]. Every time a state is generated for w[i], you set p[i] to the item you used to get to 'w[i]'. Then to output the list of items used for w[n], output p[n], and then move to the index n-weightOf(p[n]) until you reach 0 to output all the items.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MKCoordinateregion's center changes when span changed - iphone I have a MKCoordinateregion called region. I want to change span of this region without changing it's center. I am using following method to change zoom. -(void) changeZoom { NSLog(@"before zoom span, center are %f, %f,%f,%f", region.span.latitudeDelta, region.span.longitudeDelta, mymap.centerCoordinate.latitude, mymap.centerCoordinate.longitude); region.span.latitudeDelta = current_factor ; region.span.longitudeDelta = current_factor ; region.center.latitude = mymap.centerCoordinate.latitude ; region.center.longitude = mymap.centerCoordinate.longitude ; [mymap setRegion:region animated:TRUE]; NSLog(@"after zoom span, center are %f, %f,%f,%f", region.span.latitudeDelta, region.span.longitudeDelta, mymap.centerCoordinate.latitude, mymap.centerCoordinate.longitude); } Log shows : before zoom span, center are 0.021950, 0.021950,19.068080,72.838111 after zoom span, center are 0.043901, 0.043901,19.068040,72.838154 This method set's span accurately as desired.But I dont want any change in the center's coordinate, Because when I zoom out and then zoom back I end up at a location different from starting location. Is there any method so that zoom in and out are possible without any change in center? Thanks for any help in advance. A: Your before and after center coordinates are almost exactly the same, so it shouldn't be a problem. If you really want the exact same center coordinates, call setCenterCoordinate:animated: right after you use setRegion:animated: and pass some saved center coordinates. CLLocationCoordinate2D originalCenter = mymap.centerCoordinate; // ... adjust region [mymap setCenterCoordinate:originalCenter animated:NO]; Also, you should use YES instead of TRUE for booleans: [mymap setRegion:region animated:YES]; A: You need to adjust the region of the map to make sure the aspect ratio fits the frame size of the map view. Once the region with the desired center is calculated, adjust the region as, MKCoordinateRegion adjustedRegion = [mymap regionThatFits:region]; [mymap setRegion:adjustedRegion animated:TRUE]; See docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Including a file from included file. Referencing issue Here's a sample file structure: page.php db.php folder1/subpage.php folder2/fn.php page.php require_once('folder2/fn.php'); folder1/subpage.php require_once('../folder2/fn.php'); folder2/fn.php - requires database connection require_once('../db.php'); /* then gets info from database */ Basically, fn.php contains database functions to get/set information. It requires db.php, which is database connection file. This code works in subpage.php, but not in page.php (getting "failed to open stream: No such file or directory in ..." error). Is there a way (using relative referencing), so that it works in all files no matter of directory level? Thanks for your help! A: I always use the absolute path to the include. There are a couple ways to do this, this command will return the absolute path <?php echo getcwd(); ?> But this is what I personally use: <? include $_SERVER['DOCUMENT_ROOT'] . "/includes/analytics.php"; ?> no matter where the file is php will have the absolute path.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I run an arbitrary java file with Eclipse? I need to run some example java code. I like using eclipse because it shows the methods, properties, constructors and so on. The problem I'd like to solve is that unless I create a new project I can't compile and run the example code I'm using! Is there a way around this? A: No, there is no way around this. A Java file is very rarely a self-contained program with no dependencies at all. Most of the time, a program is composed of many collaborating classes depending on external libraries. If you just want to test a self-contained Java program consisting of just one java file, then create a "playground" eclipse project, drop this file inside this project, and run it. Use the same playground project for all the other self-contained java programs if you want: you may have several main classes inside a single eclipse project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alignment of objects in Android In any layout i am not able to align the objects like textview, edittext ot button as per my wish. I m New to android, please somebody help me, I wanted to design form like in .net windows programing. Thanks in advance A: You can do it.Take RelativeLayout and take all your widgets inside it and use options like android:layout_centerInParent,android:layout_alignParentLeft,.....there are many more. From here you can find about this layout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: My python interpreter does not recognize strings Newbie disclaimer: I am new to Python and just started using IDLE to play around with Python. My problem is the interpreter does not recognize strings, whether enclosed in ¨¨ or ´´. I configured IDLE to use UTF-8. but it does not seem to be an IDLE issue. What I tried is to test this string in the interpreter directly. It does not work. print ¨Money¨ to the interpereter returns File "<stdin>", line 1 print ¨Money¨ ^ SyntaxError: invalid syntax Can someone help me with this? I am using a new laptop running fedora15 with the international keyboard layout and python version is 2.7.1. A: You need to use "" or '', not ¨¨, ´´ or any other fancy characters. A: Just switch your keyboard setting between normal US English for coding, and US English International for texting, that worked for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: If I close one of my forms, they all close I am new to win forms (C#). The current form that I'm making has the option to create a new (blank) instance of itself, but if I ever close that first instance, all the others close as well. This is not what I want to happen. (Closing any form opened up from the first doesn't close any others, though) I was thinking it may be because I am creating a new copy from within one of the copies/objects, so it is tied to that first object so it closes when it does; however, if I open up another form from the one opened from the first one and then close that one that was opened from the first one, the one that I opened up from it doesn't close. I want it so that I can still close that first form without the others closing, and that when the last one closes, the program stops running. Is there any way to do this? A: You can run as many forms as you need but each in the separate thread using System; using System.Threading; using System.Windows.Forms; public partial class MyForm: Form { public MyForm() { InitializeComponent(); } private void Button1Click(object sender, EventArgs e) { var t = new Thread(() => Application.Run(new MyForm())); t.Start(); } } A: You should not have to close the Entry Point (MainForm) Form. Check the Main() method code in Program.cs code file. public static void Main(string[] args) { // Starts the application. Application.Run(new Form1()); } Read this page. To prevent a form from closing, handle the Closing event and set the Cancel property of the CancelEventArgs passed to your event handler to true. A: You dont need to create new thread for every form. Just use this: Form newForm1 = new Form(); this.Hide(); newForm1.ShowDialog(); this.Close(); A: Shortly: The first form of every windows application is the main form. If it closes, so does the application. (See Program.cs for more details) To solve this you can call Application.Run (While I don't know if it's smart or not) A: static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); new Form1().Show(); // any entry point with form Application.Run(); // without main form } } Program.cs You can use like this code block. But when any form closed, application not finished. (Even if the last a form in application.) Because application not included mainform. If application has not any a opened form. Application will suspend in process. You can see then the task manager. As a result you will call manually Application.Exit() method in each form close events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala Object Serialization I am having trouble opening multiple objects that were serialized into a single .bin file. Right now, I can only get one object to be read in when I attempt to open the file. After the first object is read, the error message is displayed (and no further objects are read). My code looks like the following: val ois = new ObjectInputStream(new BufferedInputStream(newFileInputStream(chooser.selectedFile))) val toRead:Int = ois.readInt() for (i <- 0 to toRead) { ois.readObject() match { case anObject : myObject => aMutableBuffer += anObject case _ => } ois.close() } The error that I am getting is a lot of the following: Exception in thread "AWT-EventQueue-0" java.security.PrivilegedActionException:java.security.PrivilegedActionException: java.io.IOException: Stream closed at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87) at java.awt.EventQueue.dispatchEvent(EventQueue.java:649) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) Caused by: java.security.PrivilegedActionException: java.io.IOException: Stream closed at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98) at java.awt.EventQueue$2.run(EventQueue.java:652) at java.awt.EventQueue$2.run(EventQueue.java:650) ... 9 more Caused by: java.io.IOException: Stream closed at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:145) at java.io.BufferedInputStream.read(BufferedInputStream.java:241) at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2248) at java.io.ObjectInputStream$BlockDataInputStream.peek(ObjectInputStream.java:2541) at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2551) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1296) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350) atABCk.PhotoshopApp$$anonfun$ABCPhotoshopApp$$fileOpenPicture$1.apply$mcVI$sp(PhotoshopApp.scala:32) at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:75) at ABC.PhotoshopApp$.ABC$PhotoshopApp$$fileOpenPicture(PhotoshopApp.scala:31) at ABC.PhotoshopApp$$anon$9$$anon$11$$anon$1$$anonfun$2.apply$mcV$sp(PhotoshopApp.scala:111) at scala.swing.Action$$anon$2.apply(Action.scala:60) at scala.swing.Action$$anon$1.actionPerformed(Action.scala:78) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.AbstractButton.doClick(AbstractButton.java:389) at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:809) at com.apple.laf.AquaMenuItemUI.doClick(AquaMenuItemUI.java:137) at javax.swing.plaf.basic.BasicMenuItemUI$Handler.menuDragMouseReleased(BasicMenuItemUI.java:913) at javax.swing.JMenuItem.fireMenuDragMouseReleased(JMenuItem.java:568) at javax.swing.JMenuItem.processMenuDragMouseEvent(JMenuItem.java:465) at javax.swing.JMenuItem.processMouseEvent(JMenuItem.java:411) at javax.swing.MenuSelectionManager.processMouseEvent(MenuSelectionManager.java:305) at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:852) at java.awt.Component.processMouseEvent(Component.java:6373) at javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at java.awt.Component.processEvent(Component.java:6138) at java.awt.Container.processEvent(Container.java:2085) at java.awt.Component.dispatchEventImpl(Component.java:4735) at java.awt.Container.dispatchEventImpl(Container.java:2143) at java.awt.Component.dispatchEvent(Component.java:4565) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4621) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4282) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4212) at java.awt.Container.dispatchEventImpl(Container.java:2129) at java.awt.Window.dispatchEventImpl(Window.java:2478) at java.awt.Component.dispatchEvent(Component.java:4565) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:679) at java.awt.EventQueue.access$000(EventQueue.java:85) at java.awt.EventQueue$1.run(EventQueue.java:638) at java.awt.EventQueue$1.run(EventQueue.java:636) ... 14 more This only happens when I read in an object to my buffer that keeps track of the objects. Moreover, I am able to save the file correctly (as I have done tests to ensure everything got there). Anyone have any ideas what is going on here? A: You are closing your Stream ois at the end, but inside the loop. Then you try to read from it on the first line of the loop. Which obviously failes with a IOException: Stream closed
{ "language": "en", "url": "https://stackoverflow.com/questions/7618510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sharing an app with .ipa file and make push notifications to work If I share an ipa file to test my iOS app on colleague devices, are push notifications going to work ? Do I need to register any new colleague profile / submit the devices on which the app is going to be installed ? thanks A: You need to sign the app with the same certificate created when you enabled Push Notifications for the app. When the testing user installs that app and accepts push notifications for this app, they will receive them, simple enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Solr(Lucene) is indexing only the first document after adding a custom TokenFilter I created a custom token filter which concatenates all the tokens in the stream. This is my incrementToken() function public boolean incrementToken() throws IOException { if (finished) { logger.debug("Finished"); return false; } logger.debug("Starting"); StringBuilder buffer = new StringBuilder(); int length = 0; while (input.incrementToken()) { if (0 == length) { buffer.append(termAtt); length += termAtt.length(); } else { buffer.append(" ").append(termAtt); length += termAtt.length() + 1; } } termAtt.setEmpty().append(buffer); //offsetAtt.setOffset(0, length); finished = true; return true; } I added the new Filter to the end of index and query analysis chain for a field and testing the filter from http://localhost:8983/solr/admin/analysis.jsp seems to be working. The filter is concatenating the tokens in the stream. But on re-indexing the documents only my first document is getting indexed. This is how my filter chain looks like. <analyzer type="index"> <charFilter class="solr.PatternReplaceCharFilterFactory" pattern="[-_]" replacement=" " /> <charFilter class="solr.PatternReplaceCharFilterFactory" pattern="[^\p{L}\p{Nd}\p{Mn}\p{Mc}\s+]" replacement="" /> <tokenizer class="solr.WhitespaceTokenizerFactory" /> <filter class="solr.LowerCaseFilterFactory" /> <filter class="solr.StopWordFilterFactory" ignoreCase="true" words="words.txt" /> <filter class="org.custom.solr.analysis.ConcatFilterFactory" /> </analyzer> <analyzer type="query"> <charFilter class="solr.PatternReplaceCharFilterFactory" pattern="[-_]" replacement=" " /> <charFilter class="solr.PatternReplaceCharFilterFactory" pattern="[^\p{L}\p{Nd}\p{Mn}\p{Mc}\s+]" replacement="" /> <tokenizer class="solr.WhitespaceTokenizerFactory" /> <filter class="solr.LowerCaseFilterFactory" /> <filter class="solr.StopWordFilterFactory" ignoreCase="true" words="words.txt" /> <filter class="org.custom.solr.analysis.ConcatFilterFactory" /> </analyzer> Without the ConcatFilterFactory all words are getting indexed properly but with ConcatFilterFactory only the first document is getting indexed. What am I doing wrong? Kindly help me in understanding the problem. UPDATE : Finally figured out the issue. if (finished) { logger.debug("Finished"); finished = false; return false; } Looks like the same class is being reused. Makes sense. A: You should write a unit test for your filter. It should fail even if your Analysis works. Apparently you forgot to add this line before returning false: finished = false;
{ "language": "en", "url": "https://stackoverflow.com/questions/7618513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: I want to pass three different strings to my main method in java. How do I do this? I want people to enter there first name then middle name then last name inside of a method. I then want to pass all three variables into my main method. Is there anyway I can do this? And how would I get the different data stored in my main method? A: No there isn't but use Command line arguments. public class YourProgram { public static void main(String []args) { } } c:\>java YourProgram "First String" "Second String" "Third String" A: If by main you refer to application's entry point, the main method. E.g. public class SomeClass{ public static void main(String[] args){ String firstName = args[0]; String middleName = args[1]; String lastName = args[2]; } } Then you can pass it as a three arguments after program name when you call it. java SomeClass "first name" "middle name" "last name" A: If you're referring to the actual main method, as in the first method that runs, you can't pass in any variables because there isn't a place to pass a variable, it's where the program starts. edit: as AVD said, you can pass the variables if you run the program from the console, but not inside the code itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I guarantee uniqueness of a table value only within a subset of the table rows? I have a table of projects belonging to various users: project_id, owner_user_id, project_name I do not need the project_names to be globally unique to the table, so making project_name UNIQUE does not help. I would just like to prevent the user from creating duplicate project_names on INSERT or UPDATE. Upon INSERT/UPDATE, I simply want to check if there is already a project_name belonging to a specific owner_user_id, and if it already exists, the INSERT/UPDATE should fail. I could use a SELECT to first check for existence of the project_name within the user's projects, and then only do an INSERT/UPDATE if the select returns no results. But this is multi-threaded and another thread could INSERT the same project_name immediately after I perform the SELECT but before the INSERT/UPDATE. Putting this all into a transaction feels like overkill. Is there a single query that can perform this instead? A: You could add a UNIQUE constraint on the two columns as a pair: alter table your_table add unique (owner_user_id, project_name) That will ensure that project_name values are unique per-user. You'll want to have a look at your collation set up to make sure your project_name values are compared without regard to case. Or you could standardize the project names to title case before hitting the database. Don't try to maintain data integrity by hand unless you have to, let the database take care of your constraints whenever possible. A: This does need to be in a transaction. You need to retrieve some information ("which names are already in use?") and then act on it ("if my name is not in use, then use it"). This must be done atomically. As you have correctly surmised, there is a race condition if the insert does not happen atomically after the check. This is what transactions are for. A: You can add a unique constraint on both fields CONSTRAINT C_UNICITY UNIQUE (owner_user_id, project_name) Each time you try to insert or update a record which present duplicate, you'll get a sql error A: $result = mysql_query("select * from Project where owner_user_id='1';"); if (mysql_affected_rows()==0) { $result = mysql_query("insert into Project (projectname) values ('pojectname');"); A: Depending on database referential integrity violations to throw errors for you to trap is not generally a preferred form of UI validation - you generally want something at a higher abstraction level anyway. But there's nothing particularly "overkill" about using transactions and UNIQUE constraints liberally to protect your data as much as your users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom cell code showing leaks in iPhone this may be a simple question but i can't figure the solution.Im creating a custom cell for a table view.When I'm testing the app instruments is showing leaks in code used for creating custom cell.I don't understand where i have to release the stuff for removing the leaks.Can anyone give me a hand for this. This is the code i used for creating the custom cell. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellID= @"Parcustom"; Parcustom *cell = (Parcustom *)[tableView dequeueReusableCellWithIdentifier:cellID]; if(cell==nil) { NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"Parcustom" owner:nil options:nil]; for(id currentObject in nibObjects) { if([currentObject isKindOfClass: [Parcustom class]]) { cell = (Parcustom *)currentObject; } } } // Configure the cell... cell.f1.text=[datedisplay objectAtIndex:indexPath.row]; cell.f2.text=[tips objectAtIndex:[[indexx objectAtIndex:indexPath.row]intValue]]; cell.selectionStyle=UITableViewCellSelectionStyleGray; return cell; } The instrument is saying leak in the line NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"Parcustom" owner:nil options:nil]; How can i remove this leak.Can anyone help me please. A: Replace below code with if block NSArray *nibObjects = [[NSArray alloc] initWithArray:[[NSBundle mainBundle] loadNibNamed:@"Parcustom" owner:nil options:nil]]; for(id currentObject in nibObjects) { if([currentObject isKindOfClass: [Parcustom class]]) { cell = (Parcustom *)currentObject; } } [nibObjects release]; A: It seems there is no leak in the code presented. I suppose actual leak is somewhere in Parcustom class. Perhaps you don't release some ivar in Parcustom's dealloc. Maybe f1 or f2. A: I don't see a leak in your code - Try running the static analyzer ("Analyze" in XCode's menu) and see if it reports a leak. If it does, you can expand the information about the leak and see the root cause.
{ "language": "en", "url": "https://stackoverflow.com/questions/7618526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }