text
stringlengths
8
267k
meta
dict
Q: In Django how can I create a user and a user profile at the same time from a single form submission I am using extended version of the UserCreationForm to add users via my own template, which is working well. I would also like to include, as part of the same form template, a custom field from my userprofile model, so that when the user is created a user profile with my custom field would also be created. My approach to this has been to use two forms and combine them in one template with a single submit button. The form displays exactly as I wanted, and returns validation errors correctly, but predictably it falls down when it comes to saving to the database. When I call save() on the user form the user is created, but of course when I try to save the userprofile form it throws an error because the user doesn't yet exist so it has not user associated to it. Although I think I understand the cause of my problem, I am at a loss as to how to fix it, I am not even sure if the approach that I have taken is correct. I have included all my code below including the model as well as the forms and the view just in case this helps anyone to better understand what I am trying to do: UserProfile class (models.py) LEVEL = ( ('admin', 'administrator'), ('team', 'team leader'), ('member', 'team member'), ) class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) level = models.CharField(choices=LEVEL, max_length=20) UserCreationForm and UserProfileForm classes (forms.py) class UserCreationFormExtended(UserCreationForm): def __init__(self, *args, **kwargs): super(UserCreationFormExtended, self).__init__(*args, **kwargs) self.fields['first_name'].required = True self.fields['last_name'].required = True class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') class UserProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields["level"].choices = ( ('admin', 'administrator'), ('team', 'team leader'), ('member', 'team member') ) class Meta: model = UserProfile use_add view (views.py) def user_add(request): if request.method == 'POST': uform = UserCreationFormExtended(request.POST) pform = UserProfileForm(request.POST) if uform.is_valid(): uform.save() pform.save() return render_to_response('user/add_success.html', context_instance=RequestContext(request)) else: return render_to_response('user/add.html', { 'uform' : uform, 'pform' : pform }, context_instance=RequestContext(request)) else: uform = UserCreationFormExtended() pform = UserProfileForm() return render_to_response('user/add.html', { 'uform' : uform, 'pform' : pform }, context_instance=RequestContext(request)) A: First, add exclude = ('user',) to the Meta class for ProfileForm. Then, in your view: user_valid = uform.is_valid() profile_valid = pform.is_valid() if user_valid and profile_valid: user = uform.save() profile = pform.save(commit=False) profile.user = user profile.save() Although it occurs to me that since you only have one field on the profile form, an easier way to do it is to forget that form completely, and just add the field to the user form: class UserCreationFormExtended(UserCreationForm): level = forms.ChoiceField(choices=LEVEL, max_length=20) ... etc... if uform.is_valid(): user = uform.save() profile = Profile.objects.create(user=user, level=uform.cleaned_data['level'])) A: There's a similar solution I found here: http://sontek.net/blog/detail/extending-the-django-user-model Basically you just extend the default form UserCreationForm but keeping the same name. By doing it like this you dont have to add any new views or anything like that, it works seamlessly with the way Django's docs tell you to do UserProfiles. Frankly, I don't understand why they explain how to add the fields to the admin page, and then don't tell you how to actually use those fields anywhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is it possible to use Active Directory to house information about outside domain computers for PHP LDAP query later? For an intranet website. I have considered using Active Directory, LDAP, queried via PHP for security. That is I would query AD for the user, let this have access so x webpage or x control on that webpage. I also need, however, to use machine for security so the person can only access if they are a certain user and they are on a certain machine. Some of these machines are outside of the AD (same company just not in my domain.) Because of the last statement I use I currently use a MySQL database for users and then use IP addresses of the incoming for controlling the access of pages and items on a page. I still make them have an account on AD for getting on the Intranet to begin with...I just hand off control of granular security to the mysql database after AD authorization and authentication to the main page of intranet. I hope this makes sense. Thanks for any help. edit: point is I want to put everything in AD and remove the extra database layer. A: Sure, just create entries for the external machines using an appropriate schema, include the IP address as an attribute, then when the user logs in search AD for a machine entry with that IP address.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIScrollView prevent scrolling in one direction regardless of contentSize/Offset I have a UIScrollView with paging enabled but I would like to be able to prevent the user to swipe to the next page or back to the previous page in some cases. For instance someone could be passing a test with ten questions (one question per page) but scrolling won't work unless the person has answered the question at the current page. It could also be to prevent them to swipe back to the previous page. So basically I cannot use directional lock or temporarily disable user interaction because the reader could be allowed to swipe left but not to swipe right. I noticed a few people play around with the content offset but I find that solution ugly because the user can still swipe, it's just that the app automatically readjusts the content offset. I would like it to be as if the view had reached the end of the content or if user interaction was disabled. I guess I could maybe "play" with the content size/offset and refresh it on each page but I am not sure how to do that properly as I also have "links" that can allow someone to jump from one page to another (that could at the time be outside the defined content). I have tried using a custom view for pages where swipe in a specific direction is locked but it doesn't work as I could not find a way to prevent the scroll view from detecting the swipe without affecting pages were swipe should work in a normal way. I saw that I could set that custom view exclusiveTouch property to YES and assumed that since it was going to get all the events I could handle swipes via custom gesture recognizers and forward the events if swipe was allowed or ignore them if not. It did not work, the ScrollView always catches swipe events. I feel I have exhausted every possibility and I cannot find anyone who had similar needs. So I am wondering, is this even possible? If yes, will it require bad hacks or to make a new custom scroll view? Any help/idea would be greatly appreciated. A: use your condition at the appropriate place in your code where you want the scroll/paging locked and set pagingEnabled or scrollEnabled of your scrollView object to NO. EDIT: Should've read your requirement more carefully. For your needs a better solution would be to use multiple views slide in and out from the sides based on your conditionals. Animate them. Gesture recognizers should also help. And I'm not talking scrollView here. View1 -> condition -> passes? (button action or gesture) -> animation into view2 and so on. If you really must use the scrollView, the best you can do is to set the contentSize to the width of the screen and set alwaysBounceHorizontal to NO to prevent the automatic bouncing effect: CGRect size = scrollView.contentSize; size.width = CGRectGetWidth(scrollView.frame); scrollView.contentSize = size; scrollView.alwaysBounceHorizontal = NO; A: Found in another post, this is how I solved the same problem I had. Put this in you view controller and set it as the delegate of the UIScrollView CGPoint oldOffset; // instance variable - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { oldOffset = scrollView.contentOffset; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (scrollView.contentOffset.x < oldOffset.x) { [scrollView setContentOffset:oldOffset]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Xcode 4 - svn problem So I created a new project wrote some code and now I just imported my project into my svn server. I just checked out the project and I am getting this message 'Test_project'is locked for editing and you may not be able to save your changes. Do you want to unlock it? when I click on unlock I get this message. The file “myusername.xcuserdatad” could not be unlocked. I cant even locate this file. Has anyone else had this problem? Please help. I'm totally new here A: myusername.xcuserdatad is a directory inside the xcodeproj bundle. Right click the .xcodeproj file in Finder and select "Show Package Contents". In there will be a directory called xcuserdata nd the subdirectory you need will be under that. It may be enough to delete that directory (also delete it from Subversion) to resolve your issue (make sure Xcode is closed when you do this). A: * *check the svn status of this file/folder, go into the work folder *if the status it's "K", then it's be locked. (check commend:"svn status -v") *input "svn unlock " + your file name , to unlock the file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to save textcolor on textview by using NSUserdefaults I am the beginner of iphone developer,my problem is how to save the textcolor on textview. i want to taken 3buttons in each one set one color.when i tap the button.what the button had color text write on textview and at the same time save the feature also.when i open the application it does not lose the old feature.so how can solve the problem please help me. thanks... A: You can archive any object and store it in user defaults. To set it: NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color]; [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"color1"]; And to retreive it: NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"color1"]; UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
{ "language": "en", "url": "https://stackoverflow.com/questions/7584988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: First elisp attempt - minor mode for tab key not being invoked on tab? I've decided to get my toes wet with a bit of lisp, since I want to make emacs behave a little better when I hit TAB. My command works fine. It just performs indent-for-tab-command and if nothing happens, it performs tab-to-tab-stop, on the assumption that it's unlikely I was hitting TAB just to have the point refuse to budge when I'm inside a multi-line string or some such. After the first TAB press, it continues to do tab-to-tab-stop until either editing resumes, or the point is moved elsewhere. AFAIK, my logic is ok, though my lisp code probably isn't! Originally I just hacked this into my emacs dot files by doing (local-set-key (kbd "TAB") 'tab-dwim) for major modes where I wanted this behaviour. That worked as expected. Then I decided that what I was doing was basically a minor mode, so I tried to move the key-binding into a minor-mode. For some reason, even though the minor mode is enabled (as indicated in the mode line, and just from toggling it on and off), my tab-dwim function isn't being invoked when I hit the TAB key. I can still invoke it with M-x as expected. What am I doing wrong with my minor mode's :keymap? ;;; ;; TAB DWIM ; buffer-local before/after point tracking (setq point-before-tab nil) (setq point-after-tab nil) (make-local-variable 'point-before-tab) (make-local-variable 'point-after-tab) (defun tab-dwim () "Indents normally once, then switches to tab-to-tab-stop if invoked again. tab-dwim will always perform tab-to-tab-stop if the first TAB press does not cause the point to move." (interactive) (print "in tab-dwim now") ; THIS LINE IS NEVER INVOKED ON TAB? (setq point-before-tab (point)) (if (eq point-before-tab point-after-tab) ; pressed TAB again (tab-to-tab-stop) (indent-for-tab-command)) (if (eq (point) point-before-tab) ; point didn't move (tab-to-tab-stop)) (setq point-after-tab (point))) (define-minor-mode tab-dwim-mode "Toggle tab-dwim-mode. With a non-nil argument, turns on tab-dwim-mode. With a nil argument, turns it off. When tab-dwim-mode is enabled, pressing the TAB key once will behave as normal, but pressing it subsequent times, will continue to indent, using tab-to-tab-stop. If tab-dwim determines that the first TAB key press resulted in no movement of the point, it will indent according to tab-to-tab-stop instead." :init-value nil :lighter " DWIM" :keymap '(([TAB] . tab-dwim))) (provide 'tab-dwim) Cheers, Chris A: I think you are very close. Try this for your keymap: '(("\t" . tab-dwim))) A: Yes, use "\t" or the vector format "[(tab)]". Some additional notes for your elisp development: * *Avoid making global variables as much as possible. In this case, I think dynamically binding with let is appropriate. Also have a look at let*. *Understand the difference between make-local-variable and make-variable-buffer-local. The way you've written your code, the buffer-local variable would only exist in the buffer that loads your package. *As Nemo mentioned, it's extemely extremely extremely recommended that you use a common prefix for all variables/functions related to each package. Emacs has only one namespace, this is the "hacky" way to keep it somewhat organized.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: struts 2 Action within action Can i get the response of an action inside other when the second one is still in progress. for example : i need to display a page that is called under some action which is still running and may be acting as a listener to events always.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Horizontal Scroll View I have a horizontal scroll view, and inside I have a number of image views, they go across the screen and altogether are wider than the screen. I've tried to scroll through them using touch, but nothing happens, am I missing something? A: Inside HorizontalScrollView, put a LinearLayout with orientation Horizontal and add ImageView to that LinearLayout
{ "language": "en", "url": "https://stackoverflow.com/questions/7584994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Basics of ScrollView in Iphone I started with a view based template where I added a scroll view from IB in view Controller.xib Then in MyViewController.m in method - (void)viewDidLoad 1)added 5 imageview with images in that with proper x and y 2)Then I set the contentSize 3)then [scroll setContentOffset:CGPointMake(0,0)]; - (void)scrollViewDidScroll:(UIScrollView *)sender { NSLog(@"inside DID SCROLL"); NSLog(@"The scroll is %@", sender); NSLog(@"The scroll.contentOffset.x is %@", [sender contentSize]); } Now if contentoffset is (10, 0) it crashes straight away, but if contentoffset is (0, 0) then it calls didScroll and then crashes on [sender contentSize] What am I doing wrong, I'm sure it's a very basic error. Thanks A: Yes. Its a basic error. contentSize is a struct which you can not print as object by using %@. You can print is as, NSLog(@"%@", NSStringFromCGSize([scroll contentSize])); Or as, NSLog(@"%f, %f", scroll.contentSize.width, scroll.contentSize.height);
{ "language": "en", "url": "https://stackoverflow.com/questions/7585000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to copy text from commandline mode in Vim while searching There is already a question regarding how to copy text in commandline in Vim. There are two alternative answers: * *":p, and *Ctrl+F, followed by finding the previous command. But these methods don't work when the previous command is a search. That is if I enter into command mode with / or ?, then the search term used cannot be accessed with these methods. Is there a way to copy text for search text as well? A: I believe you are looking for the / register. You can use "/p to paste the last search. While on the command-line you can use <c-r> followed by a register to insert the contents of the given register. example: <c-r>/ will paste the last search. You may also wish to use q/ to do more extensive editing of your previous searches. :h registers :h q/ :h c_CTRL-R A: Taking the approach similar to the one proposed in the accepted answer to the question “How to copy text from commandline mode in Vim”, one can use the / register to paste the most recent search pattern: "/p The whole history of searches can be explored using the command-line window (see :help cmdwin). To open it for editing of search strings from Normal mode, use the q/ or q? commands. To do the same when entering a search pattern for the / or ? commands, press the key combination specified by the cedit option (Ctrl+F, by default).
{ "language": "en", "url": "https://stackoverflow.com/questions/7585001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android ActionBar Tab Color I have added ActionBar tabs to my application. Default color for that underline is light blue. How do I change that color or style for selected tab ? A: For anyone wants to change actionbar color/background in code, you can do something like this final ActionBar actionBar = getActionBar(); actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar_bg)); To change the tab bar color under the actionbar: actionBar.setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.color_brown_dark))); To change tab bar background: actionBar.setStackedBackgroundDrawable(getResources().getDrawable( R.drawable.coupon_header)); A: ActionBar bar = getActionBar(); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // set background for action bar bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0c2354"))); // set background for action bar tab bar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#B5C0D0"))); bar.show(); A: Here is a much easier way: I've been struggling with this for days, but finally found the solution. I'm using AppCompat. You can set colorAccent in your theme and that will change the highlight color on your ActionBar. Like so: <item name="colorAccent">@color/highlightcolor</item> Here it is in context: <style name="LightTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="colorPrimary">@color/darkgrey</item> <item name="colorPrimaryDark">@color/black</item> <item name="colorAccent">@color/highlightcolor</item> </style> Where I originally posted this answer: Android Tab underline color not changing A: 1) Generate the Action Bar Style, click Download ZIP to get the files 2) When you extract the zip file created in Step 1, you will get a res folder. Add this folder to your project under platform/android. 3) Modify manifest.xml to Use the New Action Bar Style, where "Action" is name of your style set in step 1. <android xmlns:android="http://schemas.android.com/apk/res/android"> <tool-api-level>14</tool-api-level> <manifest> <application android:theme="@style/Theme.Action"/> <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="16"/> </manifest> </android> This manual helped me and I hope it will help you too. A: This may give some clues Action Bar Style Gen A: selectableItemBackground is the attribute I think your looking for. I'd recommend you read this article about Customizing the Action Bar as well as look at this question on SO and this one as well. In code i cant seem to find a way to customize the individual item selected but , customizing the bar itself would look something like this. ActionBar bar = getActionBar(); bar.setBackgroundDrawable(new ColorDrawable("FF0000"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7585002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: IE6/7 divs float without width problem when cleared (in a fixed width parent div) HTML: <div id="container"> <div id="div1">div one floats to the left</div> <div id="div2">div two floats to the left</div> </div> CSS: #container{ width:200px; background:gray; } #div1 { float:left; background:red;} #div2 { float:left; background:green; clear:left;} in IE6/7: notes: I want the widths of the child divs like #div1 and #div2 be automatic according to their contents. Since with inline-block it seems the line-height does not work, I use float. I have tried adding an empty clear div after #div1, instead of clear in #div2, and that works. Is there any other simpler solution and what's the bug? Appreciate your help. A: Going with your solution... Simply don't clear on the floating div, you're telling it to float but to be cleared too. Kinda confusing! <style> #container{ width:200px; background:gray;} #div1 { float:left; background:red;} #div2 { float:left; background:green; } </style> <div id="container"> <div id="div1">div one floats to the left</div> <br style="clear:left" /> <div id="div2">div two floats to the left</div> <br style="clear:left" /> </div> If you don't put the 1st <br />, ie6/7 will try to fit the 2nd div in the little space left. If you clear the div, it will put it on a new line, but give it the same length as if it was still to the right of the first div. Your solution is good and simple enough in my opinion, you can go with it. Otherwise, here are 2 alternatives : Alternative 1 Inline blocks works... if you use non-block element to begin with (not sure exactly why). <style> #container{ width:200px; background:gray;} #div1 { background:red; display:inline-block; line-height:30px;} #div2 { background:green; display:inline-block;width:auto; } </style> <div id="container"> <span id="div1">div1</span> <span id="div2">div2 doesnt float blablabla</span> </div> Alternative 2 Use tables (not really good, but still, it works!) <style> #container{ width:200px; background:gray;} #div1 { background:red;} #div2 { background:green; } </style> <div id="container"> <table><tr><td id="div1">div one floats to the left</td></tr></table> <table><tr><td id="div2">div two floats to the left</td></tr></table> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7585003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Send on Socket while listening I have programmed (in JAVA) a socket using simple examples in the web. I can either send or listen at one time - as far as I understood. Isn't there a possibility where I can send/listen/receive full duplex? Thank you very much. A: You can send and receive using two different threads. If you have one thread reading you can have another writing. The reading thread need to be waiting all the time if you use a blocking socket. You only need a writing thread when you have something to send. A: The TCP/IP channel is full duplex in its nature. You just have to use another thread (on the client side as well as server side) to check the availability of data. I would like to share with you guys the code repo. It is really simple, you can get the idea to make your stuff work. It is an elaborate example. The steps accidentally look like Ordous's solution. https://github.com/khanhhua/full-duplex-chat Feel free to clone! It's my weekend homework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Create Table Error Thanks for all the help everyone provides. I am trying to run my DDL statements and I am getting a weird error. If I copy and paste the ddl it works, but when I try to run it from a *.sql file, it gives an error. Here it is: mysql> source createtable.sql ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREAT E TABLE stars ( id int NOT NULL AUTO_INCREMENT, first_name varchar(50) NOT ' at line 12 I don't know if this makes a difference or not, but it is the second table def in my ddl script. Thanks! EDIT Here is the starting of the DDL. It gives me an error on the second table. CREATE TABLE movies ( id int NOT NULL AUTO_INCREMENT, title varchar(100) NOT NULL default '', year int NOT NULL, director varchar(100) NOT NULL default '', banner_url varchar(200) default '', trailer_url varchar(200) default '', PRIMARY KEY (id) ) CREATE TABLE stars ( id int NOT NULL AUTO_INCREMENT, first_name varchar(50) NOT NULL default '', last_name varchar(50) NOT NULL default '', dob date, photo_url varchar(200) default '', PRIMARY KEY (id) ) A: You'll need to separate your statements with semicolons: CREATE TABLE movies ( id int NOT NULL AUTO_INCREMENT, title varchar(100) NOT NULL default '', year int NOT NULL, director varchar(100) NOT NULL default '', banner_url varchar(200) default '', trailer_url varchar(200) default '', PRIMARY KEY (id) ); CREATE TABLE stars ( id int NOT NULL AUTO_INCREMENT, first_name varchar(50) NOT NULL default '', last_name varchar(50) NOT NULL default '', dob date, photo_url varchar(200) default '', PRIMARY KEY (id) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7585008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Exception Stack Trace difference between Debug and Release mode The code below generates different exception stack trace in both debug and release mode: static class ET { public static void E1() { throw new Exception("E1"); } public static void E2() { try { E1(); } catch (Exception e) { throw; } } public static void Entry() { try { E2(); } catch (Exception e) { Console.WriteLine(e.StackTrace); } } } Result in Debug Mode: at ET.E1() in D:\myStudio\CSharp\CSharp4.0\MyCSharp\ExceptionHandling.cs:line 47 at ET.E2() in D:\myStudio\CSharp\CSharp4.0\MyCSharp\ExceptionHandling.cs:line 58 at ET.Entry() in D:\myStudio\CSharp\CSharp4.0\MyCSharp\ExceptionHandling.cs:line 68 Result in Release Mode: at ET.E2() in D:\myStudio\CSharp\CSharp4.0\MyCSharp\ExceptionHandling.cs:line 55 at ET.Entry() in D:\myStudio\CSharp\CSharp4.0\MyCSharp\ExceptionHandling.cs:line 68 Please note that the first line from the result in Release mode is missing. How to return the offending line in release mode. A: You are probably seeing the result of inlining. When you compile in debug mode, inlining is always turned off (so that debugging makes sense). When you compile in release mode, the compiler will remove certain methods (subject to a lot of rules) and insert their content into all of the call sites. This improves the overall performance of those methods by removing the method call overhead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Borders around groups of plots I've got 16 plots on a page, arranged in a 4x4 grid. I'd like to have a border around each set of 2x2, but can't work out how to do it. I initially used layout(matrix(c(1,2,5,6,3,4,7,8,9,10,13,14,11,12,15,16), 4, 4, byrow=TRUE)) to create the correct layout, but, as far as I know, there's no way of creating margins that extend beyond both the current plot and any subsequent plot that the margin would overlap. The 2nd approach I tried was to use split.screen(), thinking that any oma() settings would only apply to the current screen, however, it appears to apply to the whole window; for example, the following code produces a border at the outer of the whole display area, not screen(1): depths <- c(1:10) split.screen(c(2,2)) screen(1) par(oma=c(1,1,1,1)) plot(depths) box("inner", lty="dotted", col="green") Trying various things with either box("inner") or box("outer") after setting oma settings doesn't create the desired result. Are there any other obvious approaches I should be trying? Thanks, Chris A: Try using box("figure"): depths <- c(1:10) split.screen(c(2,2)) screen(1) box("figure") split.screen(c(2,2)) par(cex=0.5) screen(5) plot(depths) A: Here is a way using layout: layout(matrix(c(1,2,5,6,3,4,7,8,9,10,13,14,11,12,15,16), 4, 4, byrow=TRUE)) replicate(16, hist(rnorm(100))) par(xpd=NA) rect( grconvertX(0.005, from='ndc'), grconvertY(0.505, from='ndc'), grconvertX(0.495, from='ndc'), grconvertY(0.995, from='ndc')) rect( grconvertX(0.005, from='ndc'), grconvertY(0.005, from='ndc'), grconvertX(0.495, from='ndc'), grconvertY(0.495, from='ndc')) rect( grconvertX(0.505, from='ndc'), grconvertY(0.505, from='ndc'), grconvertX(0.995, from='ndc'), grconvertY(0.995, from='ndc')) rect( grconvertX(0.505, from='ndc'), grconvertY(0.005, from='ndc'), grconvertX(0.995, from='ndc'), grconvertY(0.495, from='ndc')) Adjust it to your preferences.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: positioning and font size issues on iPhone Safari I'm trying to make this website: http://501commons.org render the same on iPhone as on other browsers. On Android it works just fine. I have already added the -webkit-text-size-adjust: 100%; to the body style, which helped a little. What is still not working are the following pieces, and I can't figure out why mobile safari is not displaying them properly: * *the top left logo just plain won't show up *the search box in the top right is way too far to the left *the red slogan in the header "A Resource for Nonprofits etc" is too large, too low, and extends beyond the right border *the font of the three nav menu items (Explore the Commons, Volunteer, Invest) is too large Everything else seems ok, at least on the home page. What's weird is that all four problems above occur in the header. Any help would be hugely appreciated! Thanks! A: I figured it out: Top left logo The logo not showing up was due to a strange non-cascading issue. The logo is an <img> tab inside an <a id="portal-logo" ...>. The #portal-logo has a display: inline-block; rule in the next-to-last stylesheet that applies to it, but not in the last one. In other words, this is what we have: #portal-logo { /* in the last CSS file */ margin-bottom: 0; } #portal-logo { /* in the next-to-last CSS file */ display: inline-block; margin: 1.375em 0; } Adding display: inline-block; to the last stylesheet magically makes the logo appear. Then I had to also fiddle with margins, position, top, etc to make it appear in the right place, but all these are in a CSS file that is loaded conditionally only on mobile browsers, so it's ok. It's just really strange that Safari on iOS does not cascade the display: inline-block; style! Search box I made the search box be rendered in the proper place by adding text-align:right; to its container, even though an earlier rule for the same container with text-align:left; makes it work just fine in every other browser. Slogan The slogan required the most tweaking. It's contained in a <div id="slogan">. Here is the old rule: #slogan { color: #EE3524; float: right; font-size: 110%; font-weight: bold; margin-right: -190px; padding-top: 60px; position: relative; z-index: 1; } And here is the new rule that works on mobile safari: #slogan { -webkit-text-size-adjust: 100%; clear:right; color:#ee3524; font-size:17.6px; font-weight: bold; float:right; margin-right:0px; padding-bottom:50px; padding-top:0px; position:relative; text-align:right; z-index:1; } One of the key differences is the absolute font-size in px, instead of as a % value. Menu Items font Likewise, specifying the font-size in px instead of % seemed to be the key here: Old: #portal-globalnav li a { background-color: transparent; color: #FFFFFF; font-size: 1.2em; font-weight: bold; min-width: 3em; padding-bottom: 11px; } New: #portal-globalnav li a { background-color:transparent; color:#fff; font-size:15.4px; font-weight:bold; padding-bottom:11px; min-width:3em; } YMMV!
{ "language": "en", "url": "https://stackoverflow.com/questions/7585020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling FB.login with to get permissions throw an error in IE I'm calling in canvas: FB.login(function(){}, { scope:'publish_stream' }); On Firefox and Chrome shows popup with permission dialog. But on IE there is error (see attach.) : An error occurred with my_app_name. Please try again later. My FB.init: FB.init({ appId: <FB_APP_ID>, status: true, cookie: true, xfbml: true, oauth: true, hideFlashCallback: function(){} }); Earlier (before oauth) I was using code below, it was ok, but it not work wit oauth: FB.ui({ method: 'permissions.request', perms: 'publish_stream', }, function(){}); edit: Information from access token: edit2: If you will find a solution, write answer - if it will work, I'll give you 100 points from my reputation. A: To make it work in IE, you should add channelUrl param to your FB.init with fully qualified url. For example: FB.init({ appId: <FB_APP_ID>, status: true, cookie: true, xfbml: true, channelUrl: 'http://www.example.com/facebook-channel.html' }); The url must point to a page that contains just only one script tag: <script src="http://connect.facebook.net/en_US/all.js"></script> It's important to make channelUrl an absoulte, if you just write channelUrl: '/facebook-channel.html' It wont work. I've got a lot of headache with it, so I hope it'll be helpfull for you or anybody who troubled with it like me before. A: Try to switch _inCanvas to true and see what happens FB._inCanvas = true; A: I also had this problem in the past. You are probably opening it on a domain that is not the same as the one specified as your site domain on the application settings page. A: If you have selected to use sandbox in developers.facebook.com/apps. You should change it to not use. A: Now you’re running on https you will need to reference all assests over https. IE will now show a load of warnings telling the user not all content is sent over the secure connection. This is probably why your popup fails. Set the SDK to load stuff over HTTPS: FB._https = true; FB.init({ /* your app id and stuff */ }); A: maybe it's because IE not setting 3rd party cookies? try adding header('P3P: CP=HONK'); into php file, header function has to come before anything in file is output. A: I done walkaround for that. I'm opening new window with url like: https://www.facebook.com/dialog/oauth?client_id=APPID&scope=publish_stream&redirect_uri=MYPAGE When MYPAGE (which is in my app url) is loaded it simply closes itself. If you will find a solution, write answer - if it will work, I'll give you 100 points from my reputation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: XSS With MongoDB / Django Forms I am running a 100% NoSQL backend (MongoDB) and developing using Django. The application I am building has a lot of different forms, and for a variety of reasons, I am trying to avoid using Django.Forms because they are complicated and do not seem to be very flexible. How worried do I need to be about XSS (as far as I can tell, it is not possible to get a SQL injection when you are using MongoDB) Since most of my forms are being submitted via AJAX...is it enough to just use the Django CRSF tokens + an open source sanitizing lib (http://bitkickers.blogspot.com/2011/01/sanitize-html-with-beautiful-soup.html) with all incoming data? What is the best solution to this problem that does not involve using cleaned_data with Django Forms? A: XSS is a Javascript vulnerability, it is unrelated to SQL injection. To prevent XSS, you need to do the same sensitization, regardless of how your data is stored. Based on its description, using that library and a CSRF token should be sufficient. EDIT While you do not need to worry about SQL injection with MongoDB. If you switch to a relational database, your application will no longer be secure. Sanitizing against XSS injection offers no protection against SQL injection, which the library you mention will not do. A: Actually, MongoDB is vulnerable to SQL intejection as well as NoSQL injection! http://leapar.lofter.com/post/122a03_3028b0
{ "language": "en", "url": "https://stackoverflow.com/questions/7585027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing a SMS message count sequence I am trying to implement a message counter(to count number of characters entered in an SMS), which should count from 160 down to zero(for the first page) increment the second page and then do the count all over again but this time start from 159 down to 0 for subsequent pages. How do I do this int pgNo; public int PageNumber(int length, int maxchar) // this is for the page number { pgNo = ((length / maxchar) + 1); return pgNo; } public int CharCount(int length, int maxchar)// this is for determining the count in that page { int num = length % maxchar; // num is the count of the page if (num == 0 && length == 0) // checking to determine either 0 or maxchar is to be displayed { num = maxchar; // e.g. 0/100 or 100/100 } return maxchar - num; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DIV Overflow:scroll - disable page scroll whilst mouse is inside Is it possible to disable the ability for the mouse wheel to scroll the page whilst it is inside a certain DIV. That way it can only scroll the div and not the page. JQuery libraries are installed so I imagine it would be something along the lines of .scroll() and stop.pagination but I do not know enough about how to do this. Any ideas? Marvellous A: Fixed it. $('.scrollable').mouseenter(function(){ $('body').css('overflow', 'hidden'); }); $('.scrollable').mouseleave(function(){ $('body').css('overflow', 'auto'); }); A: Pure css. For the div you want to scroll: #divId { overflow: scroll; height: someHeight; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Macro does not work in a duplicate worksheet Good morning. I have a Microsoft Excel Macro Enabled Workbook with two worksheets: let's say Sheet1 and Sheet2. In Sheet2 I have a combo box (form control) that works as a table sorter. This table will be also in Sheet2. The combo uses the following code: Option Explicit Sub DropDown4_Change() Dim comboValue As String Dim Key1ColumnIndex As Integer Dim Key2ColumnIndex As Integer 'You can get the name by doing something like this in the immediate window: "? ActiveSheet.Shapes(1).OLEFormat.Object.Name" comboValue = ActiveSheet.Shapes("Drop Down 4").ControlFormat.List(ActiveSheet.Shapes("Drop Down 4").ControlFormat.ListIndex) Select Case comboValue Case "By Keyphrase" Key1ColumnIndex = 18 Key2ColumnIndex = 19 Case "By Region" Key1ColumnIndex = 19 Key2ColumnIndex = 18 Case "Default" Key1ColumnIndex = 1 Key2ColumnIndex = 1 End Select Range("DataValues").sort Key1:=Range("DataValues").Cells(1, Key1ColumnIndex), _ Order1:=xlDescending, Header:=xlNo, DataOption1:=xlSortNormal, _ Key2:=Range("DataValues").Cells(1, Key2ColumnIndex), order2:=xlDescending End Sub This code works like charm in this worksheet. I'm using Aspose Cells for Java to use this Excel Workbook as a template to generate new workbooks with multiple datasheets based in Sheet2 copies (which contains my combo) but the problem is that when I do this, the combo doesn't work anymore as it did in the template. In this line: comboValue = ActiveSheet.Shapes("Drop Down 4").ControlFormat.List(ActiveSheet.Shapes("Drop Down 4").ControlFormat.ListIndex) I get this error: Run-time error '438' Object doesn't support this property or method It looks like ControlFormat is not being recognized as a valid method for the combo shape. This happens whether you use the combo name or the combo index (in this case is always 6). "Drop Down 4" is the right name. I have alerted the name several times in each worksheet and both the index and the name are right. So I hope you guys can help me out. Thank you for your patience and sorry if my English is not clear enough. Feel free to ask questions. A: I figured it out by myself that hard coding the combo name (in this case "Drop Down 4") is a terrible way to do this since Excel assigns new names every time a copy of Sheet2 is added. Although Excel does this, combo names always starts with the word "Drop" (from Drop Down). I modified a little bit the code and made it work: Option Explicit Sub DropDown4_Change() Dim comboValue As String Dim Key1ColumnIndex As Integer Dim Key2ColumnIndex As Integer Dim Index As Integer Dim comboName As String Dim comboName2 As String Dim comboID As Integer 'You can get the name by doing something like this in the immediate window: "? Sheet1.Shapes(1).OLEFormat.Object.Name" For Index = 1 To ActiveSheet.Shapes.Count comboName = ActiveSheet.Shapes(Index).OLEFormat.Object.Name If InStr(comboName, "Drop") > 0 Then 'MsgBox InStr(comboName, "Drop") comboName2 = comboName comboID = Index End If Next comboValue = ActiveSheet.Shapes(comboID).ControlFormat.List(ActiveSheet.Shapes(comboID).ControlFormat.ListIndex) Select Case comboValue Case "By Keyphrase" Key1ColumnIndex = 18 Key2ColumnIndex = 19 Case "By Region" Key1ColumnIndex = 19 Key2ColumnIndex = 18 Case "Default" Key1ColumnIndex = 1 Key2ColumnIndex = 1 End Select Range("DataValues").sort Key1:=Range("DataValues").Cells(1, Key1ColumnIndex), _ Order1:=xlAscending, Header:=xlNo, DataOption1:=xlSortNormal, _ Key2:=Range("DataValues").Cells(1, Key2ColumnIndex), order2:=xlAscending End Sub A: Where is your code located? This worked for me (in a general module)... Sub DoSorting() Dim dd, val Set dd = ActiveSheet.Shapes(Application.Caller) val = dd.ControlFormat.List(dd.ControlFormat.ListIndex) MsgBox val End Sub Copying the sheet did not break it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hybrid between AutoResetEvent and ManualResetEvent I was wondering if there is any hybrid EventWaitHandle that will auto-reset it's state as AutoResetEvent is doing when .Set() is invoked and simultaneously will allow everybody who did .WaitOne() to pass the same as ManualResetEvent is doing. The only one solution i came up is a very ugly one to use ManualResetEvent and to do the follwoing: event.Set(); Thread.Sleep(100); event.Reset(); What is the better way to do this ? Thanks. UPD: Thansk to Hans I came up with the following solution. Looks like it works: class HybridWaitHandle { private bool signal = false; private readonly object locker = new object(); private int blocked = 0; void WaitOne() { lock (locker) { blocked++; while (!signal) Monitor.Wait(locker); blocked--; if (blocked == 0) signal = false; } } void Set() { lock (locker) { signal = true; Monitor.PulseAll(locker); } } } A: Use Monitor.PulseAll() instead. Known as "bounded buffer", sample code is here. Available in .NET 4 as BlockingCollection<>. A: It's a bit hard to say without knowing more about how you're using it, but it sounds like a counted semaphore might fit the problem fairly well. You release the semaphore N times. That lets N threads run. When N threads have been released, the semaphore is reset. Note that technically, this isn't necessarily N separate threads -- it could be 1 thread released N times. As such, if you need/want to assure that you're releasing N separate threads, you may (for one possibility) want to create 2 separate semaphores, alternating between the two for consecutive steps of the process. N threads wait on the first semaphore. When you release it N times, each thread runs, and then waits on the other semaphore. Eventually all the threads will be released by the first semaphore and run, which will reset that semaphore. Then you can do the next processing step using the other semaphore. Note, however, that much of this runs somewhat contrary to how threads tend to work best. You're forcing all the threads to remain in lock-step, but they're generally at their best if you just let them run as "freely" as possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Overflow issue in google chrome See this page in Chrome: http://jsbin.com/onariz/ Now it looks normal: Ok. Now if you have a scroll wheel on your mouse this is where you are going to want to use it. Click with the scroll wheel in the scrollable area of the page and drag your mouse to the corner. Now -- what the heck? Why does the page do this: Why would it do that? How can I prevent that, or is this just a Google Chrome glitch? (I am using Chrome version 14.0.835) A: The issue has been fixed in newer version of Chrome: http://code.google.com/p/chromium/issues/detail?id=89366
{ "language": "en", "url": "https://stackoverflow.com/questions/7585037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ReSharper "Possible NullReferenceException" wrong with FileInfo? I just started using ReSharper and I'm trying to identify why it thinks this code is wrong. var file = new FileInfo("foobar"); return file.Directory.FullName; It highlights file.Directory as a "Possible System.NullReferenceException". I'm not sure how this is possible because the file object can never be null and I can't figure out how the DirectoryInfo object returned from the FileInfo object could ever be null. A: The Directory property can indeed be null. The implementation of the property is roughly public DirectoryInfo Directory { get { string directoryName = this.DirectoryName; if (directoryName == null) { return null; } return new DirectoryInfo(directoryName); } } It can definitely return null. Here is a concrete example var x = new FileInfo(@"c:\"); if (x.Directory == null) { Console.WriteLine("Directory is null"); // Will print }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: localstorage lib that supports like queries I am looking for a javascript lib that lives on top of localstorage that supports like queries. This in itself would be easy to write, but I wouldn't want to reinvent the wheel. What localstorage libs do people use? A: If you want an SQL interface in JavaScript, use the Web SQL Database API. I think most browsers support this. If you want an object database interface, use Lawnchair. This doesn't have a like query, but you could store an object that has an index and use that to query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use data frame as an element in list? I tried to assign a data frame as an element to a list, but after the assignment I found that the data frame has been changed to a list with values from the first column of the data frame. For example the following code : dfm <- data.frame(x=1:2, y=3:4) print(dfm) l <- list() l['Key'] <- dfm print(l) gives the output: x y 1 1 3 2 2 4 $Key [1] 1 2 Is there a way to keep the data frame the way it is in a list ? A: It would benefit you to pay attention to the warning message: Warning message: In l["Key"] <- dfm : number of items to replace is not a multiple of replacement length You want to use [[ instead of [ (read ?Extract to understand why): l[['Key']] <- dfm
{ "language": "en", "url": "https://stackoverflow.com/questions/7585043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to share share widgets pointers with another widgets I have a kind of video player application written in QT, the idea is that I can click in an video frame and the app will get the coords and color information from this exact pixels, so far so good the application already works as spected, but the thing is that I have a control panel wish has an List Widget that I fill with the information from the frame, to do that I need to have some kind of communication between these two widgets, what I do now is use this method to find the mainWindow: QWidget* mainwindow; QWidgetList list = QApplication::topLevelWidgets(); for (int a = 0; a < list.size(); a++) if (list[a]->objectName() == "MainWindow") { mainwindow = list[a]; break; } with this I have access to the mainwindow widget and the mainwindow will serve as a bridge to get access to the pointers of another widget, the problem that I see with this approach is that I need to have an get method to every widget I need access.. Another way to do this is to have an set method in the widget and use a parent widget wish has access to the two widgets I'm looking for to set it right, the problem with this is making methods to this in a parent widget wish doesn't have anything to do with the two methods.. So what I'm asking for is what the best or cleaner method to do this? there is some QT-Way to do this? Thanks! PS: Just to be clear, I'm not talking about SIGNALS and SLOTS, my idea is to use theses, but first I need an pointer to the widget I'm looking for to then connect to it's slots! A: You are trying to do it in lower level code, that is why it is awkward. Neither widget has the context of the other. Just create signal/slots on the two widgets you want to communicate, then have the calling scope connect them after they are created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamic cast/ensure typesafety from collection with varying generics I've decided to use generics in my design, which works fine. Only when I get to abstraction, I got stuck. I'm collecting different instances implementing the same interface with a different generics. To save those in a list, I need to use wildcards, as far as I know. So my current code is like this: import java.util.List; import java.util.ArrayList; public class Main { private List<IView<?>> views = new ArrayList<IView<?>>(); public void addView(IView<?> view) { this.views.add(view); } public void handle() { for (IView<?> view : this.views) { // ## ERROR ## view.render( view.cast(new Object()) ); } } } public interface IView<T> { public T cast(Object entity); public void render(T entity); } public class FirstView implements IView<One> { // .. Added to Main-collection views } public class SecondView implements IView<Two> { // .. Added to Main-collection views } I also tried an alternative approach returning a Class from the IView which I then use to call the class.cast. Same problem. This is NOT accepted by the compiler - The method Render(Capture#2-of ?) in the type IView(Capture#2-of ?) is not applicable for the arguments (Capture#3-of ?). I partially think to understand the problem, but I see no way of solving it. It would be very much appriciated if someone could help me getting going again. A: I don't believe you can assign a value to an ? "typed" variable. An unbounded "?" means "the original type of the variable is unknown", which means there is no known type it's safe to assign to it. It doesn't mean that the actual value of the type parameter is retrieved at runtime. The entire idea of using a generic method to do a cast doesn't make sense in Java generics. The only way to do a cast of an unknown type object in a type-safe way is with an actual cast. The only solution is to get rid of the cast() method, and use raw types: public void handle() { for (IView view : this.views) { view.render(new Object()); } } Assuming the cast() method is only doing casting and not type conversion. If the implementing method that ends up being called is FirstView.render(One object), I believe Java will actually cast the parameter to One. (This can also cause amusing bugs where a ClassCastException is thrown on a line of code with no casts.) If cast() can do a type conversion (in which case, "cast" is a bad name for the operation), that means that every IView must be able to accept Object, in which case it doesn't make much sense have the parameter of render() be the generic type to begin with. The design I would use is something like the following: interface IView<T> { void renderObject(Object o); void render(T); T coerce(Object o); } abstract class ViewBase<T> implements IView<T> { void renderObject(Object o) { render(coerce(o)); } } class FirstView extends ViewBase<One> { // … } encapsulating the "cast" operation. There is no statically typesafe way to work with a collection of objects of different types - in Java, IView<One> and IView<Two> are types as different as String and Integer and there are no safe conversions between the two. A: Since I was wondering about the two captures in code view.render(view.cast(new Object());, I read the appropriate section in Angelika Langer's Generics FAQ. It states that: We cannot call methods through an unbounded wildcard parameterized type that take arguments of the "unknown" type. PERIOD. So using a wildcard declaration prevents the use of parameterized arguments, even if type inference were simple, as in your case :( Hence view.cast(new Object(); is allowed, but view.render(view.cast(new Object()); isn't. Just for clarification via an example, Angelika gives the following: Box<?> box = new Box<String>("abc"); box.contains("abc"); // error where contains takes as argument the parameterized type of Box. She states: The invocation is illegal if performed through a reference variable of type Box<?> . [Defining the contains method as taking an argument of type Object , instead of T , would avoid this effect. In this case the contains method would not take an object of "unknown", but an object of "any" type, and it would be permitted to invoke it through a reference variable of type Box<?> .] So she suggests retrieting back to Object (similarly to the suggestion in my other answer). Btw, she discourages using raw types, as does Josh Bloch in Effective Java's item 23, "Don’t use raw types in new code". A: I do not understand the compiler error, i.e. why view.render(view.cast(new Object()); produces two captures. (I've tried this code with view being final, and the same error message shows). But since IView<One> and IView<Two> only have Object as common type, the way of solving it is using List<IView<Object>>. A: I sort of replaced the casting by returning a typed object (and I slightly changed the example by replacing the new Object with IEntity); public class Main { public static List<IView<? extends IEntity<?>>> views = new ArrayList<IView<? extends IEntity<?>>>(); public static <T extends IEntity<T>> void register(IView<T> view) { Main.views.add(view); } public static void handle() { for (IView<? extends IEntity<?>> view : Main.views) { // ## Error ## /* Bound mismatch: The generic method view(IView<T>) of the type Main * is not applicable for the arguments (IView<capture#1-of ? extends IEntity<?>>). * The inferred type capture#1-of ? extends IEntity<?> is not a valid * substitute for the bounded parameter <T extends IEntity<T>> */ Main.view(view); } } public static <T extends IEntity<T>> void view(IView<T> view) { IKey<T> key = view.getKey(/* Some arg */); T entity = key.getEntity(); view.render(entity); } } public interface IView<T> { public IKey<T> getKey(/* Some args */); public void render(T entity); } public interface IKey<T> { public T getEntity(); } The wildcard is someway bounded, but then it creates another problem (which may actually be the same): Is there a way to check that two wildcards match, i.e.: for (IView<? extends IEntity<?>> view : Main.views) Where ? can only be one (=the same) (generic)type?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Assert multiple change expectations within a single lambda request I have a test like that: lambda { post("/api/users", parameters) }.should change(User,:count).by(1) lambda { post("/api/users", parameters) }.should_not change(ActionMailer::Base, :deliveries) But I want to do it like that: lambda { post("/api/users", parameters) }.should change(User,:count).by(1).and_not change(ActionMailer::Base, :deliveries) Is it possible to do it without the need of two post calls? Thanks A: In my tests I am very strict: I want each test to test only a single thing. So I would always choose the first form, not the second. Secondly I am not sure it is technically possible. The .should expects a block, which is executed before and after the lambda. Anyway, to my knowledge currently rspec does not support this (and imho with good reason). A: I have found a solution to test it. lambda{ lambda { post("/api/users", params) }.should change(User,:count).by(1) }.should change(ActionMailer::Base.deliveries, :count).by(1) A: I recently came across this issue when migrating some request tests over to feature test format for Capybara 2.1, and switching the testing syntax there from should-based to expect-based. To use the original question as the example, I had code like: subject { -> { post("/api/users", parameters) } } it { should change(User,:count).by(1) } it { should_not change(ActionMailer::Base, :deliveries) } Bringing this over to expect syntax in a scenario test presented some issues and yielded this kind of (working) clunkiness (sorry, not a big fan of explicitly nested lambdas/expects): expect(-> { expect(post("/api/users", parameters)).to change(User,:count).by(1) } ).to_not change(ActionMailer::Base, :deliveries) There are some great solutions to this issue in this StackOverflow thread which I tried and succeeded with, but what I ended up doing was simply follow the original format somewhat and split out each statement into its own scenario; something like: feature "Add users via API" do given(:posting_parameters_to_api) { -> { post("/api/users", parameters) } } scenario "foo" do expect(posting_parameters_to_api).to change(User,:count).by(1) end scenario "bar" do expect(posting_parameters_to_api).to_not change(ActionMailer::Base, :deliveries) end end More verbose than the original request spec, but essentially working in the same way. Implementation will likely come down to personal taste.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Run commands in GNU Screen windows from .screenrc Is there a way to send a sequence of commands to GNU Screen windows from my .screenrc? It seems like this should be easy to do: .screenrc: startup_message off screen -t "RAILS SERVER" <send command to last created window> <my alias to cd Rails project> <send command to last created window> rails s screen -t "RAILS CONSOLE" <send command to last created window> <my alias to cd to Rails project> rails c I've gone over the Screen man-page several times, but can't find anything that will <send command to last created window>. Thanks, Max A: It's not a separate command; you just specify the command to run on the line that creates the window. For example (untested): screen -t "RAILS SERVER" sh -c "cd ... ; rails s" A: Keith's answer gets the job done but it ties the window to that process so that as soon as the application is done executing, the window closes. Here's what I wound up doing that worked perfectly: screen -t "RAILS SERVER" stuff "cd $my_rails_directory; rails server^M" screen -t "RAILS CONSOLE" stuff "cd $my_rails_directory; rails console^M" The important part to note here is the ^M character. This isn't actually a ^ followed by an M. This is a raw newline character. In almost any CLI program (vi, emacs, shell), you can press CTRL-V and then press ENTER to generate this character. How does this work? The stuff command types the given string directly into the console. The newline literal at the end actually sends the command off the way you normally would if you typed it yourself. Hope that helps! I've found this approach to be far more stable and reliable than others.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: mysql won't import database dump file on Windows XP I created a data base using mysql. I used MySQLDump to create one database backup file in text format (MySql 5.5 on Windows XP). The database is local on my machine (local host). I am having trouble using the MySQL command to load the dump file to restore the database. I have done the following: * *Research stack overflow for how to do it. I noticed there's a bug using the MySQL command to restore the data from a post. Before I run the command, I DROP the database and CREATE the database using MySQL workbench. *I type the following command in the DOS prompt to restore the database: mysql -u root -p -h localhost -D matlab_data -o < backup.sql *backup.sql is a the backup file in text format created by MySqlDump. *I am then asked for the password which I enter. I get the DOS prompt right away with no error message. I've waited several hours for the command to run and the database is still empty. I have tried various command formats over the last few days. If I enter incorrect data in the command line (non existen file, database, etc), I get an error message. I feel I would not see the DOS prompt until the database is restored. If I don't DROP and CREATE the database, I get an error message. Otherwise, not. Does anybody have any idea what the issue is? I realize that I could be making a stupid mistake. Thank you for your help. A: shell into the mysql console and run the sql file as this If you are already running mysql, you can execute an SQL script file using the source command or . command: mysql> source file_name mysql> \. file_name note that file_name must be an absolut path
{ "language": "en", "url": "https://stackoverflow.com/questions/7585071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Code First with an existing database I have a table in database which points to itself, i.e. parent_id >> category id. This is the ER diagram I have modelled this table like following, but it gives *Error : 'Category': member names cannot be the same as their enclosing type : public class Category { [Key] public int category_id { get; set; } public string category_name { get; set; } public int category_parent { get; set; } public string category_desc { get; set; } public virtual Category Category { get; set; } } How should I model such tables ? A: You have to make category_parent nullable and configure navigational property Category to the scalar property category_parent. Try to use proper naming convensions. public class Category { [Key] [Column("category_id")] public int Id { get; set; } [Column("category_name")] public string Name { get; set; } [Column("category_parent")] public int? ParentId { get; set; } [Column("category_desc")] public string Description { get; set; } [ForeignKey("ParentId")] public virtual Category ParentCategory { get; set; } } A: I think you just need to change the Category property name to something else, so it is not the same as the class name... public virtual Category SubCategory { get; set; } A: public class Category { [Key] public int category_id { get; set; } public string category_name { get; set; } public int category_parent { get; set; } public string category_desc { get; set; } public int parent_category_id { get; set; } <-- ADD & setup as foreign key public virtual Category ParentCategory { get; set; } <-- Change name public virtual ICollection<Category> Categories { get; set; } } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Category>.HasMany(cat => cat.Categories) .WithRequired() .HasForeignKey(cat => cat.parent_category_id); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to prevent a certain mdichild form from getting focus/activation when switching between other mdichild forms using Ctrl+Tab? C# In my mdi application i have four mdichild forms, one of them is used as a background and holding some controls.. How to prevent this background mdichild form from getting focus/activation when switching between other mdichild forms using Ctrl+Tab? In other word how to skip this background mdi child form from the Ctrl+Tab sequence? and also make its z-order to be the last one so that it doesn't hide other mdichild forms when switching between them? thanks in advance. A: By overriding Form.ProcessCmdKey and skip the background form. protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if ((keyData & Keys.Tab) == Keys.Tab && (keyData & Keys.Control) == Keys.Control) { Form nextForm = GetNexMdiChildForm(); if (nextForm != null) { nextForm.Activate(); return false; } } return base.ProcessCmdKey(ref msg, keyData); } private Form GetNexMdiChildForm() { //get current form index Form currentForm = this.ActiveMdiChild; int currentFormIndex = Array.IndexOf(this.MdiChildren, currentForm); //get next form index int nextFormIndex = currentFormIndex + 1; if (this.MdiChildren.Length == nextFormIndex) { nextFormIndex = 0; } //check if next form is Form 3 if (this.MdiChildren[nextFormIndex] == background_mdichild_form ) { nextFormIndex++; if (this.MdiChildren.Length == nextFormIndex) { nextFormIndex = 0; } } return MdiChildren[nextFormIndex]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I only display records which have not yet reached their expiry date (field)? In my app I can add offers and give them a start and end date, the offers are displayed as partials. How can I go about only displaying them if the start date is todays date or earlier and the end date has not yet been reached? So far I have: offer partial <% if offer.date_from > Date.today && offer.date_to < Date.today %> <div class="offer_partial"> <div class="offer_title"> <%= offer.title %> </div> <div class="offer_body"> <%= offer.body %> </div> </div> <% end %> But this gives a undefined method `>' for nil:NilClass error. Is it even ok to do these kind of checks in the view? Thanks very much for any help! A: To answer your second question first, no, you should build a collection of the Offer models through a query in the controller, thereby leaving the view to just iterate through that collection and render the HTML. Also, the if block doesn't do what you want it to. You said "Today's date or earlier", but you're checking for today's date or later. It seems that you've inverted the logic. The error you're getting means that date_from is nil. Are you validating those fields or are they allowed to have a nil value? This is how I would set that collection up: class Offer < AR::Base scope :end_date_not_reached, where("date_from <= ?", Date.today).where("date_to > ?", Date.today) end In the controller: @offers_in_progress = Offer.end_date_not_reached In the view: <% @offers_in_progress.each do |offer| %> <!-- stuff here --> <% end %> Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to delete files from DDMS by programmatically? I've listed the File from DDMS using final String[] files = fileList(); lv = (ListView)findViewById(R.id.list); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, files)); Now, i'm in need to delete a particular file from this list. I've a method on Button for to this deleting process delete_Click(View view) Can anyone know how to do this with this method(). Thanks in Advance. A: There is a problem of multiple choice. You have to look at this Click here
{ "language": "en", "url": "https://stackoverflow.com/questions/7585083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect the status of a printer paper i need to get paper status information from a printer. I have a list of esc/pos commands. I'm trying to send these comands with escape function http://msdn.microsoft.com/en-us/library/windows/desktop/dd162701%28v=vs.85%29.aspx This is my code type TPrnBuffRec = record bufflength: Word; Buff_1: array[0..255] of Char; end; procedure TFTestStampa.SpeedButton2Click(Sender: TObject); var Buff: TPrnBuffRec; BuffOut: TPrnBuffRec; TestInt: Integer; cmd : string; begin printer.BeginDoc; try TestInt := PassThrough; if Escape(Printer.Handle, QUERYESCSUPPORT, SizeOf(TESTINT), @testint, nil) > 0 then begin cmd := chr(10) + chr(04) + '4'; StrPCopy(Buff.Buff_1, cmd); Buff.bufflength := StrLen(Buff.Buff_1); Escape(Printer.Canvas.Handle, Passthrough, 0, @buff, @buffOut); ShowMessage( conver(strPas(buffOut.Buff_1)) ); end finally printer.EndDoc; end; function TFTestStampa.Conver(s: string): String; var i: Byte; t : String; begin t := ''; for i := 1 to Length(s) do t := t + IntToHex(Ord(s[i]), 2) + ' '; Result := t; end; Problem is with different cmds I obtain always the same string .... Can you give me an example of escape function with last parameter not nill ? Alternatives to obtain paper status ? A: I suppose you are using Delphi 2009 above and you used this source for your example, so your problem might be caused by Unicode parameters. In Delphi since version 2009, string type is defined as UnicodeString whilst in Delphi 2009 below as AnsiString, the same stands also for Char which is WideChar in Delphi 2009 up and AnsiChar below. If so, then I think you have a problem at least with your buffer data length, because Char = WideChar takes 2 bytes and you were using StrLen function which returns the number of chars what cannot correspond to the data size of number of chars * 2 bytes. I hope this will fix your problem, but I can't verify it, because I don't have your printer :) type TPrinterData = record DataLength: Word; Data: array [0..255] of AnsiChar; // let's use 1 byte long AnsiChar end; function Convert(const S: AnsiString): string; var I: Integer; // 32-bit integer is more efficient than 8-bit byte type T: string; // here we keep the native string data type begin T := ''; for I := 1 to Length(S) do T := T + IntToHex(Ord(S[I]), 2) + ' '; Result := T; end; procedure TFTestStampa.SpeedButton2Click(Sender: TObject); var TestInt: Integer; Command: AnsiString; BufferIn: TPrinterData; BufferOut: TPrinterData; begin Printer.BeginDoc; try TestInt := PASSTHROUGH; if Escape(Printer.Handle, QUERYESCSUPPORT, SizeOf(TestInt), @TestInt, nil) > 0 then begin Command := Chr(10) + Chr(04) + '4'; StrPCopy(BufferIn.Data, Command); BufferIn.DataLength := StrLen(Command); FillChar(BufferOut.Data, Length(BufferOut.Data), #0); BufferOut.DataLength := 0; Escape(Printer.Canvas.Handle, PASSTHROUGH, 0, @BufferIn, @BufferOut); ShowMessage(Convert(StrPas(BufferOut.Data))); end finally Printer.EndDoc; end; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7585084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Multithreaded use of Regex Given the following from MSDN: Regex objects can be created on any thread and shared between threads. I have found that for performance, it is better NOT to share a Regex instance between threads when using the ThreadLocal class. Please could someone explain why it runs approximately 5 times faster for a thread local instance? Here are the results (on an 8 core machine): Using Regex singleton' returns 3000000 and takes 00:00:01.1005695 Using thread local Regex' returns 3000000 and takes 00:00:00.2243880 Source Code: using System; using System.Linq; using System.Threading; using System.Text.RegularExpressions; using System.Diagnostics; namespace ConsoleApplication1 { class Program { static readonly string str = new string('a', 400); static readonly Regex re = new Regex("(a{200})(a{200})", RegexOptions.Compiled); static void Test(Func<Regex> regexGettingMethod, string methodDesciption) { Stopwatch sw = new Stopwatch(); sw.Start(); var sum = Enumerable.Repeat(str, 1000000).AsParallel().Select(s => regexGettingMethod().Match(s).Groups.Count).Sum(); sw.Stop(); Console.WriteLine("'{0}' returns {1} and takes {2}", methodDesciption, sum, sw.Elapsed); } static void Main(string[] args) { Test(() => re, "Using Regex singleton"); var threadLocalRe = new ThreadLocal<Regex>(() => new Regex(re.ToString(), RegexOptions.Compiled)); Test(() => threadLocalRe.Value, "Using thread local Regex"); Console.Write("Press any key"); Console.ReadKey(); } } } A: Positing my investigation results. Let's ILSpy Regex. It contains a reference to RegexRunner. When Regex object is matching something it locks its RegexRunner. If there is another concurrent request to the same Regex object another temporary instance of RegexRunner gets created. RegexRunner is expensive. More threads are sharing Regex object the more chance to waste time creating temporary RegexRunners. Hope Microsoft will fix that addressing the era of massive parallelism. Another thing: static members of Regex class taking pattern string as a parameter (like Match.IsMatch(input, pattern)) also must perform badly when the same pattern is being matched in different threads. Regex maintains a cache of RegexRunners. Two concurrent Match.IsMatch() with the same pattern will try to use the same RegexRunner and one thread will have to create temporary RegexRunner. Thanks Will for letting me know how you handle here questions that topic-starter have found an answer for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: jQuery is not a function I am trying to install a simple news ticker jQuery plugin to the home page of a website built using Joomla 1.5 No matter what I do, I always get the error jQuery("#js-news").ticker is not a function despite the files are loaded correctly and the $ sign is replaced with jQuery to avoid conflicts with Mootools. I also tried to use the Cycle plugin first, but I was getting the same error. The weird thing is I am using the jQuery library (1.6.2) without any problem. link here Any suggestion? Thanks A: Try adding this to your first line of code: jQuery.noConflict(); A: I would try to wrap it in a document.ready() as well - defining jQuery last is perfect but remember to call noConflict(). Consider the following : $j = jQuery.noConflict(); $j(document).ready(function(){ $j('#js-news').ticker(); }); Or alternatively - Thanks @Kevin B $j = jQuery.noConflict(); $j(document).ready(function($){ $('#js-news').ticker(); }); A: It looks to me as if you need to use $.noConflict(); ( http://api.jquery.com/jQuery.noConflict/ ) I get the error with the jQuery or $ on your page, unless I execute the noConflict method. It seems the ticker plugin is not executing because of the mootools conflict.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: google-style file for C++ for emacs I use the google-style file for emacs. It also looks like a good one to start learning some emacs lisp, not that long. However there is sth I am trying configure in that file, maybe some already did that before, for coding a class, I wrote, namespace A { class A_A { public: A_A(); private: int a; }; } however public/private keywords are not at the right places, I did not understand why it places them like this out of the box, how can fix this? I am not good at emacs lisp yet unfortunately. EDIT: I wanted to have sth like namespace A { class A_A { public: A_A(); private: int a; }; } A: To get indent you like use such debug techniques: (setq c-echo-syntactic-information-p t) When you press TAB for indenting you will see something like: syntax: ((inclass 33) (access-label 33)) As you can see access-label identify how indent priv/pub modifiers. So change to what you want: (defconst my-c-style '( (c-tab-always-indent . t) (c-offsets-alist . ( (access-label . /) ; XXXXXX LOOK HERE!!!!!!! )) ) "My C Programming Style") (defun my-c-mode-style-hook () (c-add-style "my" my-c-style t) ;; If set 'c-default-style' before 'c-add-style' ;; "Undefined style: my" error occured from 'c-get-style-variables'. (setq c-default-style '( (java-mode . "my") (c-mode . "my") (csharp-mode . "my") (c++-mode . "my") (other . "my") )) ) (add-hook 'c-mode-common-hook 'my-c-mode-style-hook) In example I remove half-level indent as inclass add one full indent (to get 1/2 of indent. For offset syntax read C-h v c-offsets-alist RET. For example: If OFFSET is one of the symbols `+', `-', `++', `--', `*', or `/' then a positive or negative multiple of `c-basic-offset' is added to the base indentation; 1, -1, 2, -2, 0.5, and -0.5, respectively. A: Probably nowadays a good solution is given by the config file provided in Github by Google. In the repository styleguide there is the config file google-c-style.el that, as described in the file, ;; Provides the google C/C++ coding style. You may wish to add ;; `google-set-c-style' to your `c-mode-common-hook' after requiring this ;; file. For example: ;; ;; (add-hook 'c-mode-common-hook 'google-set-c-style) ;; ;; If you want the RETURN key to go to the next line and space over ;; to the right place, add this to your .emacs right after the load-file: ;; ;; (add-hook 'c-mode-common-hook 'google-make-newline-indent) The file is also distributed via MELT package system as google-c-style.el.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java time class Ok this is homework and i am struggling a bit, i cant figure out what to pass in toString method and i am not quite sure my methods for getting the current and the elapsed time are correct. I then have to pass this to the main method and display the times in output statements. That is not really my problem, i can only have 3 variables, how can i figure out the elapsed time from the current time and still hold the original hour, second, minute variables without changing them so all data from both time constructors are held in those variables? I hope i am making sense.Thanks for any input package chapter_10; public class Time { private long hour; private long minute; private long second; public void time() { long second = System.currentTimeMillis(); long minute = System.currentTimeMillis(); long hour = System.currentTimeMillis(); } public void setTime(long elapsedTime){ long millisecond = System.currentTimeMillis(); long second = millisecond / 1000; long minute = second / 60; long hour = minute /60; } public long getHour() { return hour; } public long getMinute() { return minute; } public long getSecond() { return second; } public String toString(){ return // what should i return here, String.towhat? } } Here is the assignment, just to clarify. Time class: give it 3 private data members for hour, minute, and second. Use type long or int. If you use int you must cast inside the ctors. add a no-arg ctor that uses code like that in Listing 2.6 on p38 to assign values to hour, minute, and second from the current time. add another ctor that will take a single long parameter named elapseTime (better would be elapsedTime), a number for milliseconds since the Unix epoch date. this second ctor will also use code as per Listing 2.6 to set the data members for that elapsed time since the epoch. a third ctor is not necessary. add a getter for each data member. Each getter will require only a single statement. Getters are needed because the data members are private. add a toString method that returns the hours, minutes, and seconds for a Time object. main class: in the main method create a Time object with the no-arg ctor. create a few time objects with the other ctor. display the times for each object you instantiate. A: You aren't setting those private data members properly at all. The values in the time method shadow the private data members. Worry about that, then fix the toString(). A: Well, toString generally is a String that represents your object in a unique way. Since your object here is Time, so an unique time is represented by it's time. So, if you write something like: public String toString(){ return getHour() + ":" + getMinute() + ":" + getSecond() + ":" + getMillisecond(); } This would be a nice implementation of the tostring method, since this represents with success what is this object. PS: Your millisecond nor all your fields are being stored in your class as a field! Check that out! Edit: Now I noticed, your code won't work at all. The System.currentTimeMillis() returns time in UTC. That means, the calculation you are doing won't work at all. You must first convert from UTC to a valid millisecond approach. Consider using the Date/Calendar class for working with time. A: I can't guarantee that I understand your questions completely/correctly. Have you considered storing the actual result of call to currentTimeMillis()? You can then have three variables: long startTime; long endTime; long elapsedTime; and then extracting the relevant pieces when they are needed?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding A Column To Access Database, Visual Studio Not Updating Column List I have a project with a dataset of an access database file. I opened up the DB file in access, added a column to a table, closed VS2010 & reopened and still it is telling me that the new column is not there in the Data Sources window, even after clicking the refresh button. I have re-opened Access and confirmed that I am editing the correct file & that the change made is there afterwards still but still no change in VS. Any ideas what I have done wrong here / how to get VS to update with the correct table details?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EasyMock to test SecurityException I am trying to use easyMock to write a test, that tests SecurityException in the following code. eg. for NumberFormatException I use the below. EasyMock.expect(mockEntityManager.find(UserProfile.class,"abc")).andThrow(new NumberFormatException()); Any ideas on what to expect to throw SecurityException? public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) { EntityManager entityManager = (EntityManager)Component.getInstance("entityManager"); if (s == null || s.equals("null")) { return null; } else { try { long i = Long.parseLong(s); return entityManager.find(UserProfile.class, i); } catch (NumberFormatException e) { logger.error(e); } catch (SecurityException e) { logger.error(e); } } return null; } A: I have the feeling that you haven't written that code, and that's why you're wondering what might throw SecurityException. The answer is nothing, as long as you're using a good implementation of EntityManager. The documented version of EntityManager.find()enter link description here doesn't throw SecurityException. BUT if you're running that code inside a J2EE app server that uses a custom version of EntityManager, it could be that it throws that exception... But I don't think it should. A: Thanks for your responses..here is what I did to expect SecurityException. MyClass abc = new MyClass(); EasyMock.expect(mockEntityManager.find(MyClass.class,111L)).andThrow(new SecurityException()); EasyMock.replay(mockEntityManager); Object target = abc.getAsObject(mockFacesContext, mockUiComponent,"111"); Assert.assertEquals(null, target);
{ "language": "en", "url": "https://stackoverflow.com/questions/7585098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Style with image as parameter I wonder how can i parametrize an image source inside an style, and this style is used inside another style. Let me try to be more clear. I defined an style for buttons, the style has an image. Then i have another style. On that style, I have two buttons (i´ve applied the button style), and i want to able to change the image of each button. But i can´t get it work. The first part of the code defines a style for a button the idea is to change the image as needed to represent an action. This is my code: <Style x:Key="InnerInscribirseButtonMatch" TargetType="{x:Type Button}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <ControlTemplate.Resources> <Storyboard x:Key="MouseOver"> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="Blur_back"> <EasingDoubleKeyFrame KeyTime="0" Value="0"/> <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="-0.666"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="Blur_back"> <EasingDoubleKeyFrame KeyTime="0" Value="0"/> <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="0.705"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="contentPresenter"> <EasingDoubleKeyFrame KeyTime="0" Value="0"/> <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="2.665"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="contentPresenter"> <EasingDoubleKeyFrame KeyTime="0" Value="0"/> <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="2.999"/> </DoubleAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="Blur_back"> <EasingColorKeyFrame KeyTime="0" Value="#FFE9E9A7"/> <EasingColorKeyFrame KeyTime="0:0:0.1" Value="#FFF1F0DD"/> </ColorAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="image"> <EasingDoubleKeyFrame KeyTime="0" Value="0"/> <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="3"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="image"> <EasingDoubleKeyFrame KeyTime="0" Value="0"/> <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="4"/> </DoubleAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="Back"> <EasingColorKeyFrame KeyTime="0" Value="#FF356AA0"/> <EasingColorKeyFrame KeyTime="0:0:0.1" Value="#FF1264B6"/> </ColorAnimationUsingKeyFrames> </Storyboard> </ControlTemplate.Resources> <Grid> <Rectangle x:Name="Blur_back" RadiusY="5" RadiusX="5" Stroke="#FF3F4C6B" StrokeThickness="2" Fill="#FF5B8BBC" Margin="-4.5,-4" Opacity="0" RenderTransformOrigin="0.5,0.5"> <Rectangle.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Rectangle.RenderTransform> <Rectangle.Effect> <BlurEffect Radius="7"/> </Rectangle.Effect> </Rectangle> <Rectangle x:Name="Back" RadiusY="5" RadiusX="5" Stroke="#FF3F4C6B" StrokeThickness="2" Fill="#FF356AA0"/> <Rectangle x:Name="Glass" RadiusY="5" RadiusX="5" Stroke="#FF3F4C6B" StrokeThickness="2" Fill="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.15" Margin="0,0,0,61" RenderTransformOrigin="0.5,0.5"> <Rectangle.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Rectangle.RenderTransform> </Rectangle> <ContentPresenter x:Name="contentPresenter" HorizontalAlignment="Center" RecognizesAccessKey="True" VerticalAlignment="Bottom" RenderTransformOrigin="0.5,0.5" Margin="13.766,0,15.766,14.351" d:LayoutOverrides="Width"> <ContentPresenter.Effect> <DropShadowEffect Opacity="0.77"/> </ContentPresenter.Effect> <ContentPresenter.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </ContentPresenter.RenderTransform> </ContentPresenter> <Image x:Name="image" Margin="12,3.5,17,22.5" RenderTransformOrigin="0.5,0.5" Width="64" Height="64" Source="apuntarlista.png"> <Image.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Image.RenderTransform> </Image> </Grid> <ControlTemplate.Triggers> <EventTrigger RoutedEvent="Mouse.MouseDown"> <BeginStoryboard x:Name="MouseOver_BeginStoryboard" Storyboard="{StaticResource MouseOver}"/> </EventTrigger> <EventTrigger RoutedEvent="Mouse.MouseUp"> <StopStoryboard BeginStoryboardName="MouseOver_BeginStoryboard"/> </EventTrigger> <EventTrigger RoutedEvent="Mouse.MouseLeave"> <StopStoryboard BeginStoryboardName="MouseOver_BeginStoryboard"/> </EventTrigger> <Trigger Property="IsCancel" Value="False"/> <Trigger Property="IsFocused" Value="True"/> <Trigger Property="IsDefaulted" Value="True"/> <Trigger Property="IsMouseOver" Value="True"/> <Trigger Property="IsPressed" Value="True"/> <Trigger Property="IsEnabled" Value="False"/> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> well, this is the part i want to customize. The source part: Source="apuntarlista.png" <Image x:Name="image" Margin="12,3.5,17,22.5" RenderTransformOrigin="0.5,0.5" Width="64" Height="64" Source="apuntarlista.png"> <Image.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Image.RenderTransform> </Image> here, you have the second style <Style x:Key="ButtonStyleCambiable" TargetType="{x:Type Button}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Grid Height="130" Width="Auto" Margin="50,0,-315,0"> <Rectangle x:Name="background" Fill="{Binding BackgroundColor, FallbackValue=#FF932424}" RadiusY="15" RadiusX="15" Stroke="{Binding BorderBackgroundColor, FallbackValue=#FF954444}" StrokeThickness="3" Height="130" Width="375" Margin="0" HorizontalAlignment="Left" d:LayoutOverrides="HorizontalAlignment"/> <Rectangle x:Name="white_glass" Fill="White" RadiusY="15" RadiusX="15" Stroke="{x:Null}" StrokeThickness="3" Opacity="0.07" Height="65" VerticalAlignment="Top" Width="375" Margin="0" HorizontalAlignment="Left" ClipToBounds="True" d:LayoutOverrides="HorizontalAlignment"/> <TextBlock HorizontalAlignment="Left" Margin="13,13.901,0,0" TextWrapping="Wrap" Width="272" VerticalAlignment="Center" FontSize="48" FontFamily="Cambria" Foreground="White" Text="{Binding Description, FallbackValue=50/100}" FontWeight="Bold"> <TextBlock.Effect> <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/> </TextBlock.Effect></TextBlock> <TextBlock HorizontalAlignment="Left" Margin="206,14.192,0,0" TextWrapping="Wrap" Width="122" VerticalAlignment="Top" FontSize="24" FontFamily="Cambria" Foreground="White" FontWeight="Bold" Text="En espera: " d:LayoutOverrides="HorizontalAlignment"> <TextBlock.Effect> <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/> </TextBlock.Effect></TextBlock> <TextBlock HorizontalAlignment="Left" Margin="210,50.123,0,51.739" TextWrapping="Wrap" Width="109" VerticalAlignment="Stretch" FontSize="24" FontFamily="Cambria" Foreground="White" FontWeight="Bold" Text="Libres: " d:LayoutOverrides="HorizontalAlignment, Height"> <TextBlock.Effect> <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/> </TextBlock.Effect></TextBlock> <TextBlock HorizontalAlignment="Left" Margin="292,51.123,0,50.739" TextWrapping="Wrap" Width="130" VerticalAlignment="Stretch" FontSize="24" FontFamily="Cambria" Foreground="White" FontWeight="Bold" Text="{Binding FreeSits, FallbackValue=10}" d:LayoutOverrides="HorizontalAlignment, Height"> <TextBlock.Effect> <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/> </TextBlock.Effect></TextBlock> <TextBlock HorizontalAlignment="Left" Margin="329,15.192,0,0" TextWrapping="Wrap" Width="96" VerticalAlignment="Top" FontSize="24" FontFamily="Cambria" Foreground="White" FontWeight="Bold" Text="{Binding PeopleWaiting, FallbackValue=1}" d:LayoutOverrides="HorizontalAlignment"> <TextBlock.Effect> <DropShadowEffect ShadowDepth="3" Opacity="0.35" BlurRadius="13"/> </TextBlock.Effect></TextBlock> <Button Content="Inscribir" HorizontalAlignment="Left" Margin="381,2,0,2" Style="{DynamicResource InnerInscribirseButtonMatch}" Width="129" FontFamily="Calibri" FontSize="24" Foreground="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.85"/> <Button Content="Info" HorizontalAlignment="Left" Margin="518,2,0,2" Style="{DynamicResource InnerInscribirseButtonMatch}" Width="129" FontFamily="Calibri" FontSize="24" Foreground="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.85"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsFocused" Value="True"/> <Trigger Property="IsDefaulted" Value="True"/> <Trigger Property="IsMouseOver" Value="True"/> <Trigger Property="IsPressed" Value="True"/> <Trigger Property="IsEnabled" Value="False"/> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> there i have: <Button Content="Inscribir" HorizontalAlignment="Left" Margin="381,2,0,2" Style="{DynamicResource InnerInscribirseButtonMatch}" Width="129" FontFamily="Calibri" FontSize="24" Foreground="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.85"/> <Button Content="Info" HorizontalAlignment="Left" Margin="518,2,0,2" Style="{DynamicResource InnerInscribirseButtonMatch}" Width="129" FontFamily="Calibri" FontSize="24" Foreground="White" Height="Auto" VerticalAlignment="Stretch" Opacity="0.85"/> as you can see both buttons use Style="{DynamicResource InnerInscribirseButtonMatch}" but i want each one to have a diferent image. How can i do that? I Hope to be clear. Thanks in advance. A: I think that you can define Button.DataContext property, for example, by string, and bind the Image.Source property with control DataContext. <Button DataContext="apuntarlista.png" Style="{DynamicResource InnerInscribirseButtonMatch}" /> <Button DataContext="apuntarlista2.png" Style="{DynamicResource InnerInscribirseButtonMatch}" /> And in your inner style: <Image x:Name="image" RenderTransformOrigin="0.5,0.5" Width="64" Height="64" Source="{Binding}"> <Image.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Image.RenderTransform> </Image> A: IMHO i would always try to not change the style so that is needs specific input. Thats what the Content is for and the ContentTemplate. But of course this is difficult sometimes. We use for these cases an AttachedProperty So make a new static class name it for example ButtonIconService. give it an Attached Property named Icon set it on your buttons like <Button ButtonIconService.Icon="pathToIcon.png" <Button ButtonIconService.Icon="pathToOtherIcon.png" and bind it to your Image in your template. <Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(ButtonInfoService.Icon)}}" im not sure at the moments if the brackets around ButtonInfoService.Icon are needed? Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Turn on screen on device How can I turn the sceen on ? I tried something like this adb -d shell am broadcast -a android.intent.action.SCREEN_ON It really should work, I send broadcast intent it is received by the system, but the screen doesn't turn on I do not understand what is the problem, is it possible to turn the screen of the device by code ? I mean with software ? Cause it seems like the turning on of the screen is done just by the hardware button press . . . at least I got that felling , am I wrong ? A: I could be wrong about this, but... You shouldn't think of broadcasts as something to send to get things done, but instead think of them as things that are sent when things are done. I think the system sends 'android.intent.action.SCREEN_ON' when screen is goes on, but sending 'android.intent.action.SCREEN_ON' does not necessarily make the screen go on. I hope this makes sense. For the answer, you can find it in... * *Calling hidden API in android to turn screen off *turn the screen on/off in Android with a shake A: adb shell input keyevent KEYCODE_POWER Works to turn on screen (when display is off) Works to turn off screen (when display is on/awake) A: For Android 5.0 and above: adb shell input keyevent KEYCODE_WAKEUP or adb shell input keyevent 224 KEYCODE_WAKEUP Key code constant: Wakeup key. Wakes up the device. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already awake. https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_WAKEUP Note: KEYCODE_POWER has been added in API level 1, while KEYCODE_WAKEUP has been added in API level 20! A: The command to toggle the screen on/off is: adb shell input keyevent 26 This condensed command is preferred because it allows you to use it in scripts. Cheers! A: u can turn it on/off if u do like: adb shell @shell: input keyevent 26 @shell: (enter or via hidden command empty line) @shell: exit this worked for me on some android versions ;)(NOTE: this will turn the screen on and off, depends on the actual screen state) To detect the current state of the screen u can use the following ways:Android < 5.x.xadb shell dumpsys input_methodIn the output search for mScreenOn=true/false Android >= 5.x.xadb shell dumpsys displayIn the output search for mScreenState=ON/OFF In my scripts i use this \s{0,}mScreen(State|On)=(?<STATE>(true|false|on|off))\s{0,} (Compiled|IgnoreCase|ExplicitCapture) regular expression for both outputs to detect the current state. EDIT (16.03.2018): There is also another way to detect the screen state, it works since Android 3.0. The dumpsys window policy command will give us all we need. - In the output search for mScreenOn(Fully)?=(?<STATE>(true|false)). There are also other useful informations like: * *mUnrestrictedScreen (value is like: (0,0) 768x1280) *mRestrictedScreen (value is like: (0,0) 768x1184) Regards, k1ll3r8e A: this works in android 12 #!/bin/bash screenState=$(adb shell dumpsys window policy | grep screenState=SCREEN_STATE_ | cut -c 32-) if [ "$screenState" == "OFF" ]; then adb shell input keyevent KEYCODE_POWER fi
{ "language": "en", "url": "https://stackoverflow.com/questions/7585105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to prevent webkit from going back in history when scrolling horizontally? The title should say it all. Chrome + safari goes back in history when scrolling to the left using a trackpad, very annoying if you expect a horizontal scroll. I was hoping to be able to disable it using: document.addEventListener('mousewheel', function(e) { e.preventDefault(); }); But that didn’t work. Neither did a return false; from the handler. I think this is a OSX Lion specific issue, but I’m not sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CGRect to UIImage I have this code: CGRect visibleRect; visibleRect.origin = mainViewController.scrollView.contentOffset; visibleRect.size = mainViewController.scrollView.bounds.size; I want to store the content inside visibleRect in a UIImage. Is that possible? A: This code may work: UIGraphicsBeginImageContext(visibleRect.size); CGContextTranslateCTM(UIGraphicsGetCurrentContext(), visibleRect.origin.x, visibleRect.origin.y); [mainViewController.scrollView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); A: You can't store a UIImage in the CGRect. You'd do something like the following CGRect visibleRect; visibleRect.origin = mainViewController.scrollView.contentOffset; visibleRect.size = mainViewController.scrollView.bounds.size; UIImageView* img = [[UIImageView alloc] init]; [img setFrame:visibleRect]; [img setImage:[UIImage imageNamed:@"Your-img"]]; [[self view] addSubview:img]; [img release];
{ "language": "en", "url": "https://stackoverflow.com/questions/7585112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WPF dependency between controls I have 3 textboxes their visibility depends on checkbox. I want to set IsEnabled = false on all textboxes, when checkbox.IsChecked = false and IsEnabled = true when IsChecked=true. How can I achieve this dependency in XAML? thanks. A: you can bind between named elements, and as long as you are binding to dependency properties, the binding will reflect any changes <TextBox IsEnabled="{Binding ElementName=SomeCheckBox, Path=IsChecked}" /> A: Bind the IsEnabled property to the IsChecked property on the CheckBox. <TextBox IsEnabled="{Binding ElementName=NameOfCheckBox, Path=IsChecked}" /> If your goal is to then tie that bool value to Visibility as your question suggests, you would then need to also leverage a converter, such as the BooleanToVisibilityConverter. <TextBox Visibility="{Binding IsChecked, ElementName=NameOfCheckBox, Converter={StaticResource BoolToVisConverter}}" /> A: <StackPanel> <CheckBox Name="Checker" /> <TextBox IsEnabled="{Binding ElementName=Checker, Path=IsChecked}" /> <TextBox IsEnabled="{Binding ElementName=Checker, Path=IsChecked}" /> <TextBox IsEnabled="{Binding ElementName=Checker, Path=IsChecked}" /> </StackPanel>
{ "language": "en", "url": "https://stackoverflow.com/questions/7585115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML Mixed Encodings? First I would like to say thank you for the help in advance. I am currently writing a web crawler that parses HTML content, strips HTML tags, and then spell checks the text which is retrieved from the parsing. Stripping HTML tags and spell checking has not caused any problems, using JSoup and Google Spell Check API. I am able to pull down content from a URL and passing this information into a byte[] and then ultimately a String so that it can be stripped and spell checked. I am running into a problem with character encoding. For example when parsing http://www.testwareinc.com/... Original Text: We’ve expanded our Mobile Web and Mobile App testing services. ... the page is using ISO-8859-1 according to meta tag... ISO-8859-1 Parse: Weve expanded our Mobile Web and Mobile App testing services. ... then trying using UTF-8... UTF-8 Parse: We�ve expanded our Mobile Web and Mobile App testing services. Question Is it possible that HTML of a webpage can include a mix of encodings? And how can that be detected? A: It looks like the apostrophe is coded as a 0x92 byte, which according to Wikipedia is an unassigned/private code point. From there on, it looks like the browser falls back by assuming it's a non-encoded 1-byte Unicode code point : +0092 (Private Use Two) which appears to be represented as an apostrophe. No wait, if it's one byte, it's more probably cp1252: Browsers must have a fallback strategy according to the advertised CP, such as ISO-8859-1 -> CP1252. So no mix of encoding here but as others said a broken document. But with a fallback heuristic that will sometimes help, sometimes not. If you're curious enough, you may want to dive into FF or Chrome's source code to see exactly what they do in such a case. A: Having more than 1 encoding in a document isn't a mixed document, it is a broken document. Unfortunately there are a lot of web pages that use an encoding that doesn't match the document definition, or contains some data that is valid in the given encoding and some content that is invalid. There is no good way to handle this. It is possible to try and guess the encoding of a document, but it is difficult and not 100% reliable. In cases like yours, the simplest solution is just to ignore parts of the document that can't be decoded. A: Apache Tika has an encoding detector. There are also commercial alternatives if you need, say, something in C++ and are in a position to spend money. I can pretty much guarantee that each web page is in one encoding, but it's easy to be mistaken about which one. A: seems like issue with special characters. Check this StringEscapeUtils.escapeHtml if it helps. or any method there edited: added this logic as he was not able to get code working public static void main(String[] args) throws FileNotFoundException { String asd = "’"; System.out.println(StringEscapeUtils.escapeXml(asd)); //output - &#8217; System.out.println(StringEscapeUtils.escapeHtml(asd)); //output - &rsquo; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Vim NERDTree colors I want to change default blue color of folders How to set it? A: If you want to customize file colors based on extension, I created this plugin. You can use it with vim-devicons, but If you don't have it, you can add this line to your .vimrc and it will highlight the filenames: let g:NERDTreeFileExtensionHighlightFullName = 1 A: :hi Directory guifg=#FF0000 ctermfg=red A: Not a heavy vim user, but, I think you can add the following to your .vimrc to highlight the folders/directories in Cyan highlight Directory ctermfg=cyan Have only tried this out in MacOS 10.14 A: NERDTree doesn't provide such an option but looking at the source and reading about highlight you could come up with some customization.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Connect to Vbulletin forum with android app I'm trying to make a small app that connect to a vbulletin forum to retrieve the numbers of unread subjects in user panel. I found how to retrieve info from a website, but the problem is I have no idea how to login to the forum. Can someone give me an advice or a least a link to help me start ? A: There are several ways to login to web site: form login, http authentication, login via AJAX, etc.. You need to investigate how login is done in case of your particular site. Check the http connections (e.g. Firefox with Firebug can see connections) to see what kind of connection is made when you click the login button on the site. A: You'll need to send a _POST request via your app with the username and an md5 hash of the user's password. The username field name should be "vb_login_username" and the password field name should be "vb_login_md5password". Once you figure that out, you can create your own custom login page that your app talks to. Here's something similar to what I use. It returns the user's information in JSON format on a successful login. require_once('./global.php'); require_once(DIR . '/includes/functions_login.php'); define("BADLOGIN" , "You have entered an invalid username or password."); define("BADLOGIN_STRIKES" , "You have entered an invalid username or password. You have %s login attempts left, after which you will be unable to login for 15 minutes."); define("BADLOGIN_STRIKES_ZERO" , "You have entered an invalid username or password and used up your failed login quota. Please wait 15 minutes before trying to login again."); // ################################ start login ################################# if ($_POST['do'] == 'login') { $vbulletin->input->clean_array_gpc('p', array( 'vb_login_username' => TYPE_STR, 'vb_login_password' => TYPE_STR, 'vb_login_md5password' => TYPE_STR, 'vb_login_md5password_utf' => TYPE_STR, 'cookieuser' => TYPE_BOOL, )); // can the user login? $strikes = verify_strike_status($vbulletin->GPC['vb_login_username']); // make sure our user info stays as whoever we were (for example, we might be logged in via cookies already) $original_userinfo = $vbulletin->userinfo; if (!verify_authentication( $vbulletin->GPC['vb_login_username'], $vbulletin->GPC['vb_login_password'], $vbulletin->GPC['vb_login_md5password'], $vbulletin->GPC['vb_login_md5password_utf'], $vbulletin->GPC['cookieuser'], true)) { exec_strike_user($vbulletin->userinfo['username']); // load original user $vbulletin->userinfo = $original_userinfo; if ($vbulletin->options['usestrikesystem']) { if ((5 - $strikes) == 0) { die(json_encode(array( 'hasErrors' => (int) 1, 'errorMsg' => BADLOGIN_STRIKES_ZERO ))); } else { die(json_encode(array( 'hasErrors' => (int) 1, 'errorMsg' => sprintf(BADLOGIN_STRIKES, 5 - $strikes) ))); } } else { die(json_encode(array( 'hasErrors' => (int) 1, 'errorMsg' => BADLOGIN ))); } } exec_unstrike_user($vbulletin->GPC['vb_login_username']); // create new session process_new_login($vbulletin->GPC['logintype'], $vbulletin->GPC['cookieuser'], $vbulletin->GPC['cssprefs']); $userinfo = fetch_user($vbulletin->userinfo['userid']); // is banned user? if ($userinfo['usergroupid'] == 8) { process_logout(); } // return userinfo die(json_encode(array( 'success' => (int) 1, 'user' => $userinfo ))); } Hopefully this helps get you started. By the way, set the field name "cookieuser" to true and the user will be remembered the next time a request is made.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could not load file or assembly 'app_code' or one of its dependencies when impersonating I made a web site with VS2010 and publish it on IIS7. It runs fine but it can't connect to an OLAP server so I had to setup impersonation. Impersonation runs fine in debug on my dev machine, but when I publish this on the server, I get this error*: Exception Details: System.IO.FileLoadException: Could not load file or assembly 'App_Code' or one of its dependencies. An API call exited abnormally. (Exception from HRESULT: 0x800300FA (STG_E_ABNORMALAPIEXIT)) When I comment the impersonate line in web.config the problem disappears. Anyone has an idea about what could be causing this? Thanks in advance, Guillaume *This is a translation of the actual message in french: Server Error in '/' Application. Impossible de charger le fichier ou l'assembly 'App_Code' ou une de ses dépendances. Un appel API a été interrompu anormalement. (Exception de HRESULT : 0x800300FA (STG_E_ABNORMALAPIEXIT)) Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.FileLoadException: Impossible de charger le fichier ou l'assembly 'App_Code' ou une de ses dépendances. Un appel API a été interrompu anormalement. (Exception de HRESULT : 0x800300FA (STG_E_ABNORMALAPIEXIT)) Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Assembly Load Trace: The following information can be helpful to determine why the assembly 'App_Code' could not be loaded. === Informations d'état de liaison préalable === JRN : utilisateur = Unknown JRN : DisplayName = App_Code (Partial) AVT : des informations de liaison partielle ont été fournies pour un assembly : AVT : Nom d'assembly : App_Code | ID de domaine : 2 AVT : une liaison partielle se produit lorsqu'une partie seulement du nom complet de l'assembly est fournie. AVT : cela peut entraîner le chargement d'un assembly erroné par le classeur. AVT : il est recommandé de fournir une identité textuelle complètement spécifiée pour l'assembly, AVT : qui comprend le nom simple, la version, la culture et le jeton de clé publique. AVT : pour plus d'informations et pour obtenir des solutions à ce problème, consultez le livre blanc à l'adresse suivante http://go.microsoft.com/fwlink/?LinkId=109270. JRN : Appbase = file:///C:/inetpub/wwwroot/modstats/ JRN : PrivatePath initial = C:\inetpub\wwwroot\modstats\bin Assembly appelant : (Unknown). === JRN : cette liaison démarre dans le contexte de chargement de default. JRN : utilisation du fichier de configuration de l'application : C:\inetpub\wwwroot\modstats\web.config JRN : utilisation du fichier de configuration d'hôte : C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config JRN : utilisation du fichier de configuration de l'ordinateur à partir de C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config. JRN : stratégie non appliquée à la référence à ce stade (liaison d'assembly privée, personnalisée, partielle ou basée sur l'emplacement). JRN : tentative de téléchargement de la nouvelle URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/9e702efb/dfa5c6b2/App_Code.DLL. JRN : tentative de téléchargement de la nouvelle URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/root/9e702efb/dfa5c6b2/App_Code/App_Code.DLL. JRN : tentative de téléchargement de la nouvelle URL file:///C:/inetpub/wwwroot/modstats/bin/App_Code.DLL. JRN : utilisation du fichier de configuration de l'application : C:\inetpub\wwwroot\modstats\web.config JRN : utilisation du fichier de configuration d'hôte : C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config JRN : utilisation du fichier de configuration de l'ordinateur à partir de C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config. JRN : stratégie non appliquée à la référence à ce stade (liaison d'assembly privée, personnalisée, partielle ou basée sur l'emplacement). ERR : impossible de terminer l'installation de l'assembly (hr = 0x800300fa). Détection terminée. Stack Trace: [FileLoadException: Impossible de charger le fichier ou l'assembly 'App_Code' ou une de ses dépendances. Un appel API a été interrompu anormalement. (Exception de HRESULT : 0x800300FA (STG_E_ABNORMALAPIEXIT))] [FileLoadException: Impossible de charger le fichier ou l'assembly 'App_Code, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' ou une de ses dépendances. Un appel API a été interrompu anormalement. (Exception de HRESULT : 0x800300FA (STG_E_ABNORMALAPIEXIT))] System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) +567 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +192 System.Reflection.Assembly.Load(String assemblyString) +35 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +123 [ConfigurationErrorsException: Impossible de charger le fichier ou l'assembly 'App_Code, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' ou une de ses dépendances. Un appel API a été interrompu anormalement. (Exception de HRESULT : 0x800300FA (STG_E_ABNORMALAPIEXIT))] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +11554224 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +485 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +79 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +337 System.Web.Compilation.BuildManager.CallPreStartInitMethods() +280 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1167 [HttpException (0x80004005): Impossible de charger le fichier ou l'assembly 'App_Code, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' ou une de ses dépendances. Un appel API a été interrompu anormalement. (Exception de HRESULT : 0x800300FA (STG_E_ABNORMALAPIEXIT))] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11686928 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4863749 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237 A: One of my colleagues found the solution -- I now owe him a beer! In the IIS7 control panel, to go the Basic Parameters for the web site. Specify the impersonated user. When reloading the site, it will now complain that it can't access "...\Temporary ASP.NET Files" give read/write access to the impersonated user. Voilà! A: I got the same error message. In my case, the "Application Pool" on IIS was using a wrong .NET Framework version. So I just changed to ".NET Framework v4.0.30319". A: Give write permission (add everyone) to Temporary ASP.NET Files C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
{ "language": "fr", "url": "https://stackoverflow.com/questions/7585126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Add fraction constraint to a column in oracle I am using oracle 10gr2. I am trying to enforce a constraint on a column called "score" such that only fractions can be entered. More specifically, a the format should contain one digit in the numerator and one digit in the denominator, such that a user can only enter a fraction such as 3/4,2/5,or 7/8. The column only accepts numbers as the input. Can anyone show me the SQL to use? A: If I understand correctly, I think the proper way to do this is to store the data in two columns. This especially makes sense if the top number is a user's actual score on a problem and the bottom number is the possible score, which is what it sounds like you are doing. This will enable you to sum up scores using the built in number functions in Oracle rather than parsing strings. Then, you limit the size of each column to (0-9) by using the type NUMBER(1,0). For example: alter table table_name add ( column possible number(1,0), column actual number(1,0) ); If you have data in the score column already, you then copy your values over from there to your new columns. Finally, you drop that column. alter table table_name drop score; Also, I'd do a search on "Oracle less than constraint", because you probably don't want the actual score to exceed the possible, and probably do a similar constraint to make the possible score greater than zero. A: I don't have an instance of Oracle to test against, but here are some pointers and some untested code: Pointers: * *Look here on how to create a check constraint: http://www.techonthenet.com/oracle/check.php *After you know that, you can use Regex to validate the input. Read here for further reference: http://psoug.org/reference/regexp.html You are probably going to use REGEX_LIKE and it would look like something like this: ALTER TABLE your_table add CONSTRAINT check_your_field CHECK (REGEXP_LIKE(your_field, '^[0-9]+/[0-9]+$')); Warning: this is not guaranteed to be fully functional code. It's a lead. Read, research and adjust accordingly. A caveat: 1/0 will be considered valid by the Regex above, but we all know it should not be. There's a way you can know about the second part of the fraction. Read the Regex link, everything you need to know is there. A: The domain of valid values is finite and small. Therefore, consider putting them all in a table, using a fixed width text column (i.e. three characters) and a create a foreign reference to this lookup table, rather than a CHECK constraint.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I change message in DuplexSessionChannel (tcpTransport) in WCF custom channel? I implement IDuplexSessionChannel on my Custom Channel because I use tcpTransport. In that custom channel, I cache service call response(client side caching). But it has errors. In IRequestChannel it works fine. How can I change message in TryMessage method. My code : public Message Receive(TimeSpan timeout) { Message response = null; response = CommunicationCacheManager.Get(_request.Headers.Action, _request); if (response == null) { response = this.InnerChannel.Receive(timeout); int cacheTimeout = 0; if (response.Headers.FindHeader(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE) > -1) { cacheTimeout = response.Headers.GetHeader<int>(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE); } if (cacheTimeout > 0 && response != null && !response.IsFault && !response.IsEmpty) { CommunicationCacheManager.Add(_request.Headers.Action, cacheTimeout, ref response); } } return response; } public Message Receive() { return this.InnerChannel.Receive(); } public bool TryReceive(TimeSpan timeout, out Message message) { ThrowIfDisposedOrNotOpen(); message = null; bool timedout = false; try { message = this.Receive(timeout); } catch (TimeoutException) { timedout = true; } return (!timedout); } CacheManager works. And I get the response Cache. But tryReceive run again and when I look Message. Message is closed. How can I fix that A: Problem is solved. Tcp Binding add RelatesTo Header to Message. So code is changed to public Message Receive(TimeSpan timeout) { Message response = null; response = CommunicationCacheManager.Get(_request.Headers.Action, _request); if (response == null) { response = this.InnerChannel.Receive(timeout); int cacheTimeout = 0; if (response.Headers.FindHeader(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE) > -1) { cacheTimeout = response.Headers.GetHeader<int>(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE); } if (cacheTimeout > 0 && response != null && !response.IsFault && !response.IsEmpty) { CommunicationCacheManager.Add(_request.Headers.Action, cacheTimeout, ref response); } } else { response.Headers.RelatesTo=_request.Header.MessageId; } return response; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Issue: line not showing in non-compatibility view in IE 8 I am having an issue with <hr> in IE8 (normal view) This is my CSS styling for that: #ViewName hr { background-color: #CCCCCC; border: none; font-size: 14pt; } I can see the horizontal lines in IE8 (compatibility mode) but not in normal mode. What is going on here? A: Border has to be 1px minimum for hr to work in IE8. #ViewName hr { background-color: #CCCCCC; border: 1px; font-size: 14pt; } This is not the issue in IE9.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Update Progress on processing after fileupload I have a webform with two upload controls and a number of textfields. When the button is pressed the files get uploaded and then get processed. The upload takes no time, but the processing does. I know I can't have an upload control in an update panel, so I can't work out how to use the update progress control to show my progress. My page with an updateprogress control that does work is as follows: <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1" DynamicLayout="true"> <ProgressTemplate> <div class="LOADING"> Your data is being processed<br /> <br /> <img src="/images/loading.gif" /><br /> <br /> Please wait... </div> </ProgressTemplate> </asp:UpdateProgress> <div class="addFixture"> <asp:ValidationSummary ID="ValidationSummary1" ValidationGroup="fixture" runat="server" /> <label> Type <asp:DropDownList ID="ddlType" runat="server" AppendDataBoundItems="true"> <asp:ListItem Text=""></asp:ListItem> </asp:DropDownList> <label> Date </label> <asp:TextBox ID="txtDate" runat="server"></asp:TextBox> <label> Name 1</label> <asp:TextBox ID="txtName1" runat="server"></asp:TextBox> <label> Name 2 <asp:TextBox ID="txtName2" runat="server"></asp:TextBox> <label> First XML File</label> <asp:FileUpload ID="firstFileUp" runat="server" /> <br /> <label> Second Xml File</label> <asp:FileUpload ID="secondFileUp" runat="server" /> <br /> <br /> <asp:Button ID="SubmitButton" runat="server" CausesValidation="true" Text="Submit" OnClick="SubmitButton_Click" /> <asp:Label ID="ErrorMessageLabel" runat="server" EnableTheming="false"></asp:Label> </div> </ContentTemplate> </asp:UpdatePanel> I have searched for this, but people seem to be trying to get the progress of the file upload and not the processing. Can anyone help? A: Remove the UpdatePanel as all the way you can't use FileUpload controls inside it. Add to the SubmitButton OnClientClick property with following value: OnClientClick="showProgress()" Also add onto the page javascript function below: function showProgress() { var updateProgress = $get("<%= UpdateProgress1.ClientID %>"); updateProgress.style.display = "block"; } By the way, consider to use some async file upload control like one from the Ajax Control Toolkit library A: You can use an UpdatePanel and the FileUpload if you use the ASyncFileUploadControl. It works pretty well. Make sure you download the latest version because there were a couple of issues with prior releases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails 3 getting wrong count in query I'm trying to get the number of messages that haven't been read. The Message model has a column called read_at. If the message has been read there is a value in read_at, if it's unread then that value is nil. I have one read message and one unread message. I get 0 unread messages (I should be getting 1). This is the code: Message.all(:conditions => ['website_id = ? AND read_at = ?', current_website.id, nil]).count It seems that the query is right, since the development log is showing me Message Load (0.2ms) SELECT "messages".* FROM "messages" WHERE (website_id = 2 AND read_at = NULL) A: instead of read_at = NULL try read_at is null, it is a SQL thing. :conditions => ['website_id = ? AND read_at is ?', current_website.id, nil] Here is a short article on SQL nulls, and how to use them: http://www.w3schools.com/sql/sql_null_values.asp Hope it helps A: Though the problem is the one pointed by @pdjota, you should use Rails 3 notation, here is how I would write it: Message.where('website_id = ? AND read_at IS NULL', current_website.id).count
{ "language": "en", "url": "https://stackoverflow.com/questions/7585143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transform array to list I have the following fragment of code: public void doSomething() { float array[] = new float[2]; array[0] = (float) 0.0; array[1] = (float) 1.2; someMethod(array); } public void someMethod(Object value) { //need to convert value to List<Float> } As you can see above I want to convert the value variable which is an array (but passed as an Object) to List. I tried the following as suggested here: Create ArrayList from array new ArrayList<Float> (Arrays.asList(value)); however, it does not compile. Any hints? A: public void someMethod(Object value) { float[] array = (float[]) value; List<Float> result = new ArrayList<Float>(array.length); for (float f : array) { result.add(Float.valueOf(f)); } // ... } I don't know why you're not defining the value argument as a float[] rather than an Object, though. A: [Updated per JB Nizet's correction.] If you use Float instead of float for the array, it will work if the compiler knows that value is an array - which it doesn't. Add a cast: new ArrayList<Float> (Arrays.asList((Float[])value)); or just change the parameter type of value to Float[], and leave out the cast. A: If you want to view a float[] as a List<Float> then Guava's Floats.asList method will get the job done. A: Change float to Float since Arrays.asList(T...a) cannot return a List<float> because a Java primitive type cannot be passed as an argument to a generic type. public void doSomething() { Float array[] = new Float[2]; array[0] = 0.0f; array[1] = 1.2f; someMethod(array); } public void someMethod(Object value) { List<Float> list = new ArrayList<Float> (Arrays.asList((Float[])value)); System.out.println(list); } prints [0.0, 1.2]
{ "language": "en", "url": "https://stackoverflow.com/questions/7585144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can I find the newest .pl file in a directory and all its subdirectories using Perl? How can I scan an entire directory's contents, including its subdirectories' contents, and find the newest .pl file within them using Perl? I want to build a sorted array/list of the full file paths of all .pl files within a directory tree. So, for example, if my base directory is /home/users/cheeseconqueso/ I want to search for .pl files in that directory and any subdirectory within that path and then sort the .pl files by date. The end result would be an array, @pl_paths, where $pl_paths[0] would be something like /home/users/cheeseconqueso/maybe_not_newest_directory/surely_newest_file.pl From that result, I want to execute the file, but I think once I get the sorted array figured out, executing the file in $pl_paths[0], won't be a problem. There is a similar question on SO that I have been trying to modify to suit my needs, but I am here now for obvious reasons. The code I'm using to get the newest file NAME only in one directory is: opendir(my $DH, $DIR) or die "Error opening $DIR: $!"; my %files = map { $_ => (stat("$DIR/$_"))[9] } grep(! /^\.\.?$/, readdir($DH)); closedir($DH); my @sorted_files = sort { $files{$b} <=> $files{$a} } (keys %files); print $sorted_files[0]."\n"; A: With File::Find::Rule, and Schwartzian transform, you can get the newest file with .pl extension, in a subtree starting from dir_path. #!/usr/bin/env perl use v5.12; use strict; use File::Find::Rule; my @files = File::Find::Rule->file()->name( '*.pl' )->in( 'dir_path' ); # Note that (stat $_ )[ 9 ] yields last modified timestamp @files = map { $_->[ 0 ] } sort { $b->[ 1 ] <=> $a->[ 1 ] } map { [ $_, ( stat $_ )[ 9 ] ] } @files; # Here is the newest file in path dir_path say $files[ 0 ]; The map-sort-map chain is a typical idiom: getting timestamp is slow, so we do it only one time per file, keeping every timestamp with its file in an arrayref. Then we sort the new list using timestamp ( comparing the second element of each arrayref ), and finally we discard timestamps, keeping only filenames. A: Use the File::Find core module. A: You can use File::Find if you want a core module for this, but I would prefer to use File::Find::Rule. To start off, we can find all of the .pl files under a directory with use File::Find::Rule; my @files = File::Find::Rule->file ->name('*.pl') ->in($directory); Then let's use map to associate filenames with their modification times: my @files_with_mtimes = map +{ name => $_, mtime => (stat $_)[9] }, @files; And sort them by mtime: my @sorted_files = reverse sort { $a->{mtime} <=> $b->{mtime} } @files_with_mtimes; And from there, the name of the newest one is in $sorted_files[0]{name}. If you only want to find the top one, there's actually no need to do a complete sort, but the nicest solution I can think of involves some slightly advanced FP, so don't worry about it at all if it looks strange to you: use List::Util 'reduce'; my ($top_file) = reduce { $a->{mtime} >= $b->{mtime} ? $a : $b } @files_with_mtimes;
{ "language": "en", "url": "https://stackoverflow.com/questions/7585145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Grails data not saving In the basic CRUD model, from the create view, I have the following code to save an item: println params def newItem = new ProgressItem(name: params.name, comment: params.comment, status: params.status, itemsGroup: params.itemsGroup); //add itemsGroup: based on itemsGroup.id newItem.save() redirect(controller:'project', action:'show', id:params.itemsGroup.id) //change '1' But it doesn't work, that is, when I am back at the project page there isn't another progress item added. Here are the params that print out: [status:FAILED, name:FF FF FF FF FF FF FF, itemsGroup.id:1, itemsGroup:[id:1], comment:FF FF FF FF FF FF FF, create:Create, action:save, controller:progressItem] I don't get any errors... A: If instead of newItem.save() you do: if( !newItem.save() ) { println "Validation errors on save" newItem.errors.each { println it } } Does it print out what was wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java EE Platform or Java EE Technolgy? I'm reading a book about Java EE. In that book Java EE is referred to as the 'Java EE Platform'. Why is the term 'Platform' being used here? I think it should be Java EE Technology without Platform being appended to it. Platform normally means OS and architecture. So, it doesn't make sense to write 'Java EE Platform', does it? Please correct me if I am wrong. A: If you really look at it, Java EE is a specification. Platform and technology is just used interchangeably to refer to a combination of different technologies (EJB, servlets, JSP and MANY MORE) to achieve a solution. These technologies in turn are guided by specifications; like servlet specification 2.3, EJB spec 3 etc. Java EE provides standards on how (or what capabilities) the technologies (mentioned above) should have. You can write your own Java EE compliant container (read software); that confirms to the standards mentioned by Java EE, once you do that you can say you have a Java EE version X compliant platform. A: To take a simple analogy. Java EE is to Java what POSIX is to Unix. Java EE defines a standard for using a technology called Java and POSIX defines it for a platform which is Unix. Sometimes we use these terms interchangeably, causing confusion. It is the context in which these terms are used that really matters. A: I think this is a common language v. engineering terminology issue. Here is an example that might help. We often use 'infrastructure' to refer to the network and the servers, or to the roads and the electrical grid. But in a more engineering-ish proper-sort-of terms infrastructure and superstructure is a relationship between two things, the platform and its features (infrastructure) on which an application is build (superstructure) Similarly technology is a collection of techniques and skills at using those techniques. Although in common language we often refer to devices and products as technology, in engineering-ish terms they are the result someone applying technology (hence the term application) In the case of your question the 'technology' is our civilizations knowledge and skill at designing enterprise computing solutions in an application server paradigm. Java EE specification and associated specifications (and products, etc) are results of applying that tenchnology. A: When talking about the Java platform we usually mean virtual machine. And of course Java EE Technology is a misleading term also, because Java EE actually provides a stack of technologies. So, neither of these terms are 100% correct. A: java is a programming language provide us the ability to create Applications. java enterprise edition is web based architecture provide us all the necessary interfaces and classes to create web applications. therefor java ee is a technology platform stands for the container of the java ee, in order to use the CDI context dependency injection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I redirect two pages in a single COMMAND? I want to redirect two pages at once. if(any statement) { Header("Location: http://example.com/page.php"); Header("Location: folder/page.php"); } else { echo " comment "; } Will this work? Found a solution see on comments. A: No. Why on Earth would you want to? Even if you could, how do you think a browser can display the two pages? New windows/tabs? But what if it's a windowless browser (like lynx)? If you use the above code, PHP will replace the first location header with the second as no headers are actually sent until you start outputting content, after which you cannot call header().
{ "language": "en", "url": "https://stackoverflow.com/questions/7585159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I place numbers at the end of an int (not summing)? I'm busy with making an expression tree for school, I've already build the part in which the tree is being made and printing the result of the arithmetic expression also works. There is this extra part to complete the assignment, I'd just like to make that work too. The extra assignment is making the program able to read an expression. I'm pretty far with this one, but I'm not sure if I coded this thing with placing numbers at the end of an int in a good way. The problem I'm trying to solve is when there is an expression like this... (3*(8-2))+(12/4) ... how do I get the 12 out of the array of characters since they are two apart characters? I used an array of characters in the rest of the code but of course it's possible to use a String to get the two characters. I did it this way: // if the next character is a digit... if (Character.isDigit(expression[i])) { // ... make local variables 'nextNumber'... int nextNumber = 0; // ... and 'a' which already contains this first digit... String a = Character.toString(expression[i]); // ... so when we check for the next character... for (int k = i+1; k < expression.length; k++) { // ... wether it is a digit,... if (Character.isDigit(expression[k])) { // ... we can add that digit to 'a',... a = a + Character.toString(expression[k]); } // ... and if it is not a digit... else if (!Character.isDigit(expression[k])) { // ... we will exit the for loop. break; } } // now we have to change the String to an integer... nextNumber = Integer.getInteger(a); // ... and then we are sure we have the whole number as it was ment to be // in the given expression return new ET(nextNumber); } But it seems so sloppy. I searched for a long time with Google and all I found was this way but I can't imagine there is no easier or at least a less sloppy way. Do you guys know a better way or is this the way to go? The solution I build is a relative easy way to solve the problem of the expression tree, I could work it more out but I don't want to spend any more time than is needed as long as I can show the teacher that I understood the lessons. The course which it is for is Algorithmics so it's not really about learning Java, by this I mean that I'm not asking for the solution of the problem the teacher asked me to solve. Thank you in advance! A: You can build up the number digit by digit (pseudocode): number = 0 for each digit { number = number * 10 + value_of(digit) } This will yield number as the value of the string of digits (from left to right) in base 10. In your case: digits = (1,2) number = 0 number = number * 10 + 1 // <= number = 0*10+1=1 number = number * 10 + 2 // <= number = 1*10+2=12
{ "language": "en", "url": "https://stackoverflow.com/questions/7585160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Piping unzip in a SAS infile Suppose I do the following in SAS: filename tmp pipe 'unzip -c -qq ./data_xml.zip'; libname tmp xml xmlmap=TMMap access=READONLY; data header; set tmp.header; run; data owners; set tmp.owners; run; This will unzip the data_xml.zip file and use the SAS xmlmap file to generate two data sets, header and owners. My question is, how many times will unzip run on data_xml.zip? Will the unzipping just happen once, or will it happen twice because I'm setting a data set from the tmp libname twice? A: The short answer is, YES, it will unzip it twice. As I understand it, the unzip -c essentially turns that data into a sequential source because it is streaming from the unzip command directly into the PIPE libname. Presumably, you want to stream via the -c and the PIPE because of disk space and/or performance concerns with landing the file to disk first. Unfortunately, I'm fairly certain that the way things are set up, the only way to minimize the CPU of an additional unzip will be to land it to disk on a temporary file first. However, depending on the size of the file, the CPU hit for a second unzip might not outweigh the I/O hit for having to read an expanded file from disk at least one extra time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Calculate APR (annual percentage rate) Programmatically I am trying to find a way to programmatically calculate APR based on * *Total Loan Amount *Payment Amount *Number of payments *Repayment frequency There is no need to take any fees into account. It's ok to assume a fixed interest rate, and any remaining amounts can be rolled into the last payment. The formula below is based on a credit agreement for a total amount of credit of €6000 repayable in 24 equal monthly instalments of €274.11. (The APR for the above example is 9.4%) I am looking for an algorithm in any programming language that I can adapt to C. A: I suppose you want to compute X from your equation. This equation can be written as f(y) = y + y**2 + y**3 + ... + y**N - L/P = 0 where X = APR L = Loan (6000) P = Individual Payment (274.11) N = Number of payments (24) F = Frequency (12 per year) y = 1 / ((1 + X)**(1/F)) (substitution to simplify the equation) Now, you need to solve the equation f(y) = 0 to get y. This can be done e.g. using the Newton's iteration (pseudo-code): y = 1 (some plausible initial value) repeat dy = - f(y) / f'(y) y += dy until abs(dy) < eps The derivative is: f'(y) = 1 + 2*y + 3*y**2 + ... + N*y**(N-1) You would compute f(y) and f'(y) using the Horner rule for polynomials to avoid the exponentiation. The derivative can be likely approximated by some few first terms. After you find y, you get x: x = y**(-F) - 1 A: Here is the Objective C code snippet I came up with (which seems to be correct) if anybody is interested: float x = 1; do{ fx = initialPaymentAmt+paymentAmt *(pow(x, numPayments+1)-x)/(x-1)+0*pow(x,numPayments)-totalLoanAmt; dx = paymentAmt *(numPayments * pow( x , numPayments + 1 ) - ( numPayments + 1 )* pow(x,numPayments)+1) / pow(x-1,2)+numPayments * 0 * pow(x,numPayments-1); z = fx / dx; x=x-z; } while (fabs(z)>1e-9 ); apr=100*(pow(1/x,ppa)-1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7585163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: C++ won't let me use a struct as a template argument Perhaps it is a header problem of sorts... But this is what's happening: The compiler is giving me an error on the line: Queue<Email> mailbox; This is the error: ..\EmailSystem.h:25: error: ISO C++ forbids declaration of `Queue' with no type ..\EmailSystem.h:25: error: expected `;' before '<' token Queue.h: #ifndef QUEUE_H_ #define QUEUE_H_ #include <string> #include "EmailSystem.h" ... template <class B> class Queue { ... }; #endif /* QUEUE_H_ */ Queue.cpp: #include "Queue.h" ... template class Queue<Email>; EmailSystem.h: #ifndef EMAILSYSTEM_H_ #define EMAILSYSTEM_H_ #include <iostream> #include <string> #include <vector> #include "Queue.h" struct Email { ... }; struct User { std::string name; Queue<Email> mailbox; }; ... #endif /* EMAILSYSTEM_H_ */ A: You #include "EmailSystem.h" in Queue.h, before you declare class Queue. So when the compiler tries to figure out how to create struct User, it has no clue what's the Queue<Email> you're trying to use. Note that EmailSystem.h and Queue.h include each other. A: You have a circular include. Queue.h includes EmailSystem.h and EmailSystem.h includes Queue.h so the include guards make sure that the header has no effect the second time it is being included. This means if Queue.h is the first to be included then Queue will not yet be declared before it is first used in EmailSystem.h which it includes, at this point: Queue<Email> mailbox; I'm guessing, but I find it unlikely that your template Queue (if it really is a generic class template) needs to know about Email so you should probably remove #include "EmailSystem.h" from Queue.h to solve your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using WebClient.DownloadString() return odd characters sometimes Possible Duplicate: Characters in string changed after downloading HTML from the internet To reproduce my issue have a look a the following code snippet: const string url = "http://serienjunkies.org/serie/glee/"; var webclient = new WebClient(); var source = webclient.DownloadString(url); Console.WriteLine(source.Substring(0, 200); Sometimes (with absolutely the same code) I get the correct html source and othertimes just an unreadable string with odd characters. If you get the one - wait some seconds up to one minute - then you will get the other. Expected result: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ... The other result (copy, paste from cmd): ▼ ♥????????y]2?? em§?.f♦∟3Hf??J?XRM*???%??9 Gf¶##R1p?-??;?♥???♀???U?M?I?s &?#9???⌂?????fg????o????????????;}-????v⌂???^go????????zu???????tD?u^M?h:? ... Thank you. Kind regards, Danny A: Basically the server is delivering content in a compressed (GZip) format. The answer here Characters in string changed after downloading HTML from the internet will give you a replacement downloader that will handle compressed and uncompressed files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add mapview and buttons in the same layout? I am trying to create a layout consists of mapview and textfield and buttons align at the bottom of the layout I tryied using this xml file : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/google_maps" android:layout_width="fill_parent" android:layout_height="fill_parent" android:clickable="true" android:apiKey="@string/maps_key" /> <LinearLayout android:id="@+id/linearLayout1" android:layout_height="wrap_content" android:layout_width="match_parent" android:padding="5dp" android:orientation="vertical"> <TextView android:text="@string/txtLocationDescription" android:layout_height="wrap_content" android:id="@+id/textView1" android:layout_width="wrap_content"></TextView> <EditText android:id="@+id/editText1" android:layout_height="wrap_content" android:layout_width="match_parent"></EditText> <LinearLayout android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="1.0" android:layout_width="match_parent"> <Button android:id="@+id/Button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.5" android:text="@string/btnAddNewLocation"></Button> <Button android:layout_height="wrap_content" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_weight="0.5" android:text="@string/btnCancelAddingLocation"></Button> </LinearLayout> </LinearLayout> </LinearLayout> But I got this error : 09-28 14:49:47.476: ERROR/AndroidRuntime(455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.uis/com.android.uis.LocationManagementActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class com.google.android.maps.MapView 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1622) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.os.Handler.dispatchMessage(Handler.java:99) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.os.Looper.loop(Looper.java:123) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.app.ActivityThread.main(ActivityThread.java:3647) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at java.lang.reflect.Method.invokeNative(Native Method) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at java.lang.reflect.Method.invoke(Method.java:507) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at dalvik.system.NativeStart.main(Native Method) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class com.google.android.maps.MapView 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.view.LayoutInflater.createView(LayoutInflater.java:518) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.view.LayoutInflater.inflate(LayoutInflater.java:408) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.app.Activity.setContentView(Activity.java:1657) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at com.android.uis.LocationManagementActivity.onCreate(LocationManagementActivity.java:10) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): ... 11 more 09-28 14:49:47.476: ERROR/AndroidRuntime(455): Caused by: java.lang.reflect.InvocationTargetException 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at java.lang.reflect.Constructor.constructNative(Native Method) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at java.lang.reflect.Constructor.newInstance(Constructor.java:415) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at android.view.LayoutInflater.createView(LayoutInflater.java:505) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): ... 21 more 09-28 14:49:47.476: ERROR/AndroidRuntime(455): Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity. 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at com.google.android.maps.MapView.<init>(MapView.java:291) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at com.google.android.maps.MapView.<init>(MapView.java:264) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): at com.google.android.maps.MapView.<init>(MapView.java:247) 09-28 14:49:47.476: ERROR/AndroidRuntime(455): ... 24 more What is the problem and how may I do that ? A: You can't put things inside a MapView. A better solution is to put the MapView inside a RelativeLayout and lay out the buttons on top of it inside the top-layer RelativeLayout. EDIT: Basic example: <RelativeLayout> <MapView></MapView> <Button></Button> <Button></Button> <TextView></TextView> *****Any other layout you want **** </RelativeLayout> A: Your activity should extend MapACtivity for this exception not to occur. look at this line in your crash log. MapViews can only be created inside instances of MapActivity. A: Use relativelayout, alignparent variants.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Deleted file remains in NSBundle I recently deleted a file within Xcode. After I deleted this file I cleaned up the project (Shift+cmd+K). For one or other reason the system shows the warning after the cleaning process has been finished successfully: no rule to process file '$(PROJECT_DIR)/json2.js' of type sourcecode.javascript for architecture i386 But this is not the deleted file since I deleted 1231345.jpg I use the following code to check if the path exists if([[NSBundle mainBundle] pathForResource:@"1231345" ofType:@"jpg"] == NULL) { //Here some code if the image doesn't exist } else { //Here some code if the image does exist } If I manually change the 'pathForResource' to a random number which hasn't been a previous file everything works fine! Whats going wrong here? A: Have you deleted the app in the simulator/device? If you deploy via XCode, old files are not deleted, but if you build & archive and then install the archive it usually works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to write c++ webservice in linux machine using fast_cgi module where apache being the webserver I am looking at writing c++ webservice for linux with apache being the webserver.i am working on linux for first time so i needed your help. Am following the instructions given by Fast_Cgi site. * *I have downloaded the toolkit "mod_fast_cgi-2.4.6.tar.tar" from the site " http://www.fastcgi.com/drupal/". *Then i followed the instructions given in "INSTALL.AP2" file which is present in toolkit. *I was able to generate “fast_cgi.so file”. Now this file is located in my directory Configuring httpd.conf next step is to make changes in my In http.conf file – I have added "LoadModule fastcgi_module modules/mod_fastcgi.so" in the begining of the httpd.conf file then they have said to add these things before virtual host directive <IfModule mod_fastcgi.c> FastCgiIpcDir /tmp/fcgi_ipc/ AddHandler fastcgi-script .fcgi </IfModule> Sample C++ program my test program "Testwebservice.cpp" looks like this #include "fcgi_stdio.h" /* fcgi library; put it first*/ #include <stdlib.h> int count; void initialize(void) { count=0; } int main(void) { /* Initialization. */ initialize(); /* Response loop. */ while (FCGI_Accept() >= 0) { printf("Content-type: text/html\r\n" "\r\n" "<title>FastCGI Hello! (C, fcgi_stdio library)</title>" "<h1>FastCGI Hello! (C, fcgi_stdio library)</h1>" "Request number %d running on host <i>%s</i>\n", ++count, getenv("SERVER_HOSTNAME")); } return 0; } I feel am missing something in the directive which i added just before the virtual host directive. could you help me to know what am i missing here. what is that i have to add in httpd.conf file which will direct the http requests coming to the apache webserver to my c++ application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Slow repaint underneath dragged object on X... Can Qt force drag and drop operations to be internal only? I'm implementing Qt's drag and drop API across Windows and X. When I pick up an object in the app running on X and drag it, it leaves a white ghost trail of itself on the window underneath, as if the window underneath is being slow to repaint where the dragged object was previously obscuring part of itself. I believe that this is symptomatic of the same problem that Qt has just solved with resizing windows causing flicker in child widgets on X windows - i.e. the dragged object is treated as a separate native window and therefore X handles the clipping from the dragged object to the window underneath. Since X does this in a different way to Qt, we get the ghosting effect. Has anyone experienced the same problems? One solution that comes to mind is to use the same technique as detailed in the blog article linked above and stop the dragged object being treated as a native window, presumably at the cost of drag and drop being limited to my application only (I have no problem with this). Would anyone know how to force drag and drop operations to be internal only? EDIT: I'm using QDrag::setPixmap to set the graphical representation of the dragged object - it is important that I retain this in favour of a standard drag cursor as this interface is being used on a touchscreen device and will hence have no visible cursor. A: I'm now of the opinion that short of editing and then compiling my own build of Qt (not an option for me), I can't force drag and drop operations to be internal only. Equally, I can't find any way of getting rid of the ghost trail by tweaking my window manager settings or using a compositing window manager (thanks anyway though @atomice). Using OpenGL as the renderer increases the screen repaint speed slightly, but is not perfect and introduces its own problems (see Starting a Qt drag operation on X11 w/ OpenGL causes screen flicker). I would still be very interested to hear any ideas though. I have, however, got a workaround for my problem which works on both Windows and X. Here's a simplified version: void DoDrag() { //Prepare the graphical representation of the drag mDragRepresenter = new QWidget(QApplication::activeWindow()); mDragRepresenter->setAttribute(Qt::WA_TransparentForMouseEvents); mDragRepresenter->SetPixmap(GenerateDragPixmap()); RepositionDragRepresenter(); mDragRepresenter->show(); QTimer UpdateTimer; connect(&UpdateTimer, SIGNAL(timeout()), this, SLOT(RepositionDragRepresenter())); UpdateTimer.start(40); //Start the drag (modal operation) Qt::DropAction ResultingAction = Drag->exec(Qt::CopyAction); UpdateTimer.stop(); delete mDragRepresenter; } void RepositionDragRepresenter() { mDragRepresenter->move(QApplication::activeWindow()->mapFromGlobal(QCursor::pos()) - mDragRepresenterHotSpot); } A: An X11 window is only created for a drag operation if a QDrag::mimeData()->hasImage() is true. If you modify your code so it doesn't use an image then you will just get a drag cursor instead which won't trigger a repaint of the windows underneath. You don't specify what kind of object you are dragging or how you are setting up the drag operation. Can you add some code to show that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7585182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: MPMoviePlayerViewController Not Rotating until app restart K here is an interesting problem We have an app that is presenting with unusual behavior If you install that app (from either test flight or via xcode debug) onto a "clean" device (where the app has not existed before or has been previously delete) when the app plays a mp4 from the web or from local memory. The MPMoviePlayerViewController used to play the app will not rotate. However if you force quit the app and start it again, everything rotates correctly. Even if you quit and return without closing the background thread the video will not rotate. Here is the simple code mediaController = [[MPMoviePlayerViewController alloc] initWithContentURL: [NSURL fileURLWithPath: videoPath]]; [self presentMoviePlayerViewControllerAnimated: mediaController]; [mediaController release]; Any Ideas? A: It might be that one of the root view for another one of the tabs is stopping the root view containing your player from rotating. The UITabBarController asks all its children view controllers (one for each tab) whether it should allow rotation and will only allow one to rotate to a given orientation if all of them allow it. This is done so as to avoid the orientation switching violently from one to another when the user switches tabs. Try putting a breakpoint in the shouldAllowAutoRotation for all of the UITabBarController's children and see if they get called. A: I discovered the issue with this. the UIWindow can only have one view. If another is added, 2nd views will not receive the notification. I had an action that was triggering on the first load that was doing this causing the views to not rotate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a Firefox 7 compatible plugin for Aptana Studio 3? My installation of Firefox was recently updated to version 7, and I see now that the Aptana Debugger 1.7 extension is not compatible. It looks like reverting to Firefox 6 may not be an option...it seems they do not keep all of the old versions around. Is there an update available for the Aptana Debugger extension? Is one in the works that will be compatible with Firefox 7? Thanks. Scott
{ "language": "en", "url": "https://stackoverflow.com/questions/7585189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Run a php script from a java class Possible Duplicate: Execute external program from Java Is it possible to Run a php script from a java class. My project is a struts2 frame work web application. Its purely a java webapp We use a php script to run some daily cron jobs. It was written in php by an ex-employee. Is there a way to run the php script from the javaclass? A: Since you're essentially running a command line script, you could use Runtime.getRuntime().exec. Here's a page with a plethora of examples: http://www.rgagnon.com/javadetails/java-0014.html. If the PHP script is externalized as a web page, you could use Java's URLConnection to call the page so it runs. Documentation: http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7585193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WebView, add local .CSS file to an HTML page? In android I'm using WebView to display a part of a webpage which I fetched from the internet using HttpClient from Apache. To only have the part I want from the html, I use Jsoup. String htmlString = EntityUtils.toString(entity4); // full html as a string Document htmlDoc = Jsoup.parse(htmlString); // .. as a Jsoup Document Elements tables = htmlDoc.getElementsByTag("table"); //important part Now I can just load tables.toString() in the WebView and it displays. Now I want to link a CSS file which I store inside my assets folder with this page. I know I can have something like <LINK href="styles/file.css" type="text/css" rel="stylesheet"> In my html, but how do I link it so that it uses the one I've stored locally? ---EDIT--- I've now changed to this: StringBuilder sb = new StringBuilder(); sb.append("<HTML><HEAD><LINK href=\"file:///android_asset/htmlstyles_default.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>"); sb.append(tables.toString()); sb.append("</body></HTML>"); return sb.toString(); Somehow I do not get the styles applied to the page. Is it the location path I used that is wrong? A: Seva Alekseyev is right, you should store CSS files in assets folder, but referring by file:///android_asset/filename.css URL doesn't working for me. There is another solution: put CSS in assets folder, do your manipulation with HTML, but refer to CSS by relative path, and load HTML to WebView by loadDataWithBaseURL() method: webView.loadDataWithBaseURL("file:///android_asset/", htmlString, "text/html", "utf-8", null); E.g. you have styles.css file, put it to assets folder, create HTML and load it: StringBuilder sb = new StringBuilder(); sb.append("<HTML><HEAD><LINK href=\"styles.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>"); sb.append(tables.toString()); sb.append("</body></HTML>"); webView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null); P.S. I've come to this solution thanks to Peter Knego's answer. A: You cannot store arbitrary files in res - just the specific resource types (drawables, layouts, etc.). The CSS should go to the assets folder instead. Then you can refer to it by the following URL: file:///android_asset/MyStyle.css A: On a related note, if you're not storing the file in the assets folder and want to use relative paths, Webview on Android sometimes requires dot-slash before relative paths. <LINK href="./styles/file.css" type="text/css" rel="stylesheet"> See this post
{ "language": "en", "url": "https://stackoverflow.com/questions/7585210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Hibernate update query Any one tell me the HQL for this SQL code UPDATE ModelClassname SET ClassVariablename=ClassVariablename+10 WHERE ClassVariableId=001; A: There is no point using HQL to do that, you can use direct SQL if you want to do that, through a JDBC query (or even through a Hibernate query, you can use SQL queries). Using HQL queries to update is only recommended when doing batch updates, not a single row. http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-direct A more object-oriented way would be to load your object using HQL, do what you need to do in the Java world (columnValue +=10, whatever else you need to do), and then persist it back using hibernate session flush. I suppose it involves more operations so it's less efficient (in pure performance) but depending on your Hibernate configuration (caching, clustering, second-level cache, etc.) it could be a lot better. Not to mention more testable, of course. A: As others say, there is better ways, but if you really have to, then for example with following syntax: update EntityName m set m.salary = m.salary +10 where m.id = 1 A: In addition to Adam Batkin's answer, I would like to add that such queries are generally not used (except if you need to modify a whole loat of rows at once) in Hibernate. The goal of Hibernate is to work with objects. So you generally do: MyEntity m = (MyEntity) session.get(MyEntity.class, "001"); m.setValue(m.getValue() + 10); // and the new value will automatically be written to database at flush time A: The HQL query should look pretty similar, except instead of using table and column names, you should use the entity and property names (i.e. whatever you use in Java). A: Please try this one Query q = session.createQuery("from ModelClassname where ClassVariableId= :ClassVariableId"); q.setParameter("ClassVariableId", 001); ModelClassname result = (ModelClassname)q.list().get(0); Integer i = result.getClassVariableName(); result.setClassVariableName(i+10); session.update(result); With Regards, Lavanyavathi.Bharathidhasan A: HQL will help you here with bringing object to you with its session's help that you can update easily. //id of employee that you want to update int updatedEmployeeID = 6; //exact employee that you want to update Employee updateEmployee = session.get(Employee.class, updatedEmployeeID); //for debug to see is that exact data that you want to update System.out.println("Employee before update: "+updateEmployee); //basically we use setter to update from the @Entity class updateEmployee.setCompany("Arthur House"); //commit session.getTransaction().commit();
{ "language": "en", "url": "https://stackoverflow.com/questions/7585212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Convert a char to a String I want to convert a char to a String in the following way: char aaa = '\uE001'; I want to obtain a string with the value of "\uE001" so I can use substring(2) to obtain only "E001". Is that possible? Please help A: Well, the character itself is a single character, U+E001. It has the hex value 0xE001. If you want that value as an integer, just use: int unicodeValue = aaa; You can then convert that integer value to hex in various ways, if you really need to, for example: String hex = Integer.toString(unicodeValue, 16); (That's assuming that overload is available on java-me.) ... or Integer.toHexString if that's available but Integer.toString(int, int) isn't. Why do you want this value though? If you could clarify that, we may be able to give you more useful advice. A: Integer.toHexString((int)aaa) ; ..and no substring() required. A: This is the simple like that char aaa = '\uE001'; String s=String.valueOf(aaa); A: You can take any integer value and create a hex string from it like this: String s = Integer.toHexString(num); so Jon Skeet is on the right track. You can: char aaa = '\uE001'; int num = aaa; String hex = Integer.toHexString(num); //now contains "e001"
{ "language": "en", "url": "https://stackoverflow.com/questions/7585221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Gerrit Update Patch to Latest Code How do I update my patch on gerrit to latest code without making any merge commits? My patch is a few commits behind and I don't want to make a new patch on gerrit. A: git rebase origin/master Works and will fix conflicts when needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nivo Slider Bullets "are not centered" after adding more Slides i'm using Nivo Slider in my Wordpress and vBulletin with a Iframe . but when i added more slides the navigation bullets turned to the right , and are not centered anymore. i just know about CSS an NO jquery. how can i solve this problem ? ScreenShot : http://up.vbiran.ir/images/e7r4xxdp09ms0bafb4f.jpg A: The above solution can be a issue in case if you are using multiple instance of default theme based sliders in a page. Possible solutions: 1> Prefix the nivo-controlNav class with the id of slider that you're changing. eg: If you have a slider with id nivoSlider123, you should override the margins as: jQuery('div#nivoSlider123 .nivo-controlNav').css('position:absolute;left:50%;bottom:-42px;margin-left:-40px;'); Now you can adjust the value of margin-left without effecting the other sliders. 2> Using more generalized css code: .theme-default .nivo-controlNav { position:absolute; bottom:-42px; /*left:50%; margin-left:-40px;*/ /* Tweak this to center bullets */ width:100%;text-align:center; } .theme-default .nivo-controlNav a { /*display:block;width:22px;height:22px;background:url(bullets.png) no-repeat;text-indent:-9999px;border:0;margin-right:3px;float:left;*/ display:inline-block !important; width:22px; height:22px; background:url(bullets.png) no-repeat; text-indent:-9999px; border:0; margin-right:3px; } Hope this helps. A: Have a look at the css file for the theme. The default one will be themes/default/default.css. Find this and do as it says: .theme-default .nivo-controlNav { position:absolute; left:50%; bottom:-42px; margin-left:-40px; /* Tweak this to center bullets */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7585226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to validate a field of Zend_Form based on the value of another field? I'm trying to add a custom validator to a field. It should take into account the value of another field. E.g. field A should be at most B+50%. I've made a class implementing Zend_Validate_Interface, but apparently Zend Form only sends in the value of the current field to the validator. How do I make the validator receive everything? A: When you call isValid on a Zend_Form it will pass the all the data you passed to the method $form->isValid(array('a' => 1, 'b' => 2)); Your custom validator will receive that whole array of raw values. Example Validator class My_Validator_TwoVals implements Zend_Validate_Interface { public function getMessages() { return array(); } public function isValid($value) { print_r(func_get_args()); } } Example Form $f = new Zend_Form; $a = $f->createElement('Text', 'a'); $b = $f->createElement('Text', 'b'); $b->addPrefixPath('My_Validator', '.', 'validate'); $b->addValidator('TwoVals'); $f->addElements(array($a, $b)); $f->isValid(array('a' => 1, 'b' => 2)); Output Array ( [0] => 2 [1] => Array ( [a] => 1 [b] => 2 ) ) As you can see there was also a second argument passed to isValid, which is $context. And that contains the remaining values. An alternative would be to pass the second element to match against as an option to the Validator, e.g. class My_Validator_TwoVals implements Zend_Validate_Interface { protected $a; public function getMessages() { return array(); } public function isValid($value) { var_dump($this->a->getValue()); } public function __construct(Zend_Form_Element $a) { $this->a = $a; } } Setup $f = new Zend_Form; $a = $f->createElement('Text', 'a'); $b = $f->createElement('Text', 'b'); $b->addPrefixPath('My_Validator', '.', 'validate'); $b->addValidator('TwoVals', false, array($a)); $f->addElements(array($a, $b)); $f->isValid(array('a' => 1, 'b' => 2)); Will then print int(1). As you can see, we fetched that value through the form element's API so anything you configured for validators and filters would be applied, e.g. it's not the raw value. And you can also set it to another value, etc. Also have a look at Zend_Validate_Identical to learn how ZF implements checking of other form elements: * *http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Validate/Identical.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7585232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: One custom handler for different request url's in ASP.NET web site I am doing a small ASP.NET 2.0. site refactoring. Currently there is the following folder structure: /siteroot/services/home/service1 /siteroot/services/home/service2 /siteroot/services/home/service3 ... all the folders (service1, 2, 3) contain an almost identical default.aspx, with the different content hardcoded into the web form declaration. My idea is to create one service.aspx and serve custom page (with the same template) on a particular URL request. My question is: How can I redirect all request to ../services/home/service1,2,3 to one particular handler/aspx page? Preferably not to have those folders in the project structure at all, but intercept a requests that are headed to them. A: One way: * *Create a custom handler class that implements IHttpModule *In Init(HttpApplication application), register a method for application.AuthorizeRequest *In this method, parse ((HttpApplication)sender).Request.Path as appropriate, using HttpContext.Current.RewritePath if necessary to point to a "real" service.aspx page. Then register your custom handler in <system.webServer><modules>. Another way is to use the MVC-style routing, which works without MVC just fine. Details are in the answer to the question here: custom URL Routing in asp.net. A: If you are able to implement ASP.NET 3.5 (runs on the 2.0 CLR), then Routing sounds perfect for what you need to achieve. With this you can intercept URLs based on a particular format and then route them through to a single page or handler. You won't need a folder structure for each of your services. Here's a few links on how to get going with it in ASP.NET WebForms. It's pretty quick to implement: * *http://msdn.microsoft.com/en-us/magazine/dd347546.aspx *http://msdn.microsoft.com/en-us/library/cc668201%28v=VS.90%29.aspx *http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx *http://weblogs.asp.net/scottgu/archive/2009/10/13/url-routing-with-asp-net-4-web-forms-vs-2010-and-net-4-0-series.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7585233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ArrayList passing by reference with dates object? I pass dates to an ArrayList but when I change the Date object, all the Dates inside the ArrayList will change. This is an example: Date currentDate = new Date("6/10/2011"); ArrayList<Date> datesList = new ArrayList(); currentDate.setDate(currentDate.getDate() + 1); datesList.add(currentDate); currentDate.setDate(currentDate.getDate() + 1); datesList.add(currentDate); currentDate.setDate(currentDate.getDate() + 1); datesList.add(currentDate); System.out.println(datesList.toString()); This will print: [Mon Jun 13 00:00:00 EDT 2011, Mon Jun 13 00:00:00 EDT 2011, Mon Jun 13 00:00:00 EDT 2011] Any idea of why this happening and how could I solve it? A: This is because the variable currentDate references a single instance of Date, which you have added to the list many times. When you call currentDate.setDate(currentDate.getDate() + 1) you're simply updating that same object's state, and every time you call datesList.add(currentDate) that same object is added to the ArrayList. Also note that setDate() and getDate() are deprecated methods. You should look into using a Calendar for date manipulation: Calendar cal = Calendar.getInstance(); cal.set(2011, 5, 10); ArrayList<Date> datesList = new ArrayList<Date>(); datesList.add(cal.getTime()); cal.add(Calendar.DATE, 1); datesList.add(cal.getTime()); cal.add(Calendar.DATE, 1); datesList.add(cal.getTime()); System.out.println( datesList.toString()); or better yet, Joda Time. A: You're repeatedly adding references to the same object, so you end up with a list that contains multiple references to that same object. Try adding copies instead: currentDate.setDate(currentDate.getDate()+1) datesList.add(currentDate.clone()); // note the .clone() A: List datesList has the same instance in all positions. It's the same Date instance instantiated at Date currentDate = new Date("6/10/2011");. Try cloning it with clone(), and modify & add each clone to the list. ArrayList<Date> datesList = new ArrayList(); Date currentDate = new Date("6/10/2011"); ; currentDate.setDate(currentDate.getDate()+1); datesList.add(currentDate); currentDate = currentDate.clone(); currentDate.setDate(currentDate.getDate()+1); datesList.add(currentDate); currentDate = currentDate.clone(); currentDate.setDate(currentDate.getDate()+1); datesList.add(currentDate); System.out.println( datesList.toString()); By doing this, each time you do currentDate = currentDate.clone(), you're assigning a new instance of Date with the same properties to the variable currentDate, while not modifying the original instances already added to the list. A: int dateNum = 3; ArrayList<Date> datesList = new ArrayList(); for(int x = 0; x < dateNum; x++){ Date currentDate = new Date("6/10/2011"); //Creating a new object so your not pointing to the same one in memory currentDate.setDate(currentDate.getDate()+1); datesList.add(currentDate); } System.out.println( datesList.toString());
{ "language": "en", "url": "https://stackoverflow.com/questions/7585238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: symfony setting value of specific checkbox widgets in form I have a widget defined with a series of checkboxes that is essentially used to build up a bit flag. So I have a DB column 'access_bits', and I have several checkboxes generated on in the form class, in the format of 'access_bits[]', with the appropriate values (i.e. 1,2,16,1024 etc) following the solution on this post (Symfony: How to change a form field attribute in an action?) - which is simple and sensible - I am able to magically set the attribute for all the checkboxes. But how can I target specific ones (preferably by value)? TO CLARIFY: HTML: <input name="user[access_bit][]" value="1" /> Level 1 <input name="user[access_bit][]" value="2" /> Level 2 <input name="user[access_bit][]" value="4" /> Level 3 <input name="user[access_bit][]" value="8" /> Level 4 In the DB I have a column that has a bitwise integer. So for example, to have Level 1 and Level 2 checked, the value in the column would be 3. To have them all checked, the value would be 15. "What I Want" PHP in action.class.php $exampleValue = 4; foreach ($form->getWidget('access_bit') as $thisWidget) { if ($thisWidget->getValue() == $exampleValue) { $thisWidget->setAttribute('checked','checked'); } } ... which would cunningly set the checkbox next to Level 3 as ticked. I do not want to use jQuery to do this. A: you can try this....on your form save you can use this $samplevar = $this->your_form->save(); $samplevar->setYOURFORMFIELDNAME(array of values(1,2,3)); $this->sample = YOURFORM($samplevar); or, on showing the form in first you can also pass the value in form while setting $this->samplevariable = YOURFORM($this->getYOURMODEL->setYOURFORMFIELDNAME(array of values(1,2,3) which u get form db getYOURFORMFIELDNAME); if you have values in comma seperated you cane use explode directly $samplevar = $this->YOURFORMNAME->save(); $samplevar->setYOURFORMFIELDNAME(explode(',', $samplevar ->getYOURFORMFIELDNAME())); $this->YOURFORMNAME = new YOURFORMForm($samplevar); A: Try using the setDefault method : $thisWidget->setDefault(array($examplevalue));
{ "language": "en", "url": "https://stackoverflow.com/questions/7585240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone CoreData: Sort with umlauts I have an app that fetches data (a list of countries) from an sqlite database. The countries are in German and contain umlauts, for example Österreich. I want to fetch those countries sorted by name and would expect Österreich to be near other countries with "O", but it is at the end of the results instead. This code is used to fetch the sorted countries: NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity: [NSEntityDescription entityForName: @"Continent" inManagedObjectContext: moc]]; [fetchRequest setSortDescriptors: [NSArray arrayWithObject: [[[NSSortDescriptor alloc] initWithKey: @"name" ascending: YES] autorelease]]]; NSError *error = nil; NSArray *result = [moc executeFetchRequest: fetchRequest error: &error]; Is there any way to have those special char names appear at the position I described above? Didn't find anything on the internet on this ... Thanks a lot. A: You should use UILocalizedIndexedCollation for doing sorting and categorizing entries into sections. The code for implementing this is in the question NSFetchedResultsController v.s. UILocalizedIndexedCollation The UILocalizedIndexedCollation was built to be able to on a per-language basis categorize words based on the current language settings. Á and à will be put in section A. A: Thanks for your answers, I could solve the problem another (easy) way! I just had to modify the NSSortDescriptor like this: [NSSortDescriptor sortDescriptorWithKey: @"name" ascending: YES selector: @selector(localizedCompare:)]
{ "language": "en", "url": "https://stackoverflow.com/questions/7585243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Dependency tree from spring batch configuration Having a spring job definition: <job id="footballJob"> <!-- Step bean details ommitted for clarity --> <step id="playerload" next="gameLoad"/> <step id="gameLoad" next="playerSummarization"/> <step id="playerSummarization"/> </job> Can I progmatically figure out the order of steps to execute? A: Steps will execute in order that you listed in your example. In case you'd like to specify the order you can do: <job id="job"> <step id="stepA" parent="s1" next="stepB" /> <step id="stepB" parent="s2" next="stepC"/> <step id="stepC" parent="s3" /> </job> In case you'd like a non sequential step execution / conditional flow, you can do: <job id="job"> <step id="stepA" parent="s1"> <next on="*" to="stepB" /> <next on="FAILED" to="stepC" /> </step> <step id="stepB" parent="s2" next="stepC" /> <step id="stepC" parent="s3" /> </job> In order to control the flow programmatically, depending on ExitStatus, you can inject your own decider: public class MyDecider implements JobExecutionDecider { public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { if (someCondition) { return "FAILED"; } else { return "COMPLETED"; } } } In the job configuration, a "decision" tag will specify the decider to use as well as all of the transitions: <job id="job"> <step id="step1" parent="s1" next="decision" /> <decision id="decision" decider="decider"> <next on="FAILED" to="step2" /> <next on="COMPLETED" to="step3" /> </decision> <step id="step2" parent="s2" next="step3"/> <step id="step3" parent="s3" /> </job> <beans:bean id="decider" class="com.MyDecider"/> EDIT: If you are looking to get a dependency graph, you can just use Spring Tool Suite to visualize the flow, here is a simple example. A: Can I progmatically figure out the order of steps to execute? by taking your question literally there are some options: * *use Spring Tool Suite afaik it can display job flows *parse job.xml by yourself, you could even use a spring batch job which would be quite funny *try to grok the complete batch setup process, start with spring.handlers and CoreNamespaceHandler.java, you can overwrite it by your needs * *SimpleFlow.java should be sufficient i would go with a simple xml parser
{ "language": "en", "url": "https://stackoverflow.com/questions/7585244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between String.Sort and Greater Than/Less Than Operators VB.Net I have a simple routine to find the next object based on a name property in an un-ordered collection of objects. I go through the collection and collect all the names in a List(of String) adding any names that are > my current name, which should give a list of everything that comes after the current key. I then sort the list using the default .Sort() method on the List(of String) and take the first item in the list, which should be my next item. I do the reverse to find the previous item, add all items < my current name, sort, and take the last item in the list. However, this method skips over some items. For example I have items named 1210, 1210-ADA, and 1210_ADA_DB. Using this method, getting the next item skips the middle item 1210-ADA and finds 1210_ADA_DB, but finding the previous item seems to work. If my process is correct, my only explanation is that the < and > operators compare differently than the .Sort() method. Is this true? What are the differences? Code for finding next item: Dim Key As String = Name Dim NameList As New List(Of String) For Each obj As T In Collection Dim ObjKey As String = Obj.Key If ObjKey > Key Then NameList.Add(ObjKey) End If Next If NameList.Count = 0 Then Return Nothing NameList.Sort() Dim NextKey As String = NameList.First A: my only explanation is that the < and > operators compare differently than the .Sort() method. Is this true? No. Sort internally uses the String.IComparable(Of String).CompareTo method which yields results consistent with < and >. However, this is only true as long as you have not changed the Option Compare for the project or the current file. This will change the behaviour of < and > but not of the above-mentioned method. A: I think you already found what the problem might be. But to annotate, you are getting bitten by some VB6 compat behavior. The default for Option Compare is Binary which uses String.CompareOrdinal(). Not what List.Sort() uses. Option Compare Text uses CultureInfo.CompareInfo.Compare() with the CompareOptions.IgnoreWidth, CompareOptions.IgnoreKanaType, CompareOptions.IgnoreCase options. Also not what List.Sort() uses. Avoid the operators and use String.Compare() instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Identifying something on the screen I'm curious as to how the CodedUI Test functionality in Visual Studio works. I can see how it can identify keypresses and what's typed by querying the keyboard state, but I'm having a hard time figuring out how (i.e. code-wise) it identifies what button was clicked, where that button is located, and how to track it if between the recording and test runs the button has moved or happens to be scrolled off the screen. I'm mainly interested in items which are foreign to me (i.e. I don't have access to the source code and/or it's running on a different process from my programs process).
{ "language": "en", "url": "https://stackoverflow.com/questions/7585252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A basic question on java/maven/testng I am using RHEL 5. I want to be able to write a basic Java class, write corresponding test methods using testNG and be able to say something like "mvn install" which will run test cases and install the built jar. Is there something called maven plugin to support testNG on RHEL? or there is no such thing and above can be achieved by default on linux. ALso how? A: The usual maven plugin for testing, the maven-surefire-plugin, handles testng as well as junit. A: There are a number of plugins for Maven that will auto-run your tests. I would suggest starting with an IDE solution, such as one provided by the Spring STS eclipse-based suite, which has pre-built project templates, including *.pom files already set up. If you are looking to do more than that "out of the box" functionality, reading through the Maven docs and perhaps a book would probably be a good idea. In general, whenever you have a really powerful and flexible tool like Maven, things can get complicated really fast, so having a solid understanding is critical to be able to use the tool successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access an array of structs in simulink? I have the problem, that I have to access a funktion form a dll in matlab/Simulink in the rtw. This should work with a s function, but I have the needed parameters in a array of structures organized. The question is now how I can reach them when I want to call my DLL function? Or is there a better way (e.g. level 2 Matlab files or something similar)? The pure simulation (without RTW) worked pretty well with level 2 m files but I am not able to write a tlc file for compiling them. I did not find much on the net and the documentation only about C sources. Thanks Christian A: For signals in Simulink, what you are asking for is an array of buses. There is similar support for using arrays of structs for parameters. For calling an external function, you might want to look at the legacy code tool. You might also be able to use the MATLAB function block to call your external dll. A: In addition to what @MikeT says: Generating code from Level 2 M-S-Functions is problematic. Read this: http://www.mathworks.co.uk/help/toolbox/simulink/sfg/f7-67622.html#brgscav-1 Also, M-S-functions are generally slow, because they run in the MATLAB interpreter: http://blogs.mathworks.com/seth/2010/10/28/tips-for-simulation-performance/ A: In the end I coded the problem in C and used an array where I defined to order of the elements. Then I wrote some interface functions to access this "virtual" struct. This is not very good coding but the easiest way I have found and it is portable. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7585255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to disable form submit with an input button that is an image How do I disable the form from submitting? I have tried the following chunk of jQuery with no success - any ideas? http://pastebin.com/W7hjaSe0 $('#signup').submit(function(){ $('input[type=button]', this).attr('disabled', 'disabled'); }); A: I am not sure if you are looking for the button to be physically greyed out, or just prevent default action. Here is an example that will run your code on click, grey out the button, and then prevent the default form submission behavior. $('#signup').submit(function(){ $('input[type=button]', this).attr('disabled', 'disabled').css('opacity',0.5); return false; }); A: A simple return false should do the trick. If that doesn't work you can always use the preventDefault() function of event. A: I think the problem is your selector, this is not a "button" type Change $('input[type=button]', this).attr('disabled', 'disabled'); To $('input#signup', this).attr('disabled', 'disabled');
{ "language": "en", "url": "https://stackoverflow.com/questions/7585257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create folder and set ACL with web deploy How do I create a folder using microsoft web deploy? Also, when I have created that folder how do I set the ACL on it? Can I do so when publishing to file system using Visual Studio? Or do I have to publish to a server that has IIS Web Management Service (WMSvc) enabled to be able to set the acl and create folders? A: A file system publish from Visual Studio will not set ACLs, but you can do it with Web Deploy. To automate the process of setting ACLs when publishing from Visual Studio or using MSBuild to publish, see this blog post: http://sedodream.com/2011/11/08/SettingFolderPermissionsOnWebPublish.aspx A: If you use the contentPath or dirPath providers, the directory that you specify in the source argument will be created on the destination computer if it does not already exist. If you choose the contentPath provider, you can use its includeAcls=true setting to copy the acls over. Here's example syntax: msdeploy -verb:sync -source:contentPath=c:\inetpub\wwwroot,includeAcls=true -dest:contentPath=c:\inetpub\wwwroot,computerName=Server1 For the permissions to be set correctly, you must use domain accounts or have local accounts with matching SIDs on both the source and destination computers. For more details, see the contentPath article. If you want to set permissions on the destination folder separately, you can use the setAcl provider. setAcl has settings like setAclUser and setAclAccess that allow for more granular control. See the article for more details, including the ins and outs of permissions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Twitting URLs with # in them and getting their count The goal here is to be able to "tweet" a link of the format www.example.com/page.aspx#1, and get the number of "tweets" for that link... Basically, what the out-of-the-box Twitter button does for any normal link. Reason for this is because the page displays different content based on the ID after the #, so there is a need to count which specific item was "tweeted" and how many times. I tried passing that URL to the Twitter service to get the count (http://urls.api.twitter.com/1/urls/count.json?url=), but the JSON object I get back only has {"count":0,"url":"www.example.com/page.aspx/"}. The link for the Twitter button looks like this (done in JavaScript) var twtLink = 'http://twitter.com/intent/tweet?url='+encodeURIComponent(twtUrl)+'&counturl='+encodeURIComponent(twtUrl); Any suggestions would be appreciated. Thanks! A: Twitter actually re-interrupts all URL's with their own custom t.co wrapper. This is good news for your use case. You can use these unique t.co links with the counter API. If you include the attribute &include_entities=1 to the end of some Twitter REST API calls you get back expanded info including the URL's in the tweets. You will see the original URL as well as the shortened URL version. Pass the shortened URL version into the counter API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modern Master Detail Pattern I am going to create new Financial web application using Asp.net MVC fully ajax, hosted on customer intranet. i have Company setup screen, Company Model is shown Below. Company {Main Company info, Bank info} .|_Regions - each :{Region info, Contacts} ...|_Districts - each : {district info,Contacts} .....|_Branches - each : {branch info, contacts} I thought to make it master/detail , master/detail, master/detail in one page, another idea to make master/detail for company then tabs for region,district and branch and make each tab dependent on previous one. i don't like both ideas, it is very difficult for user to understand the page layout, in addition it is very old style. the problem is all application pages follow this pattern. I need smart idea for page layout fit with nested model like this example , i prefer if it is inspired by IPad or mobile apps designs. thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7585274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ win32 changing the application display name I've developed a win32 api application using c++. It was developed using visual studio 2010. When i started developing i gave it a codename and now when it's done i would like to change the applications name, but don't know where to change it (i'm quite new to win32 and visual studio). I would like to change the .exe name and description (displayed in taskmanager), the name display in the notification area (now it shows MyCodeNameApplication.exe insted of MyCodeNameApplication). I would also like to give a description, version and author name (so when installing it doesn't say unknown provider). How can i change this things? A: Edit the version resource in your .rc file. A: change the path name in 'yourfilename'.dsp
{ "language": "en", "url": "https://stackoverflow.com/questions/7585275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving and Closing an Excel File Created in C# .Net Using Excel Office Interop dll I'm having a really hard time finding good documentation on how to properly close and save an Excel file using the Exce; Office Interop dll. Basically, I have everything working with regards to creating a new Excel workbook and filling the first worksheet with data from a list (when I set the visible property to true on the application object I can watch the Excel file open and fill the worksheet exactly the way I want it to.) I just need to know how to properly close the Excel file and save it to a location of my choice. I want to make sure I kill Excel completely when the code is done -- don't want it to continue to hold memory when I'm finished. Right now I am doing the following after filling the worksheet with the data I want: workbook.Save(); workbook.Close(Type.Missing, Type.Missing, Type.Missing); application.Quit(); UPDATE: I am now able to save the Excel file to the location I want. I simply removed the Save() call and changed the Close call to (true, filePath, Type.Missing) and it is now putting the file in the desired location. Only issue to resolve is properly closing the COM object. POSSIBLE SOLUTION At least this seems to remove Excel from the task manager every time the code finishes executing. // Close the workbook, tell it to save and give the path. workbook.Close(true, workbookPath, Type.Missing); // Now quit the application. application.Quit(); // Call the garbage collector to collect and wait for finalizers to finish. GC.Collect(); GC.WaitForPendingFinalizers(); // Release the COM objects that have been instantiated. Marshal.FinalReleaseComObject(workbook); Marshal.FinalReleaseComObject(worksheet); Marshal.FinalReleaseComObject(workrange); Marshal.FinalReleaseComObject(application); I believe this will work. I think the problem was that I wasn't releasing everything that had been instantiated and I think forcing the GC to collect was the final missing piece. I ran this 20 times and every time Task Manager would show Excel and then remove it once the code finished. FINAL UPDATE: The code above is definitely disposing of all the COM objects and everything is working properly. A: There is no 100% method to always under all cicumstances get rid of a COM object from .NET but appending Marshal.FinalReleaseComObject (application); application = null; after the call to Quit() increases your chances... For MSDN reference see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.finalreleasecomobject.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7585276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: python: what's the point of adding`__dict__` to `__slots__` The whole point of __slots__ is to save space. But I saw people add __dict__ to it so that new attributes can be added. Isn't this defeating the goal of __slots__? A: Yes. If you want __dict__, then just don't use __slots__.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to define new Model in ATK4 From: http://agiletoolkit.org/learn/understand/model/add class Model_MyModel extends Model_Table { function init(){ parent::init(); $this->addField('name'); } } From: http://agiletoolkit.org/intro/models class Model_MyModel extends Model_Table { function defineFields(){ parent::defineFields(); $this->addField('name'); } } Which is correct? What's the difference? A: Agile Data has been refactored into a separate framework: http://git.io/ad The up-to-date way for defining the model is documented here: http://agile-data.readthedocs.io/en/develop/model.html using the init() method is the right one. defineField is old way and was changed in favor of "init" due to consistency. I will update the pages accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Drawing a dynamic shape in iphone I am trying to create a simple circle by subclassing the UIView which I am able to do. But now I want to do various operations over it, such as Rotate, Pan, Scale, etc by various touch events. How can I do these? A: Just make custom object so u can get event for particular of.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How-to's for MySQL InnoDB (insert) performance optimization? I'm still struggling with the performance of my MySQL database using the InnoDB engine. Especially the performance of data insertion, minor the performance of running queries. I've been googling for information, how-to's and so on, but I found most information rather profound matter. Can I find somewhere on the net some basic information for "newbies", a starting point for performance optimization? The first, most import steps for InnoDB optimization, explained in a less complicated way. I'm using the Windows platform A: For newbies: innodb_flush_log_at_trx_commit=0, if you can afford to lose up to 1 second of your work if server crashes. This is the performace vs reliability tradeoff, but it will improve your write performance hugely. If you can afford battery backed write cache, use it. Specifically on Windows, and for write performance, MariaDB 5.3 might be a better idea than stock MySQL from Oracle, since MariaDB is able to better utilize asynchronous IO on Windows. I wrote a note about it some time ago here, on standard synthetic benchmark it performs up to 500% better than stock MySQL 5.5 (see pictures at the end of the note). However, the first and foremost thing that kills performance is the disk flushing. This is solvable if you relax durability with *innodb_flush_log_at_trx_commit* parameter, of with battery backed write cache. Also you might consider using larger transactions, they reduce the amount of disk flushes. A: I used to manage a couple very large MySQL Databases (like, 1TB+). They were huge, unforgiving beasts with an endless appetite to cause me stomach problems. I read everything I could find on MySQL Performance Tuning and innodb. Here's a summary of what helped me: * *The book High Performance MySQL is good, but only gets you so far. *The blog MySQL Performance Blog (this link is to their posts tagged 'innodb') was the most useful overall resource I found on the net. They go into detail on a lot of innodb tuning issues. It gets 'ranty' at times, but overall it's great. Here's another link there on InnoDB Performance Optimization Basics that's good. *The last main thing I did to learn it was to simply read the MySQL Docs themselves. I read how every last parameter works, changed them on my server and then did some basic profiling. After a while you figure out what works by running big queries and seeing what happens. Here's a good place to start: InnoDB Performance Tuning and Troubleshooting In the end, it's just experimenting and working through things until you gain enough knowledge to know what works. A: Try the MySQL Primer script: http://day32.com/MySQL/ A: I didn't use the 'net, I used books. :) The book I used to learn MySQL is "Beginning MySQL" from Wrox Press, by Robert Sheldon and Geoff Moes. Chapter 15 goes into some basics of optimization. I liked this book a lot and think it would be good reading and has been my #1 reference. But it isn't very storage engine specific. I have another book, Pro MySQL from apress that goes into a lot more detail about particular storage engines, but it is also much harder to read. Still a good reference though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how to set custom destination properly in drupal url I'm trying to place the destination in a drupal path like this: http://myhost/root-folder/node/100/delete?destination=node/150?nid=300 It's a little bit unusual in terms of drupal terminology, but this is my requirement. When I visit the above url it's shows me a delete button and a cancel link. But when I click on the cancel link, the redirected page url becomes like this: http://myhost/root-folder/node/150%3Fnid%3D300 instead of http://myhost/root-folder/node/150?nid=300 i.e. myhost = localhost This means it's replacing the ? with code %3F and = with %3D. How can I avoid this issue? A: That's actually totally correct, the second ? is after the query string identifier (i.e. the first ?), so it has to be url encoded to remain valid. Don't worry about it though, when Drupal performs it's redirects by using the drupal_get_destination() function it decodes the encoded string and will redirect to the correct path. Try putting a few different URLs in this online tool and you'll see what they are supposed to look like when they're encoded properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7585303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }