text
stringlengths
8
267k
meta
dict
Q: fire mouse events on both usercontrols The thing is, I have 2 usercontrols, lets call them A and B. They both have MouseRightButtonDown and MouseRightButtonUp events and usercontrol A kinda overlaps B. Now when I right mouse click on A, the mouse event on B does not fire. When I disable the mouseevents on usercontrol A, the mouseevents on usercontrol B fires. But how can I get them both to fire simultaneously? (hope I've explained it clearly) A: a bit hacky but this would work, bind the event handler only to the control 1 and call the other event handler like this: private void textBlock1_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("textBlock1_MouseRightButtonDown"); textBlock2_MouseRightButtonDown(sender, e); } private void textBlock2_MouseRightButtonDown(object sender, MouseButtonEventArgs e) { Debug.WriteLine("textBlock2_MouseRightButtonDown"); } personally I would not do this, I would do all my best to re-architect the logic and not have to call the other handler from one of the two controls, but without knowing more what your are doing, impossible to tell... A: As we are talking about Silverlight here, I strongly suggest to look on how to work Routed Events, which is a mechanism which actually will help you to avoid event relaunching, as these are events that are traverse Visual Tree of your element, from top to bottom. Definitely better then relaunching events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring MVC: BindingResult allegedly declared without preceding model attribute I am experiencing a very peculiar behavior with Spring MVC 3.1.0.M2 that suddenly popped out: @Controller @RequestMapping("/admin/participants/{participantId}") public class ParticipantEditController extends ParticipantControllerSupport { @ModelAttribute("participant") public Participant getParticipant( @PathVariable("participantId") final long participantId) { // ... } @RequestMapping(value = "/{tab}/edit", method = RequestMethod.PUT) public ModelAndView save( @ModelAttribute("participant") final Participant participant, final BindingResult errors) { // ... } } When I'm submitting my form I get the following exception: java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature! at org.springframework.web.method.annotation.support.ErrorsMethodArgumentResolver.resolveArgument(ErrorsMethodArgumentResolver.java:60) at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:65) ... What's troubling me is that my BindingResult does immediately follow the model attribute in the method signature. I've tried it with and without a @Valid annotation and with more or less other parameters, to no avail. Does anyone know what I'm doing wrong? Any help greatly appreciated. A: I have found the problem. The culprit was another method in a parent class that used a ' @ModelAttribute to calculate another model attribute: @ModelAttribute("foobar") public String getFoobar(@ModelAttribute("participant") Participant participant) { ... } A: I hope this is not the correct answer. Try not declaring your parameters as final. ex. public ModelAndView save( @ModelAttribute("participant") Participant participant, BindingResult errors)
{ "language": "en", "url": "https://stackoverflow.com/questions/7520092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET: When does GC run? Memory leak? I understand what immutability is, and how the String .NET class is special. The immutability makes it behave like a value type even though it's a reference type. Got it. The C# reference emphasizes this point (see string (C# Reference), emphasis added by me: Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection. Being a self-taught programmer I'm not well versed in garbage collectors and memory leaks and pointers and stuff. That's why I'm asking a question about it. The description of how the C# compiler automatically creates new string objects and abandons old ones makes it seem like a bunch of memory could get used up with abandoned string content. A lot of objects have dispose methods or destructors so that even the automated CLR garbage collector knows when and how to clean up after an object that isn't needed anymore. There is nothing like this for a String. I wanted to see what would actually happen if a created a program so that I could demostrate for myself and others that creating and immediately abandoning string objects can consume a lot of memory. Here's the program: class Program { static void Main(string[] args) { Console.ReadKey(); int megaByte = (int)Math.Pow(1024, 2); string[] hog = new string[2048]; char c; for (int i = 0; i < 2048; i++) { c = Convert.ToChar(i); Console.WriteLine("Generating iteration {0} (char = '{1}')", i, c); hog[i] = new string(c, megaByte); if ((i + 1) % 256 == 0) { for (int j = (i - 255); j <= i; j++) { hog[j] = hog[i]; } } } Console.ReadKey(); List<string> uniqueStrings = new List<string>(); for (int i = 0; i < 2048; i++) { if (!uniqueStrings.Contains(hog[i])) { uniqueStrings.Add(hog[i]); } } Console.WriteLine("There are {0} unique strings in hog.", uniqueStrings.Count); Console.ReadKey(); // Create a timer with an interval of 30 minutes // (30 minutes * 60 seconds * 1000 milliseconds) System.Timers.Timer t = new System.Timers.Timer(30 * 60 * 1000); t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed); t.Start(); Console.WriteLine("Waiting 30 minutes..."); Console.ReadKey(); } static void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Console.WriteLine("Time's up. I'm collecting the garbage."); GC.Collect(); } } It creates a destroys bunch of unique strings and only ends up with 8 unique strings in the hog array. In my tests the process was still holding on to 570 Mb to 1.1 Gb (it varied). The timer part waits 30 minutes while leaving the process active (not sleeping) and at the end of 30 minutes, the process was still holding on to all the extra memory until I forced collection. This makes it seem like the .NET garbage collector missed something. Lots of other places people say that calling GC.Collect() is something terrible. So the fact that the memory only seems to get reclaimed by forcing the collector using this method still makes it seem like something is wrong. A: Your post is quite a bit of bloat. In short you allocate a lot of memory while keeping references and then notice that the GC won't triggers even when they are no longer referenced, even when much time passes. This means that the GC isn't triggered based on time, but just based on what allocations happen. And once no allocations happen it won't run. If you start allocating again the memory will eventually go down. This is in no way related to immutability or strings in particular. A: Immutability means that string a = "abc"; string b = a; a=a+"def"; creates a new string containing "abcdef", and assigns it to a. The value of b is unchanged, and still refers to a string containing "abc". A: Just that the the garbage collector of your version of the CLR reacts to memory pressure, not elapsed time. Why spend precious CPU time cleaning up memory that isn't needed anyway? Sure you could argue that it would be better to perform the GC when the program is "idle". The problem is, that you want to keep the GC algorithm as simple as possible (which usually means fast) and that the algorithm can't read your mind. It doesn't know when the application is doing "nothing constructive".
{ "language": "en", "url": "https://stackoverflow.com/questions/7520095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to send an array with jQuery .ajax() I've got an array like this one : var cars = new Array(); cars['mom'] = "Ford"; cars['dad'] = "Honda"; I want to send the array cars via jQuery .ajax() function : var oDate = new Date(); $.ajaxSetup({ cache: false }); $.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8" }); $.ajax({ url: path+'/inc/ajax/cars.php', data: {cars:cars}, cache: false, type: "POST", success : function(text){ alert(text); } }); How can I read the array on the server side, with my PHP script ? Thanks ! A: try using php special array $_POST A: $php_array = json_decode($_POST['cars']); A: $.ajax({ url: path+'/inc/ajax/cars.php', data: {cars:$(cars).serializeArray()}, cache: false, type: "POST", success : function(text){ alert(text); } }); php $arr = $_POST['cars'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7520101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse Plugin - XML Editor I've followed this tutorial: Eclipse Plugin This tutorial explain why create a HTML Editor. I need a Text editor,just for auto-highlight some words, anyway I thought this tuto should be a good one to start with. The thing is that I created the Plugin project and the only thing that I changed it was the extension "pat" instead "html, htm", just that. After that I created a .pat file, but eclipse doesn't open it with my plugin, and my text editor is not in the editor's list. Any suggestion?? Let me know if you need more information. A: My guess is that you have just created the plugin, but aren't running it in your current Eclipse instance. That can be verified by opening the view "Plugin registry". That will show a list of all plugins, see if the plugin you have created is in that list. If you click on the run button in Eclipse you will open a run configuration dialog. In one of the tabs, you get to choose what plugins should be available. Make sure your plug-in is selected. This will start up a new Eclipse instance that will run your plugin. To make your plugin be a part of your ordinary Eclipse installation, you will need to export it to a jar and copy that jar to the dropins catalog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET MVC App takes ages to respond sometimes I have an ASP.NET MVC app running in IIS7. Sometimes when I type the URL into a browser it takes 5-10 seconds before it responds, then after that it is fine. It's like it's taking it's time starting/waking up. How should I best proceed with trying to identify the problem? A: If this is happening right after you've edited ASPX files or rebuilt other .NET sources (e.g., *.cs), then it's probably because of the JIT native code generation of the .NET code. This can be solved by a warm-up utility like the (currently defunct, sadly) IIS warm-up module. A: This is probably normal behaviour rather than a problem. It's probably going to sleep because it hasn't had any requests for a long time. You can try changing the Idle Timeout under the Application Pool's advanced settings or if you're running .NET 4.0, you can keep the application always running. A: You can use ASP.NET Mini Profiler to check what takes too long to load. Web.config re-saving can cause your application to be restarted and if your website is not compiled, it takes longer to load as well, plus if you have a heavy database call. In other words, there's no general solution for this, it depends on how you design the application and then improve what appear to be not efficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing a variable through to another PHP page I'm making a server manager. I want to add a "kill" command, which would call a php script that would essentially run a shell_exec('kill $arrtext'); and kill the process, thus closing the server down. Here is the part of my script that returns the results and checks to see which servers are running: <?php $COMMAND = shell_exec('ps -o command ax | grep skulltag | grep -v grep'); $old = array("skulltag-server", "-port", "-iwad", "-wad", "+exec"); $new = array("SKULLTAG", "Running on Port", "Using IWAD", "+ PWAD", "with Config"); $COMMAND = str_replace($old, $new, $COMMAND); $arr = explode("./",$COMMAND); $text = shell_exec('pgrep -u doom'); $arrtext = preg_split('/\s+/', $text); for( $i = 1; $i < count($arr); $i++ ) { echo '<div class = "serverborder">'; echo '<div class = "servertextalign">'; echo $i,'. PROCESS ID <span style="color: #f00;">',$arrtext[$i],'</span> with server parameters: <span style="color: #777;">',$arr[$i],'</span>'; echo '</div>'; echo '</div>'; echo '<br>'; } ?> However, I have no idea how I would add a link or something that would set the proper $arrtext[] variable (depending on which one they picked) and pass it to the PHP script that would kill the server. The live demo can be found at http://server.oblivionro.net/servers/ Thanks! A: Could you try using a shell_exec in another, tiny, script to run that kill script in the command line? Don't use a GET variable. I would rather create a small form for each server in the list and passing it through POST ie. requiring the tiny script that takes hidden POST variables, sending the form action to the same page, and passing the array as a parameter // In form echo '<input type="hidden" name="pid" value="'.$arrtext[$i].'"/>'; // In script $pid = $_POST['pid']; shell_exec('php -f /location/of/kill_script.php -- -'. $pid) Where pid is your process ID. Obviously, you should set up your kill script to check that the pid is valid. The benefit of this is that the script's true location can stay hidden and doesn't need even need to be in the www root. You shouldn't need to link the real script directly. A: The dirty, dirty (not recommended) way to do it is to have the link go to the script with the command, like: <a href="killScript.php?p=<?php echo $arrtext[$i]; ?>">KILL</a> Then in the killScript, you RIGOROUSLY verify that the process they are killing something they're supposed to be killing. A better way would be to avoid using as powerful a command as "kill", so that someone doesn't go to killScript.php?p=1230 where 1230 is the process number of your Minecraft game or something... A: I am confused why you feel the need to ask since you seem to have a grasp of PHP scripting and already create spans etc with the proper data. it is trivial to construct an anchor tag. The anchor tag might reference a GET variable, which could be the PID. After proper validation such as ensuring the PID references a doom server process (and proper login credentials), the PID can then be used to shell a kill command. Note that you are potentially opening your server up to allow the world to shut down processes on your server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UItableView , remove and add rows by begin/end Upradates HI i have some piece of code with table and some items in it. i'd like to u advise me, how to remove and add some rows with animation. When user scroll down to the last row "show next 5 item" code should to detect it and last row was removed and next 5 item will showed. how to detect that table was scrolled to the bottom. #import "tableAddRemoveViewController.h" @implementation tableAddRemoveViewController @synthesize myTable, listOfItems; // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { next5item = [[NSArray alloc] initWithObjects:@"next Item1", @"next Item2", @"next Item3", @"next Item4", @"next Item5", nil]; [self showItems]; [super viewDidLoad]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } cell.textLabel.text = [listOfItems objectAtIndex:indexPath.row]; return cell; } -(void) showItems { NSLog(@"Button Pressed"); listOfItems = [[NSMutableArray alloc] initWithObjects:@"item1", @"item2", @"item3", @"item4", @"item5", @"item6", @"item7", @"item8", @"item9", @"item10", @"item11", @"item12", @"item13", @"item14", @"item15",@"show next 5 items", nil]; NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init]; for (NSInteger i = 0; i < [listOfItems count]; i++) { [indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:0]]; } [myTable beginUpdates]; [myTable insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationLeft]; [myTable endUpdates]; } -(void) removeLastRow { NSLog(@"removeLastRow"); } @end thx
{ "language": "en", "url": "https://stackoverflow.com/questions/7520121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting TextArea on the stage (getChild by ID,Name) I´m trying to get the 7 TextAreas on the stage on FlashBuilder,all of them have the id as "Desc1","Desc2","Desc3"... and the names are the same "Desc1","Desc2","Desc3"..., but when i try to get it,i get a error of a null object... for(var i:int = 0;i<7;i++) { trace((stage.getChildByName("Desc"+(i+1))as TextArea).x); } I searched the web and dont find either any method of "getChildByID" A: Flex IDs don't work with getChildByName(). getChildByName() is designed to work with ids of nested elements in Adobe Flash CS. An flex id is an explicit declaration of a class member with name which is equal to the id. Due to the lack of macro in the actionscript laguage you cannot automate the creation of such lists of controls. You can manually create an Vector or an Array of the text areas and use it in other part of your code to automatically iterate over your TextAreas: var text_areas:Vector.<TextArea> = new Vector.<TextArea>(); text_areas.push(Desc1, Desc2, Desc3); // or you can do this var text_areas2:Array = []; text_areas["Desc1"] = Desc1; text_areas["Desc2"] = Desc2; text_areas["Desc3"] = Desc3; // Now you can iterate over the text areas for each (var a_text_area:TextArea in text_areas) { .... } Or you can create a flex Array: <fx:Array id="textAreas"> <s:TextArea id="textArea1"/> <s:TextArea id="textArea2" x="397" y="0"/> <s:TextArea id="textArea3" x="201" y="1"/> </fx:Array>
{ "language": "en", "url": "https://stackoverflow.com/questions/7520126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get rid of "" object name and working in loop? I do not know how to precisely define this problem; but I could not figure this out genx <- list(scaffold_1 = c("AAATTTTTATAT"),scaffold_2 = c("AAATTTTTATAT"), scaffold_3 = c("AAATTTTTATAT"),scaffold_4 = c("AAATTTTTATAT"), scaffold_5 = c("AAATTTTTATATA"),scaffold_6 = c("AAATTTTTATAT"), scaffold_7 = c("AAATTTTTATAT"),scaffold_8 = c("AAATTTTTATATA")) TATA = "TATA" myobs <- paste("genx$scaffold_", 1:8, sep = "") I want to apply the following function to every elments of the elements of myobs (are objects): source("http://www.bioconductor.org/biocLite.R") biocLite("Biostrings") require((Biostrings) countPattern (TATA, genx$scaffold_1, max.mismatch = 1) [1] 3 When I use the following: countPattern (TATA, myobs[1], max.mismatch = 1) Doesnot work as it is I believe interpreted as: countPattern (TATA, "genx$scaffold_1", max.mismatch = 1) [1] 0 Which is not same as the above one. How can get rid of "" and create a loop to perform this job, your suggestions are appreciated: A: You can directly use the list and do an sapply which acts on every element of the list. Here is some sample code sapply(genx, countPattern, pattern = TATA, max.mismatch = 1) A: You can use the get function a <- 12 get("a") # returns 12 A: What about this: sapply(genx, function (x) { countPattern(TATA, x, max.mismatch = 1) }) A: There is a problem with: get("genx$scaffold_1") because R thinks you are looking for an object with that full name, not the 'scaffold_1' component of 'genx'. What should work is: eval(parse(text="genx$scaffold_1")) But see: fortune(106) More trouble spots along these lines can be found in 'The R Inferno': http://www.burns-stat.com/pages/Tutor/R_inferno.pdf A: I would recommend that you define genx$scaffold as vector, and then you can easily use the apply function: genx = data.frame(scaffold = c(1, 2, 3, 4)) # genx$scaffold is a vector Now you can easily run the countPattern() function on every genx$scaffold's element apply(as.matrix(genx$scaffold), 1, function (x) { countPattern(TATA, x, max.mismatch = 1) }) You can easily extend the solution so that genx$scaffold can be also matrix etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Heap Sort in C++ Okay, so after struggling with trying to debug this, I have finally given up. I'm a beginner in C++ & Data Structures and I'm trying to implement Heap Sort in C++. The code that follows gives correct output on positive integers, but seems to fail when I try to enter a few negative integers. Please point out ANY errors/discrepancies in the following code. Also, any other suggestions/criticism pertaining to the subject will be gladly appreciated. //Heap Sort #include <iostream.h> #include <conio.h> int a[50],n,hs; void swap(int &x,int &y) { int temp=x; x=y; y=temp; } void heapify(int x) { int left=(2*x); int right=(2*x)+1; int large; if((left<=hs)&&(a[left]>a[x])) { large=left; } else { large=x; } if((right<=hs)&&(a[right]>a[large])) { large=right; } if(x!=large) { swap(a[x],a[large]); heapify(large); } } void BuildMaxHeap() { for(int i=n/2;i>0;i--) { heapify(i); } } void HeapSort() { BuildMaxHeap(); hs=n; for(int i=hs;i>1;i--) { swap(a[1],a[i]); hs--; heapify(1); } } void main() { int i; clrscr(); cout<<"Enter length:\t"; cin>>n; cout<<endl<<"Enter elements:\n"; for(i=1;i<=n;i++) //Read Array { cin>>a[i]; } HeapSort(); cout<<endl<<"Sorted elements:\n"; for(i=1;i<=n;i++) //Print Sorted Array { cout<<a[i]; if(i!=n) { cout<<"\t"; } } getch(); } I've been reading up on Heap Sort but I'm not able to grasp most of the concept, and without that I'm not quite able to fix the logical error(s) above. A: You set hs after calling BuildMaxHeap. Switch those two lines. hs=n; BuildMaxHeap(); A: When I implemented my own heapsort, I had to be extra careful about the indices; if you index from 0, children are 2x+1 and 2x+2, when you index from 1, children are 2x and 2x+1. There were a lot of silent problems because of that. Also, every operation needs a single well-written siftDown function, that is vital. Open up Wikipedia at the Heapsort and Binary heap articles and try to rewrite it more cleanly, following terminology and notation where possible. Here is my implementation as well, perhaps it can help. Hmmm now that I checked your code better, are you sure your siftDown/heapify function restricts sifting to the current size of the heap? Edit: Found the problem! You do not initialize hs to n before calling BuildMaxHeap(). A: I suspect it's because you're 1-basing the array. There's probably a case where you're accidentally 0-basing it but I can't spot it in the code offhand. A: Here's an example if it helps. #include <iostream> #include <vector> using namespace std; void max_heapify(std::vector<int>& arr, int index, int N) { // get the left and right index int left_index = 2*index + 1; int right_index = 2*index + 2; int largest = 0; if (left_index < N && arr[left_index] > arr[index]) { // the value at the left_index is larger than the // value at the index of the array largest = left_index; } else { largest = index; } if (right_index < N && arr[right_index] > arr[largest]) { // the value at the right_index is larger than the // value at the index of the array largest = right_index; } // check if largest is still the index, if not swap if (index != largest) { // swap the value at index with value at largest int temp = arr[largest]; arr[largest] = arr[index]; arr[index] = temp; // once swap is done, do max_heapify on the index max_heapify(arr, largest, N); } } void build_max_heap(std::vector<int>& arr, int N) { // select all the non-leaf except the root and max_heapify them for (int i = N/2 - 1; i >= 0; --i) { max_heapify(arr, i, N); } } void heap_sort(std::vector<int>& arr) { int N = arr.size(); int heap_size = N; // build the max heap build_max_heap(arr, N); // once max heap is built, // to sort swap the value at root and last index for (int i = N - 1; i > 0; --i) { // swap the elements int root = arr[0]; arr[0] = arr[i]; arr[i] = root; // remove the last node --heap_size; // perform max_heapify on updated heap with the index of the root max_heapify(arr, 0, heap_size); } } int main() { std::vector<int> data = {5,1,8,3,4,9,10}; // create max heap from the array heap_sort(data); for (int i : data) { cout << i << " "; } return 0; } A: # include <iostream> //Desouky// using namespace std; void reheapify(int *arr, int n, int i) { int parent = i; // initilaize largest as parent/root int child1 = 2 * i + 1; // to get first chid int child2 = 2 * i + 2; // to get second child if (child1 < n && arr[child1] > arr[parent]) // if child2 > parent { parent = child1; } //if child > the parent if (child2 < n && arr[child2] > arr[parent]) { parent = child2; } // if the largest not the parent if (parent != i) { swap(arr[i], arr[parent]); // Recursively heapify the affected sub-tree reheapify(arr, n, parent); } } void heapsort(int *arr, int n) { // build a heap for (int i = n - 1; i >= 0; i--) { reheapify(arr, n, i); } // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end swap(arr[0], arr[i]); // call max heapify on the reduced heap reheapify(arr, i, 0); } } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n; cin >> n; int* arr = new int[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } heapsort(arr, n); for (int i = 0; i < n; i++) { cout << arr[i] << " "; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7520133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Gwt pie chart radius I am using gwt and Google Chart Tools. wondering whether there is a way to set radius to pie chart? A: If you choose to set the width and height, it should increase the radius. Check this example on how to use the options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Format git log output with sed, awk, or the like If I have output like this (from customized git log) d1fd022 2011-09-21 17:02:26 -0400 Replace double quotes with single quotes. 7227fe4 2011-09-21 13:57:36 -0400 Add automatic CommandTFlush to mkdir/rm/touch/cd How could you pipe it through sed, awk or similar to achieve this output? d1fd022 2011-09-21 17:02 Replace double quotes with single quotes. 7227fe4 2011-09-21 13:57 Add automatic CommandTFlush to mkdir/rm/touch/cd Here the only difference is that seconds and timezone are cut out from the date. Unfortunately, git doesn't seem to support custom date formats and I'm not good with the likes of sed, so need some help. A: I suggest using cut (POSIX): [guest@pawel] ~ $ cut -c 1-24,34- foo.txt d1fd022 2011-09-21 17:02 Replace double quotes with single quotes. 7227fe4 2011-09-21 13:57 Add automatic CommandTFlush to mkdir/rm/touch/cd A: awk version: awk -F':[0-9][0-9] | ' '{$4=""}1' inputFile test: kent$ echo "d1fd022 2011-09-21 17:02:26 -0400 Replace double quotes with single quotes. 7227fe4 2011-09-21 13:57:36 -0400 Add automatic CommandTFlush to mkdir/rm/touch/cd"|awk -F':[0-9][0-9] | ' '{$4=""}1' d1fd022 2011-09-21 17:02 Replace double quotes with single quotes. 7227fe4 2011-09-21 13:57 Add automatic CommandTFlush to mkdir/rm/touch/cd A: sed 's/:[^:]* -[^ ]*//' infile Fixed (it's not a space, it's a tab).
{ "language": "en", "url": "https://stackoverflow.com/questions/7520136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where does the Liferay portal-ext.properties go in Glassfish? Below is my Liferay path: C:\glassfish3\glassfish\domains\liferay\applications A: C:\glassfish3 and there should be the deploy directory in the same place. The data directory is there if you are still using hsql. A: Actually, it goes here: C:\glassfish3\glassfish\domains\liferay\lib\classes You should not put this in the exploded classes directory, because if you ever upgrade or undeploy/redeploy, that will get overwritten. A: Try if you find location: C:\glassfish3\glassfish\domains\liferay\src\main\resources\portal-ext.properties to put your file into. Edit: Look for your portal.properties file, find there liferay.home variable. Check that path and place the file there. Another is that what I said in my comments. This tip was on liferay pages. A: This is was the correct place to place it in my liferay 6 install: C:\glassfish3\glassfish\domains\liferay\applications\liferay-portal-6.0-ee-sp2-20110727\WEB-INF\classes
{ "language": "en", "url": "https://stackoverflow.com/questions/7520138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to fetch category name from category table by one of 2 category ids in customer table Having customer and category table. There are category1_id and category2_id in customer table. If having @customer, how to fetch the category name by given @customer and linking the category1_id and category2_id with the id in category table? customer schema: create_table "customers", :force => true do |t| t.string "name" t.string "short_name" t.string "contact" t.string "address" t.string "country" t.string "phone" t.string "fax" t.string "email" t.string "cell" t.integer "sales_id" t.string "web" t.integer "category1_id" t.integer "category2_id" t.boolean "active", :default => true t.string "biz_status" t.integer "input_by_id" t.string "quality_system" t.string "employee_num" t.string "revenue" t.text "note" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end category schema: create_table "categories", :force => true do |t| t.string "name" t.string "description" t.boolean "active", :default => true t.datetime "created_at" t.datetime "updated_at" end In routes.rb file resources :customers do resources :categories end Given @customer, how to fetch category name, like @cusotmer(category1_id).category.name? Thanks. A: You have two single belongs_to associations in your model. Like this: class Customer < ActiveRecord::Base belongs_to :category1, :class_name => "Category", :foreign_key => "category1_id" belongs_to :category2, :class_name => "Category", :foreign_key => "category2_id" end class Category < ActiveRecord::Base end You can now use @customer.category1.name. (edited: belongs_to, not has_one) (edited: added :foreign_key) However, I think you are modeling a "many-to-many" relationship between customers and categories, right? Customers have multiple categories, and categories can be assigned to multiple customers. Take a look at has_and_belongs_to_many in ActiveRecord (see the guide: http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association).
{ "language": "en", "url": "https://stackoverflow.com/questions/7520143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ClearCase: Is it possible to cancel checkouts not made from your own view? Can the project manager force cancellation of checkouts of files/directories made in any view/stream/project? How? A: A ClearCase administrator can force all files of a given view to be considered as "not checked out" (which is the equivalent of canceling their checkout status), with cleartool rmview: cleartool rmview -force -uuid (uuid_of_the_view) -vob \aVob You can get the uuid by grepping the user in the output of: cleartool descr -l vob:\aVob See technote "Removing checked-out references of a view from a VOB". It will work for any view (snapshot or dynamic views, base ClearCase or UCM views) I would recommend limiting that command to a specific vob. Anyway, that doesn't concern the Project manager unless he/she is also a ClearCase administrator (ie, he/she is in the same group than the ClearCase administrators group on Windows, or if he/she is root on Unix) Regarding a cleartool unco (which you can attempt on a dynamic view only), keep in mind if will only work for: * *Version creator *Element owner *VOB owner *root (UNIX and Linux) *Member of the ClearCase administrators group (ClearCase on Windows) *Local administrator of the ClearCase LT server host (ClearCase LT on Windows) So, unless your project manager has created the Vob in which those checked out files are managed, he/she won't be able to undo checkout them. As commented below, all checkout files of the associated vob \avob are no longer considered checked out (their status is reset, not their modified content, which is untouched). In order to restore those checked out files, a user can: * *for a snapshot view, list hijacked files (as in this technote) *for a dynamic view list eclipsed files (see technote on eclipsed files) Each filename found can be piped to a clearcase checkout command. So restoring the checked out files is fairly easy for a given view and vob. A: You can't if it was checked out in a snapshot view. You may be able to if it was checked out in a dynamic view. You can use Find Checkouts to find checked out files and attempt to undo the checkouts from there. A: Ideally, if it is a view that is accessible by someone with higher privilege, e.g. Clearcase administrator who possesses the VOB owner account, it is best to ask him to perform the checkin (if you are sure the file can be checked in) or a saving of the checkedout file followed by a "cleartool unco". If it is not the case, the command cleartool rmview -force -uuid (uuid_of_the_view) -vob <vob-tag-where-checkout-is> should do the trick as mentionned previously by VonC. However, be aware that this command cancel ALL the checkout in . So if you have say : \avob\file1.c \avob\file2.c Say both files are checkedout by the same view of the same user and you want to uncheckout only file1.c. The "cleartool rmview" command described above cancels ALL the checkout in the VOB. So file2.c will also be uncheckedout. The good news is that the checkedout version will not be lost as they will stay locally in the absent user's view. He will be able to access them once he is back. A: There is still another strategy how to handle other persons checkouts as an administrator. Gain access to the users snapshot view. If the computer is reachable, mount the snapshot location and use it as yours. In this case you may even checkin these checkouts as you see the changed files. Is the computer is unreachable, you can construct a new view.dat with the view UUID and populate your view with a cleartool update command for the critial files and directories. Changes in directory versions you will see and be able to checkin, file element changes are not reachable, so you have always to unco file versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Where are perl modules located in archlinux Im trying to find perl modules, such as strict and warnings, but i cant find them... btw im actually using archlinux, i tried using whereis but it throws nothing. A: If the module has POD documentation embedded (which most do), the following will display its location: perldoc -l Some::Module (Lowercase "L" for "location") Otherwise, you can use perl -E'use Some::Module; say $INC{"Some/Module.pm"};' You might be interested in identifying all the locations in which your Perl searches for modules. If so, look at the contents of @INC. You can use perl -V (Uppercase "V") or perl -E'say for @INC;' You may also be interested in Devel::Modlist. The following will lists the path to all the modules used (directly or indirectly) by a script or module: perl -d:Modlist=path some_script.pl perl -d:Modlist=path -e'use Some::Module;' Without =path, it returns the versions of all the modules. A: To find an individual module: perldoc -l warnings All modules are under @INC directories: perl -V See also: Find installed Perl modules matching a regular expression A: The %INC hash holds the on-disk locations of loaded modules, keyed by the package name. You can step through the keys of %INC and print out the associated value. For example: $ perl -MData::Dump -e 'print "$_: $INC{$_}\n" foreach keys %INC' (I loaded Data::Dump so that at least one module would be pulled in for sure. You don't have to load that specific module yourself.) Also, the @INC array holds the include paths that perl searches for modules in, so you can always do: $ perl -E 'say foreach @INC' To find all the default include paths. A: Since you are using a Linux distribution, the native package manager is the most suitable tool. In this case, it's highly recommend to use pacman for such a task: pacman -Ql perl | egrep '(strict|warnings).pm'
{ "language": "en", "url": "https://stackoverflow.com/questions/7520146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using SVN with multi-release development My team is using SVN to manage their source control. I have been given the task to see if there is anyway to improve the way in which we use SVN. I have read much of the SVN book and done a lot of research into how others use SVN. I'm going to give an overview on how we use svn and hopefully someone has some suggestions for me. First of all, we have a release every month or two. So currently we use the trunk as our production copy of the code and we create a release branch for each scheduled delivery and for each production fix. We usually have two, sometimes three scheduled deliveries going at the same time. For example I might be coding for release 3, but I or others are testing for release 2 and doing final bug fixes for release 1. There might also be a production fix going on at the same time. Right now we do a lot of merges to keep the branches(each release) in sync. Release 3 needs the code from 2 and 1, but we obviously don't want new code from release 3 getting into release 1. So we would do a series of merges from release 1 to release 2 and from release 2 to release 3. This would have to be repeated on a regular basis to that coders on release 3 have and bug fixes from 2 or 1. Whenever a release or production fix goes into production we merge the code back into the trunk. Then we merge it from the trunk (or the release branch that just went to production) into all the active branches. As you might have noticed we spend a lot of time merging. This is a lot of work for the person in control of the source control. They are constantly doing merges and making sure they keep track of which branches are merged where. It seems like SVN as our source control management system (I know it's really only version control, but we are using it to manage our source control) should be able to help us out with this. For example, it would be great if the developer working on Release 3 knew when something changed on release 2, release 1, or the trunk and that developer could be automatically notified and he could do a merge to get the changes into his branch. But instead someone has to know to do all the merges manually... Seems like the human is doing too much work and the machine is not doing enough. Does anyone have any ideas on how we might be able to better utilize SVN's features so we could save ourselves some of this headache, and make sure that everyone is always working with the versions of code they are supposed to be! Thanks! A: I do not know that you can realistically work out a situation like this via questions and answers on a forum. Your best option might be to look at Professional Services from a company like my employer, CollabNet. Subversion Training Options Let's set aside names like "trunk" for a moment as these things mean whatever you want them to mean. I am one of the committers for Apache Subversion and I would recommend doing development somewhat like we do for Subversion itself. * *Virtually all development is done in a single location that we call trunk, but could be called "development" or "unstable" or whatever name you want. *Some work on new features will be done on feature branches created from trunk. These are generally short lived and at the discretion of the developer. We try to keep our trunk stable at all times (all tests pass), so sometimes people want to try disruptive changes on a branch first. *At some point, we think trunk has gotten the features we want to a point that it is time to make a release, so a release branch is created by copying trunk. *We do not allow any development to happen in the release branch. Bugs are fixed in trunk, and the revision(s) that contain the fix are nominated for backport to one or more releases. If approved, then the revision(s) are merged to the release branch(s) they were approved for. *Occasionally, trunk has diverged enough from the release that a fix will not merge cleanly. When this happens we make a backport-branch by copying the release branch and then merging the fix from trunk to the backport-branch. This allows the developer the ability to appropriately resolved the merge conflicts on the branch and the other developers to properly review and vote for whether the bug should be backported. This model works well because changes always only merge in one direction and you do not have to worry about someone making a quick fix for some release and then forgetting to make that same fix in trunk. So the bug does not show back up in the next release. I will point out that Subversion development is fairly linear. We do not have 3 releases in flight as you indicate above. We do still support 3 releases at a time, but the number of fixes being backported is small. I think this process could work for a more fluid environment like you describe, but I think you would be better off having a services professional to work with more closely as you try to iron it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: CSS positioning 3 i want "SOL" to be at the center of the left blocks and "SAG" to be at the center of the right blocks. But it either be at the most left or at the most right. How can i make them center of the left and right blocks? link: http://www.orhancanceylan.com/sgkm A: wrap those 3 things in divs with the following attributes display:block; width:33%; text-align:center; float:left;
{ "language": "en", "url": "https://stackoverflow.com/questions/7520153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Batch: combine txt files in columns I am trying to merge txt files (from which first column is equal in all) into one file. Thousands of them that I acquire in my experiments. I use 3 input files as an example to illustrate what I am trying to achieve: 1.txt 2.txt 3.txt l1 a1 l1 b1 l1 c1 l2 a2 l2 b2 l2 c2 l3 a3 l3 b3 l3 c3 So all input files have the first column in common. My wish is to get this output: out.txt l1 a1 b1 c1 l2 a2 b2 c2 l3 a3 b3 c3 Attempt 1 of 3 :: hmm.bat============================================= @echo off > hmm.txt & setLocal enableDELAYedeXpansion echo AAAAAAAAAAaaaaaaaaaa............ pushd %* for /f "tokens=1* delims= " %%a in (a1.txt) do ( >> hmm.txt echo. %%a hm ) for %%j in (*.txt) do ( echo. %%j yes? >> hmm.txt for /f "tokens=2* delims= " %%a in (%%j) do ( >> hmm.txt echo. %%a ) ) popd :: End_Of_Batch====================================== This batch file does extract the columns I want, but rather than that everything is in separate columns, all data is in one single column. I have not been able to manage to get output into separate columns. This attempt (2 of 3) would ultimately give what I want: ::============================================= @echo off > tral.txt & setLocal enableDELAYedeXpansion set N= for /f "tokens=1* delims= " %%a in (a1.txt) do ( set /a N+=1 & call :sub1 %%a & set A!N!=!C! ) set N= for /f "tokens=* delims= " %%a in (a1.txt) do ( set /a N+=1 & call :sub1 %%a & set B!N!=!C! ) set N= for /f "tokens=* delims= " %%a in (a2.txt) do ( set /a N+=1 & call :sub1 %%a & set C!N!=!C! ) set N= for /f "tokens=* delims= " %%a in (a3.txt) do ( set /a N+=1 & call :sub1 %%a & set D!N!=!C! ) for /L %%a in (1 1 !N!) do ( >> tral.txt echo. !A%%a! !B%%a! !C%%a! !D%%a! ) goto :eof :sub1 set C to last token :loop if '%2' neq '' ( shift goto :loop ) set C=%1 goto :eof ::================================================ However, to extend this to many (thousands) files, I would need to repeat the bit set N= for /f "tokens=* delims= " %%a in (a*.txt) do ( set /a N+=1 & call :sub1 %%a & set x!N!=!C! ) maaaaaaaany times. I have tried using a loop instead: Attempt 3 of 3 ::============================================= @echo off & setLocal enableDELAYedeXpansion type nul > slow.txt set N= for /f "tokens=1* delims= " %%a in (a1.txt) do ( set /a N+=1 & call :sub1 %%a & set A!N!=!C! ) for %%j in (*.txt) do ( set N= for /f "tokens=* delims= " %%a in (%%j) do ( set /a N+=1 & call :sub1 %%a & set x!N!=!C! ) ) for /L %%a in (1 1 !N!) do ( >> slow.txt echo. !A%%a! !x%%a! ) goto :eof :sub1 set C to last token :loop if '%2' neq '' ( shift goto :loop ) set C=%1 goto :eof ::============================================= I end up with the first column (which all data files have in common), and the second column of the very last data file. I do not know how to update the variable x in !x%%a! for each file, to get this printed in a separate column. Alternatively, does anyone know if it is possible to echo data at the end of a chosen line in the output file? I would then echo it to the end of the first line, which then would result in echoing all data in columns. Using set /P line1=< hmm.txt and then echo.%line1% %%a>>hmm.txt does not result in echoing at the end of the first line, but rather at the end of the last line. Anyone has a solution either way? A: In the meantime I have managed to find the solution (with much help from others on http://www.computing.net/answers/programming/merge-files-in-column-output/26553.html). Perhaps some day someone else has a nice use for this too. First it counts the files (nr of files is used later on). The files names without extension are listed in a file "list.dat". @echo off SetLocal EnableDelayedExpansion for /f %%a in ('dir/b *.txt') do ( set /a count+=1 set /a count1=count-1 ) echo total is !count! echo !count1! rem empty contents of files type nul > x.txt type nul > y.txt type nul > z.txt type nul > list.dat setlocal set first=y ( for /f %%g in ('dir/b/a-d a*.txt') do ( if defined first ( set first= set/p=%%~ng <nul ) else ( set/p=%%~ng <nul ) ) )>>list.dat for /f %%j in (list.dat) do ( echo. %%j for %%a in (%%j) do find /n /v "" < %%a.txt >> x.txt ) sort x.txt /o x.txt set "regex=^\[[0-9]\]" :loop findstr /r "%regex%" x.txt >> y.txt if not errorlevel 1 ( set "regex=^\[[0-9]%regex:~3% goto loop ) set cnt= set line= for /f "delims=" %%a in (y.txt) do ( set input=%%a set input=!input:*]=! set line=!line! !input! if "!cnt!"=="!count1!" ( >> z.txt echo !line:~1! set line= ) set /a cnt=^(cnt + 1^) %% !count! ) type nul > zz.dat for /F "delims=" %%i in (z.txt) do ( set cnt=1 set rrow= for %%j in (%%i) do ( set /A cnt-=1 if !cnt! equ 0 (set cnt=0 & set rrow=!rrow! %%j) ) set cnt=2 set row= for %%j in (%%i) do ( set /A cnt-=1 if !cnt! equ 0 (set cnt=2 & set row=!row! %%j) ) set row=!row:~1! echo. !rrow! !row!>> zz.dat ) del x.txt del y.txt pause A: I don't think BAT programming is appropiate for what you want to acomplish. You might find some convoluted solution, or end up using a third party tool to complement BAT programming (SED comes immediately to my mind) would IMO only add another problem to the equation, either forcing the user to install such a tool, or complicating your BAT distribution and installation with the same intent. On the other hand, solving your problem is a very easy task to program in any general purpouse programming language. So, I would try either VB or javascript, which are available in almost all windows installations. Take a look at this and get started... @set @junk=1 /* @echo off rem textcolumns text cscript //nologo //E:jscript %0 %* goto :eof :allfiles pushd %1 for /f %%a in ('dir /b /s *.txt') do call :coltxt %%a ) goto :eof :coltxt cscript //nologo //E:jscript %* goto :eof */ function openFile(fn) { var ForReading = 1, ForWriting = 2, ForAppending = 8; var TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0; var fso = new ActiveXObject("Scripting.FileSystemObject"); // Create the file, and obtain a file object for the file. // fso.CreateTextFile(fn); var f = fso.GetFile(fn); // Open a text stream for input. ts = f.OpenAsTextStream(ForReading, TristateUseDefault); // Read from the text stream and display the results. return ts; } function removeFirstWord(s) { var p1=s.indexOf(" "); if (p1>0) { return s.substring(p1+1); } else { return new String(); } } function getCol(ts) { var s; s = ts.ReadLine(); s = removeFirstWord(s); return s; } // main x = WScript.Arguments; fs = new Array(x.length); for (var i=0; i<x.length; i++) { fs[i] = openFile(x(i)); } while (!fs[0].AtEndOfStream) { var s = fs[0].ReadLine(); for (var i=1; i<fs.length; i++) { s += getCol(fs[i]); } WScript.echo(s); } for (var i=0; i<fs.length; i++) { fs[i].close(); } A: If all files have same length: for /f %i in ('find /c /v "" ^< 1.txt') do set n=%i To find number of lines. Set number of files: set f=4 Then read & merge each line: for /l %b in (1,1,%n%) do ( set /p=l%b <nul for /l %a in (1,1,%f%) do ( for /f "tokens=2" %i in ('find "l%b" ^< %a.txt') do ( set /p=%i <nul )) echo: ) Sample output: l1 a1 b1 c1 d1 l2 a2 b2 c2 d2 l3 a3 b3 c3 d3 Tested on Win 10 CMD
{ "language": "en", "url": "https://stackoverflow.com/questions/7520159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python - convert csv file to JSON I need to convert a csv file into a hierarchical JSON object (preferably using Python). I thought that the script I have (below) does a correct job of converting to JSON, but the JavaScript library I'm feeding the JSON data to (D3.js) doesn't work with it. The csv file looks like this: subject,branch,book,chapter,Encode ID,Level 1,Level 2,Level 3,Level 4 MAT,TRI,CK-12 Trigonometry - Second Edition,Right Triangles and an Introduction to Trigonometry,MAT.TRI.000,Right Triangles and an Introduction to Trigonometry,,, MAT,TRI,CK-12 Trigonometry - Second Edition,Right Triangles and an Introduction to Trigonometry,MAT.TRI.004,,The Pythagorean Theorem,, MAT,TRI,CK-12 Trigonometry - Second Edition,Right Triangles and an Introduction to Trigonometry,MAT.TRI.005,,,The Pythagorean Theorem, MAT,TRI,CK-12 Trigonometry - Second Edition,Right Triangles and an Introduction to Trigonometry,MAT.TRI.006,,,Pythagorean Triples, MAT,TRI,CK-12 Trigonometry - Second Edition,Right Triangles and an Introduction to Trigonometry,MAT.TRI.007,,,Converse of the Pythagorean Theorem, MAT,TRI,CK-12 Trigonometry - Second Edition,Right Triangles and an Introduction to Trigonometry,MAT.TRI.008,,,The Distance Formula, MAT,TRI,CK-12 Trigonometry - Second Edition,Right Triangles and an Introduction to Trigonometry,MAT.TRI.009,,Special Right Triangles,, Right now, I have the following code the recursively builds the hierarchical array: import csv import json import random random.seed() # open up the csv file f = open('/path/to/file','rU') c = csv.DictReader(f) # lists for keeping track of what subjects and branches I've already iterated over subject_list = [] branch_list = [] lev1_list = [] lev2_list = [] lev3_list = [] lev4_list = [] # iterate through file i = 0 for row in c: if i == 0: subject = row['subject'] branch = row['branch'] if len(row['Level 1']) > 0: lev1 = row['Level 1'] else: lev2 = None if len(row['Level 2']) > 0: lev2 = row['Level 2'] else: lev2 = None if len(row['Level 3']) > 0: lev3 = row['Level 3'] else: lev3 = None else: if row['subject'] != subject: # add all branches to this subject subject_list.append({'name':subject,'type':'subject','children':branch_list}) # set current subject subject = row['subject'] if row['branch'] != branch: # add all concepts to this branch branch_list.append({'name':branch,'type':'branch','children':lev1_list}) # empty lev1_list lev1_list = [] # set new branch branch = row['branch'] if len(row['Level 1']) > 0 and row['Level 1'] != lev1: # print lev1 # add all level 2 concepts to this level 1 lev1_list.append({'name':lev1,'type':'concept','level':1,'children':lev2_list}) #print lev1 #empty lev2_list lev2_list = [] #lev1_list.append(row['Level 1']) lev1 = row['Level 1'] if len(row['Level 2']) > 0 and row['Level 2'] != lev3: #print lev2 #print lev3_list # add all level 3 concepts to this level 2 if lev2 is not None: lev2_list.append({'name':lev2,'type':'concept','level':2,'children':lev3_list}) # empty lev3_list lev3_list = [] # lev2_list.append(row['Level 2']) lev2 = row['Level 2'] if len(row['Level 3']) > 0 and row['Level 3'] != lev3: # print lev3 # add all level 4 concepts to this level 4 # lev3_list.append({'name':lev3,'type':'concept','level':3}) # empty level 4 concepts # lev4_list = [] # add new level 3 if lev3 is not None: lev3_list.append({'name':lev3,'type':'concept','level':3,'size':random.randint(1,100)}) lev3 = row['Level 3'] #if row['Level 4'] is not None and row['Level 4'] is not lev4: # lev4_list.append({'name':lev4,'type':'concept','level':4}) # lev4 = row['Level 4'] i += 1 f.close() branch_list.append({'name':branch,'type':'branch','children':lev1_list}) #subject_list.append({'name':subject,'type':'subject','children':branch_list}) subject_dict = {'name':subject,'type':'subject','children':branch_list} #json_list= json.dumps(subject_list) json_list = json.dumps(subject_dict) f = open('/Users/thaymore/Sites/d3/data/trig_map.json','wb') f.write(json_list) f.close() What this gets me right now is something like this: {"type": "subject", "name": "MAT", "children": [{"type": "branch", "name": "TRI", "children": [{"children": [{"children": [{"size": 40, "type": "concept", "name": "The Pythagorean Theorem", "level": 3}, {"size": 19, "type": "concept", "name": "Pythagorean Triples", "level": 3}, {"size": 68, "type": "concept", "name": "Converse of the Pythagorean Theorem", "level": 3}], "type": "concept", "name": "The Pythagorean Theorem", "level": 2}, {"children": [{"size": 28, "type": "concept", "name": "The Distance Formula", "level": 3}, {"size": 49, "type": "concept", "name": "Special Right Triangle #1: Isosceles Right Triangle", "level": 3}, {"size": 33, "type": "concept", "name": "Special Right Triangle #2: 30-60-90 Triangle", "level": 3}], "type": "concept", "name": "Special Right Triangles", "level": 2}, {"children": [{"size": 18, "type": "concept", "name": "Using Special Right Triangle Ratios", "level": 3}, {"size": 49, "type": "concept", "name": "The Sine, Cosine, and Tangent Functions", "level": 3}], "type": "concept", "name": "Basic Trigonometric Functions", "level": 2}, {"children": [{"size": 100, "type": "concept", "name": "Secant, Cosecant, and Cotangent Functions", "level": 3}, {"size": 73, "type": "concept", "name": "Solving Right Triangles", "level": 3}, {"size": 93, "type": "concept", "name": "Inverse Trigonometric Functions", "level": 3}, {"size": 88, "type": "concept", "name": "Finding the Area of a Triangle", "level": 3}, {"size": 6, "type": "concept", "name": "Angles of Elevation and Depression", "level": 3}, {"size": 3, "type": "concept", "name": "Right Triangles and Bearings", "level": 3}], "type": "concept", "name": "Solving Right Triangles", "level": 2}, {"children": [{"size": 68, "type": "concept", "name": "Other Applications of Right Triangles", "level": 3}, {"size": 92, "type": "concept", "name": "Angles of Rotation in Standard Position", "level": 3}], "type": "concept", "name": "Measuring Rotation", "level": 2}, {"children": [{"size": 14, "type": "concept", "name": "Coterminal Angles", "level": 3}, {"size": 68, "type": "concept", "name": "Trigonometric Functions of Angles in Standard Position", "level": 3}], "type": "concept", "name": "Applying Trig Functions to Angles of Rotation", "level": 2}, {"children": [{"size": 61, "type": "concept", "name": "The Unit Circle", "level": 3}, {"size": 95, "type": "concept", "name": "Reference Angles and Angles in the Unit Circle", "level": 3}, {"size": 11, "type": "concept", "name": "Trigonometric Functions of Negative Angles", "level": 3}, {"size": 45, "type": "concept", "name": "Trigonometric Functions of Angles Greater than 360 Degrees", "level": 3}], "type": "concept", "name": "Trigonometric Functions of Any Angle", "level": 2}], "type": "concept", "name": "Right Triangles and an Introduction to Trigonometry", "level": 1}, {"children": [{"children": [{"size": 20, "type": "concept", "name": "Using a Calculator to Find Values", "level": 3}, {"size": 25, "type": "concept", "name": "Reciprocal identities", "level": 3}, {"size": 40, "type": "concept", "name": "Domain, Range, and Signs of Trig Functions", "level": 3}, {"size": 97, "type": "concept", "name": "Quotient Identities", "level": 3}, {"size": 18, "type": "concept", "name": "Cofunction Identities and Reflection", "level": 3}], "type": "concept", "name": "Relating Trigonometric Functions", "level": 2}, {"children": [{"size": 35, "type": "concept", "name": "Pythagorean Identities", "level": 3}, {"size": 95, "type": "concept", "name": "Understanding Radian Measure", "level": 3}, {"size": 30, "type": "concept", "name": "Critial Angles in Radians", "level": 3}, {"size": 16, "type": "concept", "name": "Converting Any Degree to Radians", "level": 3}, {"size": 25, "type": "concept", "name": "The Six Trig Functions and Radians", "level": 3}], "type": "concept", "name": "Radian Measure", "level": 2}, {"children": [{"size": 19, "type": "concept", "name": "Check the Mode", "level": 3}, {"size": 63, "type": "concept", "name": "Rotations", "level": 3}, {"size": 33, "type": "concept", "name": "Length of Arc", "level": 3}, {"size": 54, "type": "concept", "name": "Area of a Sector", "level": 3}, {"size": 6, "type": "concept", "name": "Length of a Chord", "level": 3}], "type": "concept", "name": "Applications of Radian Measure", "level": 2}, {"children": [{"size": 71, "type": "concept", "name": "Angular Velocity", "level": 3}, {"size": 16, "type": "concept", "name": "The Sine Graph", "level": 3}, {"size": 65, "type": "concept", "name": "The Cosine Graph", "level": 3}, {"size": 32, "type": "concept", "name": "The Tangent Graph", "level": 3}, {"size": 93, "type": "concept", "name": "The Three Reciprocal Functions", "level": 3}, {"size": 30, "type": "concept", "name": "Cotangent", "level": 3}, {"size": 4, "type": "concept", "name": "Cosecant", "level": 3}], "type": "concept", "name": "Circular Functions of Real Numbers", "level": 2}, {"children": [{"size": 100, "type": "concept", "name": "Secant", "level": 3}, {"size": 40, "type": "concept", "name": "Vertical Translations", "level": 3}], "type": "concept", "name": "Translating Sine and Cosine Functions", "level": 2}, {"children": [{"size": 58, "type": "concept", "name": "Horizontal Translations or Phase Shifts", "level": 3}, {"size": 76, "type": "concept", "name": "Amplitude", "level": 3}, {"size": 91, "type": "concept", "name": "Period and Frequency", "level": 3}], "type": "concept", "name": "Amplitude, Period and Frequency", "level": 2}, {"children": [{"size": 78, "type": "concept", "name": "Combining Amplitude and Period", "level": 3}, {"size": 12, "type": "concept", "name": "The Generalized Equations", "level": 3}, {"size": 22, "type": "concept", "name": "Drawing Sketches/Identifying Transformations from the Equation", "level": 3}], "type": "concept", "name": "General Sinusoidal Graphs", "level": 2}], "type": "concept", "name": "Graphing Trigonometric Functions - 2nd edition", "level": 1}, {"children": [{"children": [{"size": 81, "type": "concept", "name": "Writing the Equation from a Sketch", "level": 3}, {"size": 60, "type": "concept", "name": "Tangent and Cotangent", "level": 3}, {"size": 27, "type": "concept", "name": "Secant and Cosecant", "level": 3}], "type": "concept", "name": "Graphing Tangent, Cotangent, Secant, and Cosecant", "level": 2}, {"children": [{"size": 62, "type": "concept", "name": "Graphing Calculator Note", "level": 3}, {"size": 20, "type": "concept", "name": "Quotient Identity", "level": 3}, {"size": 15, "type": "concept", "name": "Reciprocal Identities", "level": 3}, {"size": 28, "type": "concept", "name": "Pythagorean Identity", "level": 3}, {"size": 28, "type": "concept", "name": "Even and Odd Identities", "level": 3}], "type": "concept", "name": "Fundamental Identities", "level": 2}, {"children": [{"size": 24, "type": "concept", "name": "Cofunction Identities", "level": 3}, {"size": 91, "type": "concept", "name": "Working with Trigonometric Identities", "level": 3}], "type": "concept", "name": "Proving Identities", "level": 2}, {"children": [{"size": 59, "type": "concept", "name": "Technology Note", "level": 3}, {"size": 26, "type": "concept", "name": "Simplifying Trigonometric Expressions", "level": 3}, {"size": 94, "type": "concept", "name": "Solving Trigonometric Equations", "level": 3}, {"size": 49, "type": "concept", "name": "Solving Trigonometric Equations Using Factoring", "level": 3}], "type": "concept", "name": "Solving Trigonometric Equations", "level": 2}, {"children": [{"size": 25, "type": "concept", "name": "Solving Trigonometric Equations Using the Quadratic Formula", "level": 3}, {"size": 11, "type": "concept", "name": "Sum and Difference Formulas: cosine", "level": 3}, {"size": 30, "type": "concept", "name": "Using the Sum and Difference Identities of cosine", "level": 3}, {"size": 75, "type": "concept", "name": "Sum and Difference Identities: sine", "level": 3}, {"size": 94, "type": "concept", "name": "Sum and Difference Identities: Tangent", "level": 3}, {"size": 22, "type": "concept", "name": "Using the Sum and Difference Identities to Verify Other Identities", "level": 3}], "type": "concept", "name": "Sum and Difference Identities", "level": 2}, {"children": [{"size": 15, "type": "concept", "name": "Solving Equations with the Sum and Difference Formulas", "level": 3}, {"size": 88, "type": "concept", "name": "Deriving the Double Angle Identities", "level": 3}, {"size": 42, "type": "concept", "name": "Applying the Double Angle Identities", "level": 3}], "type": "concept", "name": "Double Angle Identities", "level": 2}, {"children": [{"size": 13, "type": "concept", "name": "Solving Equations with Double Angle Identities", "level": 3}, {"size": 36, "type": "concept", "name": "Deriving the Half Angle Formulas", "level": 3}], "type": "concept", "name": "Half-Angle Identities", "level": 2}], "type": "concept", "name": "Trigonometric Identities and Equations - 2nd edition", "level": 1}, {"children": [{"children": [{"size": 100, "type": "concept", "name": "Solving Trigonometric Equations Using Half Angle Formulas", "level": 3}, {"size": 93, "type": "concept", "name": "Sum to Product Formulas for Sine and Cosine", "level": 3}, {"size": 71, "type": "concept", "name": "Product to Sum Formulas for Sine and Cosine", "level": 3}, {"size": 53, "type": "concept", "name": "Solving Equations with Product and Sum Formulas", "level": 3}, {"size": 45, "type": "concept", "name": "Triple-Angle Formulas and Beyond", "level": 3}, {"size": 18, "type": "concept", "name": "Linear Combinations", "level": 3}], "type": "concept", "name": "Products, Sums, Linear Combinations, and Applications", "level": 2}, {"children": [{"size": 73, "type": "concept", "name": "Applications & Technology", "level": 3}, {"size": 54, "type": "concept", "name": "Defining the Inverse of the Trigonometric Ratios", "level": 3}, {"size": 15, "type": "concept", "name": "Exact Values for Inverse Sine, Cosine, and Tangent", "level": 3}], "type": "concept", "name": "Basic Inverse Trigonometric Functions", "level": 2}, {"children": [{"size": 1, "type": "concept", "name": "Finding Inverses Algebraically", "level": 3}, {"size": 93, "type": "concept", "name": "Finding the Inverse by Mapping", "level": 3}], "type": "concept", "name": "Graphing Inverse Trigonometric Functions", "level": 2}, {"children": [{"size": 79, "type": "concept", "name": "Finding the Inverse of the Trigonometric Functions", "level": 3}, {"size": 29, "type": "concept", "name": "Composing Trig Functions and their Inverses", "level": 3}, {"size": 19, "type": "concept", "name": "Composing Trigonometric Functions", "level": 3}, {"size": 53, "type": "concept", "name": "Inverse Reciprocal Functions", "level": 3}, {"size": 28, "type": "concept", "name": "Composing Inverse Reciprocal Trig Functions", "level": 3}], "type": "concept", "name": "Inverse Trigonometric Properties", "level": 2}], "type": "concept", "name": "Inverse Trigonometric Functions - 2nd edition", "level": 1}, {"children": [{"children": [], "type": "concept", "name": "Applications & Models", "level": 2}, {"children": [{"size": 42, "type": "concept", "name": "Trigonometry in Terms of Algebra", "level": 3}, {"size": 38, "type": "concept", "name": "Derive the Law of Cosines", "level": 3}, {"size": 82, "type": "concept", "name": "Case #1: Finding the Side of an Oblique Triangle", "level": 3}, {"size": 68, "type": "concept", "name": "Case #2: Finding any Angle of a Triangle", "level": 3}], "type": "concept", "name": "The Law of Cosines", "level": 2}, {"children": [{"size": 20, "type": "concept", "name": "Identify Accurate Drawings of General Triangles", "level": 3}, {"size": 90, "type": "concept", "name": "Find the Area Using Three Sides: Heron\u2019s Formula", "level": 3}, {"size": 7, "type": "concept", "name": "Heron\u2019s Formula:", "level": 3}], "type": "concept", "name": "Area of a Triangle", "level": 2}, {"children": [{"size": 21, "type": "concept", "name": "Finding a Part of the Triangle, Given the Area", "level": 3}, {"size": 58, "type": "concept", "name": "Deriving the Law of Sines", "level": 3}, {"size": 15, "type": "concept", "name": "AAS (Angle-Angle-Side)", "level": 3}, {"size": 41, "type": "concept", "name": "ASA (Angle-Side-Angle)", "level": 3}], "type": "concept", "name": "The Law of Sines", "level": 2}, {"children": [{"size": 87, "type": "concept", "name": "Solving Triangles", "level": 3}, {"size": 31, "type": "concept", "name": "Possible Triangles with SSA", "level": 3}, {"size": 45, "type": "concept", "name": "Using the Law of Sines", "level": 3}], "type": "concept", "name": "The Ambiguous Case", "level": 2}, {"children": [{"size": 40, "type": "concept", "name": "Using the Law of Cosines", "level": 3}, {"size": 2, "type": "concept", "name": "Summary of Triangle Techniques", "level": 3}, {"size": 18, "type": "concept", "name": "Using the Law of Cosines", "level": 3}], "type": "concept", "name": "General Solutions of Triangles", "level": 2}, {"children": [{"size": 42, "type": "concept", "name": "Using the Law of Sines", "level": 3}, {"size": 6, "type": "concept", "name": "Directed Line Segments, Equal Vectors, and Absolute Value", "level": 3}, {"size": 60, "type": "concept", "name": "Vector Addition", "level": 3}, {"size": 76, "type": "concept", "name": "Vector Subtraction", "level": 3}], "type": "concept", "name": "Vectors", "level": 2}], "type": "concept", "name": "Triangles and Vectors", "level": 1}]}]} I think this might technically fit the JSON specs, but the library that I'm trying to feed the JSON data to (D3.js) can't seem to do anything with it. Is it because the order of the elements is out-of-whack (i.e., the "children" element is coming before the "name" element)? Is it something more basic that I'm doing? (The file whose structure I'm trying to match is located here.) A: Wouldn't this work? import json f = open('path/to/file','r') arr=[] headers = [] for header in f.readline().split(','): headers.append(header) for line in f.readlines(): lineItems = {} for i,item in enumerate(line.split(',')): lineItems[headers[i]] = item arr.append(lineItems) f.close() jsonText = json.dumps(arr) print jsonText A: Order of elements is not important for json. The json you are producing is wrong, though. The example you gave that you are trying to match does not have a "subject" key at the top level. It shows just "name" => "flare", and a list of children. Your script is producing json with a "subject" key. Instead of subject_dict = {'name':subject,'type':'subject','children':branch_list} try subject_dict = {'name':subject,'children':branch_list} I don't know about D3.js, so I can't say if it expects an object that follows one exact structure. Tip: one good tool to check the structure of json objects is http://jsoneditor.appspot.com. Just paste your string in there and click on "Go to Treeview". It will hellp you find differences between what you have and what you want very easily. A: D3 expects the value in JSON to also be in double quotes. so e.g. "level": 3 should be "level" : "3". When you use this data in D3 for calculation it will need to be a number again though so where you use it you can just use +data.xxx.yyy.level instead of data.xxx.yyy.level in the d3 code to turn it into a number. A: import csv import json file1 = csv.DictReader(open('filename.csv', 'r')) output =[] for each in complent: row = {} row['Id'] = each['Id'] row['Name'] = each['Name'] row['Address'] = each['Address'] row['Mobile'] = each['Mobile'] row['LandLine'] = each['LandLine'] row['Email'] = each['Email'] output.append(row) json.dump(output,open('new_file.json','w'),indent=4,sort_keys=False)
{ "language": "en", "url": "https://stackoverflow.com/questions/7520165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Should I provide an explicit back button in my view? When an application has a single view, the Back button probably resumes whatever previous application was running/suspended. I'm tempted to provide an explicit button which says 'Back' right there on the UI ... Should I provide an explicit back button in my view, or should I simply override the navigation button provided by the OS? My gut says the latter would be counter-intuitive. Are there any recommendations on this by the android community? A: That entirely depends on your application. Normally, your application is made out of multiple activities (Activity objects), and the back button will go to the previous activity. So if your app has a main menu (activity A), which has a button to go to search (activity B), which will lead to search results (activity C), then pressing the back button on the search page gets you back to the main menu. This is fully automatic, you don't need to write anything for this to work. That's how Android works, and that's how you should write your app. All Android devices have a device button (physical or on-screen, in case of Honeycomb), so don't waste precious screen real estate on a "back button". Don't be like the iPhone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need some help with basic HTML select and ie I reproduce the error in this jsfiddle : http://jsfiddle.net/DavidLaberge/KftG6/5/ Here is my HTML: <table id="infoMedicament" style="width:100%;"> <tr> <td style="width:50%">Value 1<br /> <select id="produit1" class="produit"> <option value="d02237726" >test1</option> <option value="d02326701" >test2</option> <option value="d02041421" >test3</option> <option value="d02240240" >test4</option> <option value="d00821772" >test5</option> <option value="d02225190" >test6</option> <option value="new">add</option> </select> </td> <td style="width:50%; vertical-align:top;">Search<br /> <input type="text" id="rechercheNouveauProduitTab2" style="width:250px;" /> </td> </tr> </table> It works fine in Chrome, but IE tries to open a popup. Any idea ? Here is a screen shot of the behavior I have. I have the popup blocker that appears right after I click on the <select> A: It's not your codes issue, jsfiddle.net coused it first two times for me :) A: You have incomplete code, try surrounding your form inputs with a tag, with some action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - create and call SOAP web service - error Every time i try to make a call to my webservice, through the wsdl, i get the error message shown here. I think its probably an issue within the the WSDL defintion, because I am not really sure what i am doing within the WSDL definition to begin with: [22-Sep-2011 18:54:46] PHP Fatal error: Uncaught SoapFault exception: [HTTP] Not Found in /www/zendserver/htdocs/dev/csc/request.php:4 Stack trace: #0 [internal function]: SoapClient->__doRequest('<?xml version="...', 'http://192.168....', 'http://www.exam...', 1, 0) #1 [internal function]: SoapClient->__call('EchoText', Array) #2 /www/zendserver/htdocs/dev/csc/request.php(4): SoapClient->EchoText('test') #3 {main} thrown in /www/zendserver/htdocs/dev/csc/request.php on line 4 I have a very simple web service, located at: http://192.168.1.2:10088/csc/csc.php <?php function EchoText($text){ return "ECHO: ".$text; } $server = new SoapServer(null, array('uri' => "http://192.168.1.2:10088/csc/csc.php")); $server->addFunction('EchoText'); $server->handle(); ?> I have an interfacing page, which is what i access and then get the error shown above, located at: http://192.168.1.2:10088/csc/request.php <?php $client = new SoapClient("http://192.168.1.2:10088/csc/NewWSDLFile.wsdl"); $result = $client->EchoText("test"); echo $result; >? I have my WSDL, located at: http://192.168.1.2:10088/csc/NewWSDLFile.wsdl <?xml version="1.0" encoding="UTF-8" standalone="no"?> <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://192.168.1.2:10088/csc/NewWSDLFile.wsdl" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="NewWSDLFile" targetNamespace="http://192.168.1.2:10088/csc/NewWSDLFile.wsdl"> <wsdl:types> <xsd:schema targetNamespace="http://192.168.1.2:10088/csc/NewWSDLFile.wsdl"> <xsd:element name="EchoText"> <xsd:complexType> <xsd:sequence> <xsd:element name="in" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="EchoTextResponse"> <xsd:complexType> <xsd:sequence> <xsd:element name="out" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> </wsdl:types> <wsdl:message name="EchoTextRequest"> <wsdl:part element="tns:EchoText" name="parameters"/> </wsdl:message> <wsdl:message name="EchoTextResponse"> <wsdl:part element="tns:EchoText" name="parameters"/> </wsdl:message> <wsdl:portType name="NewWSDLFile"> <wsdl:operation name="EchoText"> <wsdl:input message="tns:EchoTextRequest"/> <wsdl:output message="tns:EchoTextResponse"/> </wsdl:operation> </wsdl:portType> <wsdl:binding name="NewWSDLFileSOAP" type="tns:NewWSDLFile"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="EchoText"> <soap:operation soapAction="http://192.168.1.2:10088/csc/NewWSDLFile/EchoText"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="NewWSDLFile"> <wsdl:port binding="tns:NewWSDLFileSOAP" name="NewWSDLFileSOAP"> <soap:address location="http://192.168.1.2:10088/csc/csc.php"/> </wsdl:port> </wsdl:service> </wsdl:definitions> UPDATE.. I was able to get more detailed information on the error message by doing a try catch and print_r($e);... here is the detailed error message: SoapFault Object ( [message:protected] => Not Found [string:private] => [code:protected] => 0 [file:protected] => /www/zendserver/htdocs/dev/csc/request.php [line:protected] => 7 [trace:private] => Array ( [0] => Array ( [function] => __doRequest [class] => SoapClient [type] => -> [args] => Array ( [0] => [1] => http://192.168.1.2:10088/csc/csc.wsdl [2] => http://www.example.org/NewWSDLFile/EchoText [3] => 1 [4] => 0 ) ) [1] => Array ( [function] => __call [class] => SoapClient [type] => -> [args] => Array ( [0] => EchoText [1] => Array ( [0] => test ) ) ) [2] => Array ( [file] => /www/zendserver/htdocs/dev/csc/request.php [line] => 7 [function] => EchoText [class] => SoapClient [type] => -> [args] => Array ( [0] => test ) ) ) [faultstring] => Not Found [faultcode] => HTTP ) A: SoapFault => Not Found is that the SoapClient can't reach the server. 192.168.1.2 is a local IP-address, is the web server also on the local network? Otherwise that is the reason why your client isn't working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JAXB parsing "minOccours" - Problem with unmarshling I have following XSD which i used to generated JAXB objects <xs:complexType name="packageType"> <xs:sequence> <xs:element ref="package" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="dependencies" minOccurs="0"/> </xs:sequence> <xs:attribute name="id" type="xs:NMTOKEN" use="required"/> </xs:complexType> Now, If i receive an XML * *no dependency tag *empty dependency tag i.e. Sample XML <package id="FA33" required="false" empty="false"> <dependencies /> </package> In the above example, If i remove the "dependencies" empty tag, JAXB throws "unexpected end of package" error. Since the minOccours is there, both of these scenario shouldn't make a difference. But in my case, JAXB is unable to unmarsh the given xml in case1 i.e. if there is no dependency tag. If an empty dependencies tag is there then it goes fine. Is it expected behavior or its doing something wrong? P.S: I am using Jaxb 1.3 A: How about using JAXB 2? JAXB 1 used to validate on unmarshall. This was a problem since you couldn't really unmarshall invalid XML with missing mandatory elements etc. As far as I remember, I used to solve this problem by: * *Registering an "ignoring" validation handler *Generating schema-derived classes with a patched version of jaxb-xjc The handler is as follows: import javax.xml.bind.ValidationEventHandler; /** * Validation handler which ignores all the validation events. */ public class IgnoringValidationEventHandler implements ValidationEventHandler { /** * Static instance. */ public static final ValidationEventHandler INSTANCE = new IgnoringValidationEventHandler(); /** * Simply returns <code>true</code> * * @param event * ignored; * @return Always returns <code>true</code>. */ public boolean handleEvent(javax.xml.bind.ValidationEvent event) { return true; } } Register it via marshaller.setEventHandler(IgnoringValidationEventHandler.INSTANCE);. As for the patched jaxb-xjc, you may contact me via valikov(at)gmx.net, I can send you the jar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flex 4 List - scrollbars become visible and cover the itemrenderer I have a list inside a VDividedBox. When the box is resized so the vertical scrollbar shows on the list, it covers some of the itemrenderers. How do I get the list to resize horizontally so that the scrollbar does not cover the renderers? A: Actually, I'm fairly sure it's not the list scrollbar that's showing, but the VDividedBox's, hence why it's covering the list. It's a known bug in Flex 3. If I were you, I'd set the height of the list at 100% and remove the scrollbar by doing horizontalScollPolicy="off" on the VDividedBox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bash "diff" utility showing files as different when using a regex Ignore I'm trying to use the bash utility "diff" that is documented here: http://ss64.com/bash/diff.html. Note that I'm using a windows-ported version of the bash utility, but that shouldn't make any difference. I have two files, regex_test_1.txt and regex_test_2.txt that have the following contents: regex_test_1.txt: // $Id: some random id string $ more text text that matches regex_test_2.txt: // $Id: some more random id string $ more text text that matches I am trying to diff these files while ignoring any lines that fit this regex: .*\$(Id|Header|Date|DateTime|Change|File|Revision|Author):.*\$.* However, when I run diff and tell it to ignore lines matching this regex using the -I argument, this is the output: C:\Users\myname\Documents>diff -q -r -I ".*\$(Id|Header|Date|DateTime|Change|File|Revision|Author):.*\$.*" regex_test_1.txt regex_test_2.txt Files regex_test_1.txt and regex_test_2.txt differ I expect that it should find no differences (and report nothing). Why is it finding these files to be different? A: It's because diff uses basic regex syntax, wherein certain regex metacharacters lose their special meaning: In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). This should work: .*\$\(Id\|Header\|Date\|DateTime\|Change\|File\|Revision\|Author\):.*\$.* A: Just for giggles, add -b to your diff. Ignore differences in white space.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What function to use to select text? I search a lot of on internet but didn't find some good copy-paste manager for windows 7. I want to make something to easy copying multiple texts. So my question is what function to use in c++ to select some text that will be copy. The plan is that every time when is pressed CTRL+C selected text copy to some txt file, and when is pressed CTRL+V application show you what is in that file, and you can use what text you need. The main question is how to select text, what function to use? Platform win 7. A: You should read up a bit on how the Windows clip board works. Every application in the system can place objects of different formats (including text) on the clip board. The easiest way to grab the content out of any applications is probably to somehow monitor the clip board and get the data from there. For the pasting part, if I remember correctly, there is a special kind of "owner-handled" data on the clip board. Using that, the data isn't actually published on the clip board, only a reference to the application currently having the clip board data. Whenever the data is pasted the application gets notified that it should send the data to the recipient. It should be possible to exploit that functionality to get your application to pop up a windows where the user can select what data to paste. A: Please see my articles on clipboard viewer implementation, including common pitfalls: http://www.clipboardextender.com/developing-clipboard-aware-programs-for-windows/6 http://www.clipboardextender.com/developing-clipboard-aware-programs-for-windows/common-general-clipboard-mistakes
{ "language": "en", "url": "https://stackoverflow.com/questions/7520180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is there a way to use a ODTTF font file in my WPF app? When an XPS file is created, it subsets and obfuscates the original document's fonts as ODTTF font files, and bundles them in the XPS file (which is just a zip file, so they are easily extracted.) I've extracted one of these ODTTF files, and included it as a Resource in my WPF app. I'm now trying to use it as the FontFamily of a TextBlock. I tried various URI strings to reference the ODTTF font in my XAML, but I can't get it to work at all. (I can get a regular TTF file to work, just not an ODTTF) Is there a way to do this? I've found evidence in a few Google searches that people are managing to do this! A: ODTTF files are obfuscated. To use them as TTF you must deobfuscate them. You can use this code: void DeobfuscateFont(XpsFont font, string outname) { using (Stream stm = font.GetStream()) { using (FileStream fs = new FileStream(outname, FileMode.Create)) { byte[] dta = new byte[stm.Length]; stm.Read(dta, 0, dta.Length); if (font.IsObfuscated) { string guid = new Guid(font.Uri.GetFileName().Split('.')[0]).ToString("N"); byte[] guidBytes = new byte[16]; for (int i = 0; i < guidBytes.Length; i++) guidBytes[i] = Convert.ToByte(guid.Substring(i * 2, 2), 16); for (int i = 0; i < 32; i++) { int gi = guidBytes.Length - (i % guidBytes.Length) - 1; dta[i] ^= guidBytes[gi]; } } fs.Write(dta, 0, dta.Length); } } } Once written to a .TTF file this way you can use the font. Note that the fonts in XPS files are subsets, only containing those characters actually used in the XPS file, so they won't be useful to use in, say, MS-Word as a font.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Trouble in getting proper string input I am writing a method in Java in which the user is supposed to enter a license plate for a car. The fist two signs must be capital letters, the third sign must be a digit between 1 and 9, and the last 4 digits must be digits between 0 and 9. If the user does not enter this properly, an error message should appear, and the user will be asked to input the license plate again. After testing the problem I have discovered that if I deliberately make many different mistakes over and over, and then finally enter the license plate correctly, the program still informs me that my input is wrong. I am having a hard time knowing how to construct this, since it is supposed to take into account so many possible errors. My code presently looks like this for the method in question: char sign; System.out.print("License plate: "); licensePlate = input.next(); for (int index = 0; index < 2; indeks++) { sign = licensePlate.charAt(indeks); while (sign < 'A' || sign > 'Z') { System.out.println(licensePlate + " is not a valid license plate (two big letters + five digits where the first digit can not be 0)"); System.out.print("License plate: "); licensePlate = input.next(); } } while (licensePlate.charAt(2) < '1' || licensePlate.charAt(2) > '9') { System.out.println(licensePlate + " is not a valid license plate (two big letters + five digits where the first digit can not be 0)"); System.out.print("License plate: "); licensePlate = input.next(); } for (int counter = 3; counter < 7; counter++) { sign = licensePlate.charAt(teller); while (sign < '0' || sign > '9') { System.out.println(licensePlate + " is not a valid license plate (two big letters + five digits where the first digit can not be 0)"); System.out.print("License plate: "); licensePlate = input.next(); } } carObject.setLicensePlate(licensePlate); If anyone can help me writing this properly I would be extremely grateful! A: The problem is that you're taking new input every so often, but then not starting again. It would be worth having a separate method to perform the test, like this: boolean gotPlate = false; String plate = null; while (!gotPlate) { System.out.print("License plate: "); plate = input.next(); gotPlate = checkPlate(plate); } carObject.setLicensePlate(plate); Now put the rest of your logic into the checkPlate method: static boolean checkPlate(String plate) { // Fixed typos here, by the way... for (int index = 0; index < 2; index++) { char sign = plate.charAt(index); if (sign < 'A' || sign > 'Z') { System.out.println(plate + " is not a valid license plate " + "(two big letters + five digits where the first digit" + " can not be 0)"); return false; } } // Now do the same for the next bits... // At the end, if everything is valid, return true return true; } I'll leave you to do the checking for '0' etc - but hopefully you can see the benefits in structuring the "testing" part separately from the "getting input" part. EDIT: Original answer... Sounds like you want a regular expression: Pattern pattern = Pattern.compile("[A-Z]{2}[1-9][0-9]{4}"); Full sample: import java.util.regex.*; public class Test { private static final Pattern PLATE_PATTERN = Pattern.compile("[A-Z]{2}[1-9][0-9]{4}"); public static void main(String args[]) { checkPlate("AB10000"); checkPlate("AB10000BBB"); checkPlate("AB1CCC0BBB"); } static void checkPlate(String plate) { boolean match = PLATE_PATTERN.matcher(plate).matches(); System.out.println(plate + " correct? " + match); } } Of course, that doesn't tell you which bit was wrong. It also doesn't help you work out what was wrong with your original code... see earlier part. A: Don't use a character based approach. Take the whole string and use the regex list above and either fail or pass it as a one time operation. You don't need that level of control here to get a pass/fail result. HTH, James A: You should really use a regular expression for this. However, if you want to fix the problem with your code: the problem with your approach is that you are asking for input again after you've done some validation. For example, if the first two characters are correct, the second loop will validate the input single-handedly. If that's wrong and it asks for input again, the user could input the first two characters incorrectly and that check won't be done because the code will have passed the first stage and is now only checking the second stage. If you were to continue with your approach, you should make one large loop which would repeat if anything is wrong in the input and do all of the checks again in order.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: View HTML of jQuery injected code I'm thinking of using a couple jQuery tools/plugins to dynamically change the DOM of a page: http://plugins.jquery.com/project/appendDom http://www.botsko.net/blog/2009/04/07/jquery-form-builder-plugin/ When the new DOM is changed, I can use Firebug to see the new elements as they are added, but I'm wondering if anyone has suggestions on how I can also build an .html page that can be saved off after a number of elements have been added. My ultimate goal is to create an HTML Form Builder that will generate the HTML output so I can save the work as I go along. I also want to take the output that was generated and upload it, have it parsed, which will allow me to continue working at another time. Any thoughts on how to at least get the .html file would be great or tools that I can use. A: Assuming that you will just be needing the bits inside the body tag of the page you can get the HTML with document.body.outerHTML. A: You can use the native outerHTML: vat thehtml = $('#yourElement')[0].outerHTML; A: You could use jQuery to get the HTML of the entire <body> section: $('body').html();
{ "language": "en", "url": "https://stackoverflow.com/questions/7520189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rails 3 application, how to measure stability under high loads Hi I'm a new programmer and I've been working on my first real application that I'm going to launch in the coming weeks. The app uses some neat ideas around photo sharing, but basically is just a photo sharing web app. I'd like to find information out about what type of loads a small rails 3 application can handle but I'm not sure where to start. Do I need to run benchmarking tests to find how many requests it can handle and how fast it does this? How does one find statistics like this for their application? Ultimately I'd like an idea of the maximum amount of traffic the site could handle, or could someday handle, to get my barings down with what I'm working with. I wouldn't want to set in motion a viral marketing campaign if the site couldn't handle over a few hundred concurrent requests. I'm not trying to jump the gun and prepare for a ton of traffic that I don't have yet, but I really would like to have some understanding and an idea of where to go next in terms how the usability and scalability of my application. Thanks a lot! A: The bigger question here is where are you deploying your application: I host some of mine on a linode instance, using nginx / unicorn. It's substantially more work but I like it. I don't bother load testing much but sometimes I hit the home pages hard with Siege (you can install it with homebrew, brew install siege) to get a feel of what I am working with. While on the subject of deploying, I would think getting paid hosting from Heroku would eleviate some of your concerns about stability, upgrading your app settings to survive bigger loads. Can you give us more information on your hosting choices? A: "what type of loads a xxxx application can handle" You are correct. To answer this, we test! Without testing, we can't simply say something as broad as our ruby application, running on 2 dyno's from heroku, can handle 100 requests/sec, or 100 concurrent users. We need to test. Scaling can also be a tricky business. Without testing, we won't know which components scale well, and which ones won't. To get started, we have our application, the system under test. We are already running on Heroku, which gives us immediate access to the New Relic add on. We could try turning on the free version of New Relic to see what information it gives us. There is a pay version we could also try out during our 'tuning sessions' if we need to dive further. Then we are just missing the 'driver', the process that will drive load against the application, using the most common process flows (uploading images, browsing images, logging in, etc). To get started, we just need 1-N of our closest friends willing to act as users on our site while we monitor all the activity from New Relic. Measuring response times for user experiences, identifying slow running queries, see where our application is spending its time. When we get tired of buying our friends all the beer for helping us we can look at automating some those common business flows using a load testing tool. There are commercial ones: Mercury LoadRunner, Borland SilkPerformer and Microsoft Team Test. We might also get creative using functional testing tools such as Watir or Selenium, or even trusty wget, or curl, to drive load. We can use our laptop(s), or Amazon EC2, as load agents, which would be generating user traffic on the site by running our scripts. It doesn't have to be as hard as all this, though testing generally spirals into a quagmire if we aren't careful to make sure we are testing the right flows and maybe just as important, measuring our application. Without measurements, we won't know if changes to code or configuration, made things better or worse. disclaimer: I've never had a production Rails application, but if I did, I'd use New Relic to monitor it. At least to start, especially since we are already on Heroku. A: I have not tried it yet but I heard about: http://blitz.io/ Looks good and is supported by Heroku via Add-On
{ "language": "en", "url": "https://stackoverflow.com/questions/7520192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I add Devise's 'timeoutable' module to an existing Devise install? - Rails 3.1 These are the instructions to add a module to an existing Devise install: https://github.com/plataformatec/devise/wiki/How-To:-change-an-already-existing-table-to-add-devise-required-columns But I can't seem to locate the necessary columns for timeoutable. I looked for the fields that timeoutable requires in the Devise library: https://github.com/plataformatec/devise/blob/master/lib/devise/schema.rb - but there is no such method in that schema file. The model just has a custom method with no reference to the columns: http://rdoc.info/github/plataformatec/devise/master/Devise/Models/Timeoutable How do I add that functionality? Thanks. A: timeoutable refers to the login session timeout. No extra columns are needed, just add it to your model. The timeoutable hook contains all the magic (source: https://github.com/plataformatec/devise/blob/master/lib/devise/hooks/timeoutable.rb) A: You only need add timeoutable to your user model: devise :timeoutable And set the interval time in config/initializers/devise.rb: # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. config.timeout_in = 30.minutes A: Just add to your model: devise :timeoutable, timeout_in: XX.minutes replace XX with the number of minutes you want. A: timeoutable not working if you are have remember_me = true https://github.com/plataformatec/devise/blob/master/lib/devise/hooks/timeoutable.rb#L26
{ "language": "en", "url": "https://stackoverflow.com/questions/7520195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: How do I unit test the zend action controller? I need to rapidly build good software in php and using the zend framework. I try to go at this in a TDD way because its people more experienced than me told me that was the best way to rapidly build while keeping your code manageable. So I got the book on phpunit and went along nicely and indeed after the initial hassle it starts to speed up and the code is still nice. I kind off like how my objects can be tested individually. There is however one major problem with testing the zend action controller. The zend_test package provides a way to test it. But that seems to test the entire application at once. I don't seem to be able to nicely stub or mock any repository's or inject any other dependency's . So i've not been able to test them as extensively as i could do with the rest of the project and it shows. I've been looking to solve this problem. But all i could find on the net was the zend_test way of doing it. I would like to know your opinion on this. Maybe i am just trying to over do things or maybe there is a nicer way to develop the unit test for the zend action controllers. A: In Zend 1 a controller is a normal class. You can instantiate it, you can call methods on it (for example, replacing your default repository with a PHPUnit mock of your repository: class MyController extends Zend_Controller_Action { public functioni init() { $this->repository = new MyRepository(); } public function setRepository($repository) { $this->repository = $repository; } public function saveAction() { $dataToWrite = manipulate in some way $this->getRequest()->getParams(); $this->repository->update($dataToWrite, ...); } } But you must also inject a request, and dispatch it to get the response. Personally for controllers I prefer to write functional tests rather than unit tests (with Zend_Test). It's slower, you will probably need an in-memory sqlite database, and so on. But you will know if your application really works: you can unit test every class, but if a factory that wires your objects is wrong, you will continue to get a green PHPUnit bar with a broken application. A: Rob Allen wrote a very good article on testing Zend Controller Actions with PHPUnit. This uses Zend_Test_PHPUnit_ControllerTestCase, which bootstraps the whole application and tests the reponse. PHPUnit and functional testing in general are not suited to testing controllers. Inversely, controllers are not suited to unit testing. By that I mean that the concept of unit testing doesn't make sense with concept of the controller layer, and controllers typically are constructed in a way that makes them inherently difficult to unit test. The best alternative I can suggest is to use Selenium. This tests the response from the controller (so really tests the View in most cases). On top of the Selenium tests, you should also be unit testing your models and the rest of your library. That's about as bulletproof as you can really get in your controller layer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Mobile Forms Select is not the same size as Input or textarea I have a mobile page including a form. I need to align the select and input/textarea and make them the same size but it's not working properly. (see image) As you can see in the screenshot, the dropdown is not the same size as the input or textarea. Here's my code: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en' xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" /> </head> <style type="text/css"> select, input, textarea { border: solid 0.1em black; font: normal 1.5em Arial; margin: 0.3em 0; padding: 0.2em; } .em { width: 11em; } .px { width: 150px; } .percent { width: 50%; } </style> <select name="option1" class="em"> <option value="" selected="">= choose =</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <input name="input" type="text" value="" class="em" /> <textarea class="em"></textarea> <hr /> <select name="option1" class="px"> <option value="" selected="">= choose =</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <input name="input" type="text" value="" class="px" /> <textarea class="px"></textarea> <hr /> <select name="option1" class="percent"> <option value="" selected="">= choose =</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <input name="input" type="text" value="" class="percent" /> <textarea class="percent"></textarea> </body> </html> What am I doing wrong or what should I do? A: Here's what you have to do: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Mobile</title> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" /> </head> <body> <style type="text/css"> body { margin: 0; padding: 0.3em; } form { padding: 0px; margin: 0px; } select, input,textarea { border: solid 1px #888; display: block; font: normal 1.4em Arial; max-width: 100% !important; margin: 0.2em 0 !important; padding: 0.1em 0 !important; text-indent: 0 !important; white-space: nowrap; text-overflow:ellipsis; width: 98% !important; outline: none; word-wrap: break-word; word-wrap: break-all; white-space: nowrap; ms-box-sizing:content-box; -moz-box-sizing:content-box; -webkit-box-sizing:content-box; box-sizing:content-box; } </style> <form> <select name="option1" class="em"> <option value="" selected="">= choose =</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <input name="input" type="text" value="" /> <input name="input" type="email" value="" /> <input name="input" type="url" value="" /> <input name="input" type="tel" value="" /> <textarea class="em"></textarea> </form> </body> </html> The select box is not 100% aligned but it's pretty close.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what happens when I read/write the same file? I'm learning about NodeJS's event model. I'm confused about the output. the code simply write some text to a file and read it back. the execution order seems out of my control. var fs = require('fs'); var ws = fs.createWriteStream("my_file.txt"); ws.once('open', function(fd) { console.log( 'ws_open' ); ws.write("My first row\n"); ws.write("My second row\n"); ws.write("My third row\n"); ws.destroySoon(); }); ws.once('close', function() { console.log( 'ws_close'); }); var rs = fs.createReadStream("my_file.txt"); rs.setEncoding('utf8'); rs.once('open', function(fd) { console.log( 'rs_open' ); }); rs.once('close', function() { console.log( 'rs_close'); }); rs.once('data', function(data) { console.log( 'rs_data' ); console.log( data ); }); rs.once('error', function(exception) { console.log( 'rs_exception' ); console.log( exception ); }); Here is the output. rs_open ws_open rs_close ws_close Sometimes, it becomes ws_open rs_open rs_data My first row rs_close ws_close Can anyone give me some explanation? Thank in advance. A: You are doing asynchronous stuff as if it is synchronous. Just because something is lower in the code doesn't mean it happens later. If you don't want to read the file until you are done writing it, put your read inside the callback for the write. as in : (simplified) writeFile (name, writeData, function (error) { if (error) .... // handle error else { // successfully wrote file readFile(name, function (error, readData) { if (error) .... // handle error else { // successfully read file ... // do something with readData } }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7520212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: More specific constraints in derived classes using JSR-303 Lets say there's a class Money that has fields amount and currency: class Money { private int amount; @NotNull Currency currency; } While Price is also money it introduces additional constraint: amount cannot be negative class Price extends Money { // add more specific constraint for amount field: @Min(0) } Is it possible to express this using JSR-303? A: Introducing a property level constraint should do the job: class Price extends Money { @Min(0) int getAmount() { return super.getAmount(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7520215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to ship a Windows Forms application to a client without .NET? This is about the deployment of a Windows Forms application. I have created a Windows Forms application, but I'm not sure if the users have installed .NET version 4. I have put my Windows Forms application at my website and the users will download it to their desktop. How do I automate the process of downloading and installing .NET 4 if the users have not installed it? What are the recommended ways of deploying Windows Forms applications to users? A: You could try ClickOnce. ClickOnce deployment allows you to publish Windows-based applications to a Web server or network file share for simplified installation. You just need to define which prerequisites you want to include in bootstraper, as described here A: You could define prerequisites in your Setup And Deployment Project. A: You need to provide an installer and mark .NET as a prerequisite. See Stack Overflow question How to make an installer for my C# application? (.NET 3.5, but the idea is the same). A: You could always download and include the .NET 4 redistributable. It about 40 MB so it may not be the most optimal solution, but it may be the easiest for the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Linq-to-sql Delete a record with FK constraints Is it possible to SubmitChanges and ignore deletes that cause Foreign Key constraint errors? Say I have object A and B. B's Primary Key is a Foreign Key in A. Now I change a record A in which I replace B for another B and delete the original B. An error will occur when the deleted B is referenced in another record A (or other tables containing B as Foreign Key). Is it possible to ignore the error and let the changes be made in the database, without deleting the old B? A rec_a = (from a in db.As where a.id == some_id).First(); B rec_b_old = rec_a.B; rec_a.B = null; db.Bs.DeleteOnSubmit(rec_b_old); rec_a.B = some_other_b; db.SubmitChanges(); A: Make two calls to SubmitChanges(): A rec_a = (from a in db.As where a.id == some_id).First(); B rec_b_old = rec_a.B; rec_a.B = null; rec_a.B = some_other_b; db.SubmitChanges(); db.Bs.DeleteOnSubmit(rec_b_old); try { db.SubmitChanges(); } catch(SqlException) { } // Ignore failed delete. The second one might fail and in that case just ignore it. It is possible to try to submit everything, dig out the failing update/delete, remove it from the pending list and retry. However it requires far more code so I don't think it's worth to do it here. Another solution is to put a trigger on the A table that deletes the B record if it is orphaned. A: LINQ to SQL does not support cascading delete operations. You will need to either tell the database itself to do that or delete the child rows yourself first. See Insert, Update, and Delete Operations (LINQ to SQL) for a detailed explanation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to move image down using vba in powerpoint from excel? I am new to vba and macros in powerpoint.. What is the correct syntax to position an image down -30? PPT.ActiveWindow.View.GotoSlide 9 Set PPApp = GetObject(, "Powerpoint.Application") ' Reference active presentation Set PPPres = PPApp.ActivePresentation ' Reference active slide Set PPSlide = PPPres.Slides _ (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex) ' Copy chart as a picture ActiveChart.CopyPicture Appearance:=xlScreen, Size:=xlScreen, _ Format:=xlPicture ' Paste chart PPSlide.Shapes.Paste.Select ' Align pasted chart Dim xyz As Shape Set xyz = PPSlide.Shapes.Selection PPApp.ActiveWindow.Selection.ShapeRange.Align msoAlignCenters, True PPApp.ActiveWindow.Selection.ShapeRange.Align msoAlignMiddles, True xyz.Top = xyz.Top - 30 A: UPDATED Based on your code sample, I think you want to try something like this: PPSlide.Shapes.Paste.Select ' Align pasted chart PPApp.ActiveWindow.Selection.ShapeRange.Align msoAlignCenters, True PPApp.ActiveWindow.Selection.ShapeRange.Align msoAlignMiddles, True PPApp.ActiveWindow.Selection.ShapeRange(1).Top = PPApp.ActiveWindow.Selection.ShapeRange(1).Top + 30 You can take out the lines referring to xyz.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: outside f:ajax for composite component Is there a way I can create a composite component that can receive an <f:ajax> tag from outside? I'm creating an editableText input composite component and I want to show to end user the option to append an <f:ajax> tag inside the input tag of my component. Is there a way to make it using composite component? EditableValueHolder don't support <f:ajax>. A: I've solved the problem a week ago. I didn't posted the answer here cause I was full of work and I forgot it. :) Just need use this tag: <c:clientBehavior name="blur" default="true" event="blur" targets="input" /> accordingly with this IBM page, this tag isn't documented, probably is the reason to be so difficult to find it. Thanks for your attention.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Need a simple tutorial for android/webservice work? I'm really new working with Android, so there's a lot that's confusing me. I've looked at what seems like 100 tutorials and examples of how to get information from a web service on Android, but what I need is something for a guy that doesn't have a clue. Here are a couple of things in particular that I'm not getting: * *I don't know what to do with XML files.. meaning, once I do the Java work, is that all that needs to be done? or does anything need to be changed in the XML files? *Seems like maybe I'm supposed to create a new class for some of these tutorials, but I'm not sure, and if so, I'm not sure what to do once I've made the class *I want to retrieve the information in JSON format. For right now as long as I can get just that information that's fine, I can learn how to work with JSON later. *It seems like kSoap2 is the best way to do this. I have the jar file that's needed to work with it *I've delved a little into phonegap, so if there's an answer that uses that, then I can work with that My web service is working properly, and is essentially the same as what I've seen in a number of tutorials, so there's no problem there. If anyone can point me to a tutorial that will help me out to learn ALL that I need to know to create a sample app that gets information from my web service, or if anyone is willing to walk me through it, I would greatly appreciate it! Thanks in advance! A: Initially you have to make an http connection so that you can get the response from your api be it xml response or json response. You can use the following code for it. Keep the class separate than activity. :- public class Response { String get_url, response; Activity activity; public Response(String url){ this.get_url = url; } public String getResponse(){ InputStream in = null; byte[] data = new byte[1000]; try { URL url = new URL(get_url); URLConnection conn = url.openConnection(); conn.connect(); /* conn.*/ in = conn.getInputStream(); Log.d("Buffer Size +++++++++++++", ""+in.toString().length()); BufferedReader rd = new BufferedReader(new InputStreamReader(in),in.toString().length()); String line; StringBuilder sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); response = sb.toString(); in.read(data); Log.d("INPUT STREAM PROFILE RESPONSE",response); in.close(); } catch (IOException e1) { Log.d("CONNECTION ERROR", "+++++++++++++++++++++++++++"); // TODO Auto-generated catch block e1.printStackTrace(); } return response; } } You may call the class in your activity like this :- Response res = new Response("your_url"); String getResponse = res.getResponse(); So here you get the response from the api. Now Lets make the parser //Extend the class with Default Handler public class XMLParser extends DefaultHandler { //You must have basic knowledge about Array List and setter/getter methods // This is where the data will be stored ArrayList<Item> itemsList; Item item; String data; String type; private String tempVal; //Create the Constructor public XMLParser(String data){ itemsList = new ArrayList<Item>(); this.data = data; } public byte parse(){ SAXParserFactory spf = null; SAXParser sp = null; InputStream inputStream = null; try { inputStream = new ByteArrayInputStream(data.getBytes()); spf = SAXParserFactory.newInstance(); if (spf != null) { sp = spf.newSAXParser(); sp.parse(inputStream, this); } } /* * Exceptions need to be handled MalformedURLException * ParserConfigurationException IOException SAXException */ catch (Exception e) { System.out.println("Exception: " + e); e.printStackTrace(); } finally { try { if (inputStream != null) inputStream.close(); } catch (Exception e) { } } if (itemsList != null && itemsList.size() > 0) { // //Log.d("Array List Size",""+tipsList.get(4).getTitle()); return 1; } else { return 0; } } public ArrayList<Item> getItemList(){ return itemsList; } // Here you can check for the xml Tags @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if(localName.equalsIgnoreCase("item")){ item = new Item(); Log.d("Working", "+++++++++++++++++++++++"); } } //tempVal is the variable which stores text temporarily and you // may save the data in arraylists public void characters(char[] ch, int start, int length) throws SAXException { tempVal = new String(ch, start, length); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if(localName.equalsIgnoreCase("item")){ itemsList.add(item); Log.d("Working in endelement", "+++++++++++++++++++++++"); item.setTitle(tempVal); } } Combining all this :- Now lets see the activity public void oncreate(){ // Do something or mostly the basic code // Call the class to initate the connection and get the data FetchList fl = new FetchList(); fl.execute(); } //Always better to use async task for these purposes public class FetchList extends asyncTask<Void,Void,Byte>{ doinbackground{ // this was explained in first step Response res = new Response("url"); String response = res.getResponse(); XmlParser xml = new XmlParser(response); ArrayList<item> itemList = xml.getItemList(); xml.parse(); } } Well that is all to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alertdialog with integrated buttons in the message I want to do something like Terms of Service in an AlertDialog (it must pop up) where the user has to scroll to the bottom to see the "accept" or possible an accompanying decline button. Is there a way to include buttons in the AlertDialogs MESSAGE that the user must scroll through? Similarly another implementation would just be to have the button unpressable until the user scrolls to the bottom, how would I do that? Insight appreciated! A: I suppose you could always create a custom Dialog and show that. There's a guide on how to do that on the Android developer site right here: http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog An alternative would be to create a regular class with its own layout and then set the theme to the dialog theme. This will look like a dialog when opening, and allows for pretty much the same functionality as any other Activity. A: I believe what you can do is, compare the bottom position of the last item in the dialog, which would be the textview, to the bottom of the scrollview in the onScrollChanged listener. This way, when the user has reached the bottom, you can call AlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true); A: Here you go: AlertDialog.Builder dBuilder = new AlertDialog.Builder(this); dBuilder.setMessage(msg) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("Accept", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { /// YOUR OK PART }); AlertDialog alert = dBuilder.create(); alert.show(); Obviously msg contains your... message :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7520244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to trigger navigationController:willShowViewController delegate method in AppDelegate How can I trigger the navigationController:willShowViewController delegate method for my implementation below so that all the view controllers in the navigation controller will conform to the colorWithHexString #faf6f5? Currently, my FirstViewController will be displayed but it doesn't seem to call the delegate method to change the color of it's navigation bar (as well as for all other view controllers that are stacked onto the navigation controller subsequently). Note that I have already added the "UINavigationControllerDelegate" to my app delegate header file. //In App Delegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //Set First View FirstViewController *firstView = [[FirstViewController alloc]init]; // pushes a nav con UINavigationController *tempNavcon = [[UINavigationController alloc]initWithRootViewController:firstView]; self.navcon = tempNavcon; [self.window addSubview:navcon.view]; } - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{ navigationController.navigationBar.tintColor = [UIColor colorWithHexString:@"#faf6f5"]; } A: is there a reason why you are trying to change the tintColor in an event method rather than when the UINavigationBar instance is created? A: Here's how you do it. (Note that UIColor doesn't accept hex values; you should use an RGB value, or check this page. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //Initialize your view controller. FirstViewController * firstView = [[FirstViewController alloc] init]; // Create an instance of a UINavigationController. Its stack contains only firstView. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:firstView]; //Here is where you set the color of the navigationBar. See my note above for using RGB. navController.navigationBar.tintColor = [UIColor greenColor]; // You can now release the firstView here, navController will retain it [firstView release]; // Place navigation controller's view in the window hierarchy [[self window] setRootViewController:navController]; [navController release]; [self.window makeKeyAndVisible]; return YES; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7520247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: effective java builder idiom equivalent in c++? This is a great idiom I've been using since reading Effective Java. I've been trying to find a C++ equivalent or something similar and have had little luck. The traditional builder pattern found in the GoF book isn't really applicable in my case. It's one complicated object that has a very messy constructor. Below is a small implementation of the Java. class ComplicatedObject { private String field1; private String field2; private int field3; private ComplicatedObject(Builder builder) { this.field1 = builder.myField1; this.field2 = builder.myField2; this.field3 = builder.myField3; } public static class Builder { private String myField1 = "some default"; private String myField2 = "some other default"; private int myField3 = -1; public Builder() { } public Builder field1(String val) { this.myField1 = val; return this; } public Builder field2(String val) { this.myField2 = val; return this; } public Builder field3(int val) { this.myField3 = val; return this; } public ComplicatedObject build() { return new ComplicatedObject(this); } } public static void main(final String[] args) { //built like this ComplicatedObject obj = new ComplicatedObject.Builder().field1("blah").field2("lol").field3(4).build(); } } A: #include <iostream> #include <string> using namespace std; class ComplicatedObject { public: class Builder { friend class ComplicatedObject; private: string myField1; private: string myField2; private: int myField3; public: Builder() : myField1("some default"), myField2 ("some other default"), myField3(-1) { } public: Builder& field1(const string& val) { myField1 = val; return *this; } public: Builder& field2(const string& val) { myField2 = val; return *this; } public: Builder& field3(int val) { myField3 = val; return *this; } public: ComplicatedObject build() { return ComplicatedObject(*this); } }; private: string field1; private: string field2; private: int field3; private: ComplicatedObject(const Builder& builder) :field1(builder.myField1), field2(builder.myField2), field3(builder.myField3) {} }; int main(int argc, char** argv) { if (argc < 4) { std::cout << "not enough params."; return 1; } ComplicatedObject obj(ComplicatedObject::Builder().field1("blah").field2("lol").field3(4)); } I made minimal changes to make it C++, fast, and safe. http://ideone.com/sCH1V A: Not only can it be adapted to C++ but rather the idiom has been adapted from C++. I think the first time I heard of this idiom was before Java came into existence. IIRC Bjarne Stroustrup mentions this in C++ 2nd Edition as an explanation of why C++ does not need Smalltalk style named parameters. I could have my dates wrong but this is about 15 years old in C++. EDIT: It seems it wad first described in Design and Evolution of C++ (6.5.1) where it was called named function parameters
{ "language": "en", "url": "https://stackoverflow.com/questions/7520250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Custom order by string parameter in HQL I had an HQL query like this: Query query = session.createQuery("from User as user where user.joined!=null order by user.joined desc"); How do I set a variable User property as the sort order for my query? My solution: String order = "user.joined"; Query query = session.createQuery("from User as user where user.joined!=null order by :order desc").setString("order", order); does not give an ordered query result. A: Use a criteria query. List<User> users = session.createCriteria(User.class) .add(Restrictions.isNotNull("joined")) .addOrder(Order.desc(order)) .list(); Or, using HQL: Query query = session.createQuery("from User as user where user.joined!=null order by user." + order + " desc"); A: In your second query, when you use this method call: [Hibernate Query object].setString("order", order) You are trying to bind a column name as a parameter, which is not possible. What is a parameter (for this concern) follows the SQL parameters definition, wich is also the parameter definition used in JDBC API PreparedStatement. To dynamically build a query (besides it's parameters) there are other solutions like the ones pointed by Matt Ball. You could also see Using a prepared statement and variable bind Order By in Java with JDBC driver.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Program never seems to get to the onclick listen Hi below is some code ive been playing with but when i debug it never gets to the onitemclicklisten routine can anyone help? package sanderson.swords.mobilesales; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.app.ListActivity; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; public class OrderProductSearch extends Activity { ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); HashMap<String,String> item = new HashMap<String,String>(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try{ setContentView(R.layout.orderproducts); } catch (Exception e) { // String shaw=""; shaw = e.getMessage(); } //Create view of the list where content will be stored final ListView listContent = (ListView)findViewById(R.id.orderproductlistview); //Set for fast scrolling listContent.setFastScrollEnabled(true); //Create instance of the database final DbAdapter db = new DbAdapter(this); //Open the Database and read from it db.openToRead(); //Routine to call all product sub groups from the database final Cursor cursor = db.getAllSubGroupProduct(); //Manages the cursor startManagingCursor(cursor); int i=0; cursor.moveToFirst(); while (cursor.getPosition() < cursor.getCount()) { item.put("ProdName",cursor.getString(2)); item.put("ProdSize", cursor.getString(3)); item.put("ProdPack",cursor.getString(4)); item.put("OrdQty","0"); //list.add(item); list.add(i, item); item = new HashMap<String,String>(); cursor.moveToNext(); i = i + 1; } String[] from = new String[] {"ProdName", "ProdSize", "ProdPack", "OrdQty"}; int[] to = new int[] { R.id.productlinerow, R.id.productlinerow2, R.id.productlinerow3, R.id.productlinerow4}; SimpleAdapter notes = new SimpleAdapter(OrderProductSearch.this,list,R.layout.productlinerow,from,to); listContent.setAdapter(notes); //Close the database db.close(); listContent.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String neil = "test"; neil = neil + "test"; } }); } } A: If you set a breakpoint at listContent.setOnItemClickListener(new OnItemClickListener() { it may not break when you click. Try setting a breakpoint at String neil = "test"; and debugging. A: An easier way to verify the click listener is to add some logcat prints in it, e.g. listContent.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d(TAG, "Click!"); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7520256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open a modal from a modal with SimpleModal by Eric Martin I'm using SimpleModal by Eric Martin to create modals for a project, and I have a situation where I need to open a second modal on top of a modal that I already have open. Does anybody know how I can achieve this? A: Eric Martin, could answer better (I know he uses SO as his tech support venue), but I'm fairly certain that SimpleModal is a single instance only plugin. I say this because a single overlay (div) is created to accommodate multiple dialogues on a page, and you can not display more than one dialogue at a time. Proof: http://jsfiddle.net/QtbQQ/2/ To accommodate dialogues within dialogues, I'd imagine that you'd need to heavily modify this plugin. For instance: * *$.modal.close(); Need update to target specific modal dialogues. *Create a dialogue hierarchy model (parent-child relationships). *You'll need to dynamically adjust the z-index of the overlay to cover all parent dialogues as their children are created. In short, this all seems very possible, but it is certainly not supported by this plugin as is. Perhaps you could put a prototype together and see if Eric would add it in! A: There is a "hack" around it: your-container.modal( { onOpen: function () { var oldContent = escape(your-container).html(); }, onClose: function () { your-container.html(unescape(oldContent)).css('height','auto').css('width','auto'); } }); Also, Eric mentions the "persist" which I haven't being able to understand but, for what I could gather, it has to do with keeping DOM related stuff persistent across modals. In this case, modal( { persist:true } ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7520263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find nanoparticles I need some help. I have this sample: which is a piece of plastic with some nanoparticles inside (you can see the small black dots). Can someone help me figure out a quick and dirty algorithm where I can find the particles and color them in another color. A: Quick and dirty... OK :) * *[optional] blur it even more *find local minimums which: * *are <= any neighbour in some radius (the radius should be close to expected radius of a particle) *2.2. are <= (average-threshold), this threshold is for filtering out false detections due to noise A: You say quick 'n dirty, but given this is matlab you probably won't notice a difference between the best solution and a "quick and dirty one". Here is what is probably straight-up the best way to accomplish the task: Scale-space blob detection. Using the laplacian method is the simplest. Start by Gaussian-blurring you image with a sigma close to that of your expected nano particle standard deviation: IE a quarter of its screen width. Then your blobs will be the points where the Laplacian is most-negative; ensuring that it has greater magnitude than its surrounding points followed by a simple thresholding will do. To see how to implement this in matlab go to: http://dl.acm.org/citation.cfm?id=363419.363423 It will only be about 10 lines of code. Also, remember to work on a logarithmic (decibel) scale as you are dealing with transmission rather than reflection. A: This isn't in Matlab, but the WolframBlog covered something like this for Mathematica and it may suit your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript - how does this button fires something? Javascript is not my speciality. I have a page that contains an image. This image, when clicked, fires an Ajax code, that shows a floating box. Analyzing the page code, I don't see how this button can fire the code. The button is declared like this: <div class="leaderboard-text"> <span id="addon-add-language-button"> <image class="ajaxListAddButtonEnabled" listId="localizationList" src="/itc/images/blue-add-language-button.png" /> <image class="ajaxListAddButtonDisabled" listId="localizationList" style="display:none;" src="/itc/images/blue-add-language-button-disabled.png" /> </span> </div> just after this code, I see this var being declared: <script language = "Javascript"> var createList_localizationList = function() { var reorderEnabled = false; var preventLastRowDeletion = false; var searchEnabled = false; var list = new LCAjaxList(); list.initialize(): } document.observe("dom:loaded", createList_localizationList); </script> As far as I see, the image is firing somehow this javascript, but how can the button do that if there's no "onclick" or href reference tied to it? Where is the line that tells which method should run when the image is clicked? What should I look on the code to get a clue how this button works? What I need is to fire the method used by this button using javascript. any clues? ================ after reading all that you guys have written, I have used Safari's Inspect Element and identified this listener attached to the object: is this of any help? Now the question: how do I fire the method associated with this image from javascript? Thanks guys. A: When the DOM is completely loaded on the page it fires the event listener "createList_localizationList", so there is no need for a user to click on anything. You can add an event liseter to the button for onclick, instead of when the DOM loads with your button. You could try this: $('ajaxListAddButtonEnabled').observe('click', createList_localizationList); I am not sure if that class is used again, but maybe if you add an id to that element (id='someidname') to make sure you are not adding this to another element on the page. A: What you're looking for is .observe. That adds an event listener, so somewhere there may be $('addon-add-language-button').observe('click', SomeFunction) Event listeners are the preferred way to handle javascript events, rather than using an HTML onClick. A: My guess is that it's either one of the two statements var list = new LCAjaxList(); list.initialize(): They seem really bad designed. A list object should take a DOM object to act upon. LCAjaxList probably hardcodes the element to bind to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting the position of setImage and setTitle of UIButton I want to have a large button the spans the length of my table cells that contains a setImage icon on the right and a setTitle on the left. However, what happens by default is that everything is aligned to the left. Is there a way to change the position of the UIButton image and title views? I want everything to be in one button so that if someone clicks the title the icon will change its state as well. A: Make your image the same size as the button (i.e. pad it out with transparency) so things go where you want them to be. Say you have an image that 40 x 40, but you want it on the right side of a button 300 x 40. Just increase the size of the image with transparency to have 260 pixels of nothing on the left. For your text, you can use the alignment icons in Interface builder to put the title where you want it. A: What I did was subclass UIButton and set [self titleLabel] and [self imageView] in the layoutSubview method. #import "CustomDetailTableButton.h" @implementation CustomDetailTableButton - (void)layoutSubviews { [super layoutSubviews]; UILabel *titleLabel = [self titleLabel]; CGRect fr = [titleLabel frame]; fr.origin.x = 10.0; fr.origin.y = 5.0; [[self titleLabel] setFrame:fr]; UIImageView *imageView = [self imageView]; CGRect iFrame = [imageView frame]; iFrame.origin.x = 300.0; iFrame.origin.y = 7.0; [[self imageView] setFrame:iFrame]; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7520273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery slide up two elements - one following the other I'm trying to slide up two elements (images) one after the other at the same time - so there is no gap between the two. I thought about using jQuery.animate(), but I couldn't figure out how to move the bottom element at the same time as the animate method is executed. I'm assuming I'll have to use the position of the first element + its height for the moving position of the second one, but haven't got a clue how to actually make it slide at the same time as the first one. The container for all of them has relative position and elements are positioned inside absolutely. I just want to make a simple image / div gallery which scrolls up and don't want to use any plugins. Any idea? A: I have done a quick and dirty solution that shows how this can be done: http://jsfiddle.net/ah2zN/1/ Overflow hidden is used to prevent them from being rendered outside the slider.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git workflow tips I started using git and have been using it for couple of months now, and I am curious if my workflow is correct. I work from two different places on the project. here are the stages of my workflow: * *I pull the project from remote repo *make a local branch for a new feature *make changes and commit *merge the branch with master *push to the remote is this correct way of working on the project? A: First, let's just make something clear: there is no single "correct" workflow for Git. There are merely workflows that work - and specifically, workflows that work for you. The workflow you have outlined is typically referred to as a "feature branch" workflow (where you create a branch to work on a given feature/fix/whatever, and then merge it back), and is a perfectly legitimate workflow. If you only ever work on a single feature at a time, you could choose to simply commit directly to master, then push the updated version. This becomes difficult, however, if you're working on multiple different features simultaneously (whereas a feature branch workflow handles many simultaneous features gracefully). A: As Amber said : First, let's just make something clear: there is no single "correct" workflow for Git. There are merely workflows that work - and specifically, workflows that work for you. There is a good post on a blog about a good git workflow : A successful Git branching model You should read this post, it's really cool and you can adapt the workflow to your needs. In a nutshell, the workflow proposed by the blog post schematized like this : I have adopted this workflow for a while. I try to always respect the workflow, whether it's a teamwork or working alone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: generate WS-security usernameToken header in Visual studio 2010 I have a need to Implement Direct Authentication with UsernameToken WS-Security. I am consuming a Java Web-Service with Visual Studio 2010; which authenticates using UsernameToken header. I figured I can use WSE 3.0 -> http://msdn.microsoft.com/en-us/library/ff647197.aspx However, WSE 3.0 is not supported in Visual Studio 2010. I also found http://www.junasoftware.com/blog/how-to-use-wse-3-in-visual-studio-2010.aspx But I could not find the AddIn file in Windows 7 machine :-( So back to square 1; How do I generate WS-security usernameToken header in Visual studio 2010? A: I remember doing this a couple of months ago and it was a total headache. I think I did find the file in C:\Program Files\Microsoft WSE\v3.0\Tools but I might be wrong. If you are able to get it working, you can then create a class that inherits from SoapHeader something like this: public class SecuredWebServiceHeader : System.Web.Services.Protocols.SoapHeader { public string UserName { get; set; } public string Password { get; set; } public string AuthenticationToken { get; set; } public SecuredWebServiceHeader() { } } after this you declare an instance of SecuredWebServiceHeader variable on your WebServices and add the [System.Web.Services.Protocols.SoapHeader("SoapHeader")] attribute to all of your WebMethods. For the AuthenticationToken property of the SecuredWebServiceHeader class I just use/generate a Guid object and use it as the token. I have a AuthenticateUser method that checks whether the username provided is valid or not. If you don't find the Addin file let me know and I will try harder to find it. Good luck securing those WebServices. Hanlet
{ "language": "en", "url": "https://stackoverflow.com/questions/7520279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xcode highlight issues I have been working on a project with Xcode 3.2.6 for a few months (first time with Xcode). I really liked the following feature: when I searched for the occurrence of a term, say 'house', Xcode highlighted ALL the occurrences of 'house' in the file that I am looking at. Moreover, it used to tell me how many occurrences there were. If I decided to replace ALL the 'houses' for 'home' say, it will tell me how many replacements it did. A week ago I initialized Xcode and was doing something else at the same time, so some message (which I couldn't read) appeared and apparently I screw up this configuration. Now the find tool will highlight only the FIRST occurrence of a word, and the replace ALL feature doesn't tell me how many occurrences I am replacing. This might sound dumb but I really want this back, it is very useful for me. I tried everything that I could think of but I haven't been able to figure out how to revert it. I know I could just reset Xcode to the defaults but I don't want to do that because I have changed (not now, at the beginning) many other features. Any help will be really appreciated!!!!! thanks! A: Try to delete all derived data in the XCode folder and the restart! A: Delete Derived Data in Organizer under Projects option,then restart xCode
{ "language": "en", "url": "https://stackoverflow.com/questions/7520280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Native C++ library - who have to release the memory and how? This is about Android. The situation: C++ library and java wrapper classes plus native functions (JNI) for working with C++ classes from the library. When common java code needs C++ object, it creates corresponding java wrapper object which creates C++ object through native function and remembers the pointer to the native object in 'long' variable. In all next actions the wrapper gives this pointer to the native functions etc. The problem: How to release all allocated C++ objects at the end? Currently every wrapper class has 'finalize' method where it calls native function for releasing of the C++ object, but Android doesn't guarantee the calling of 'finalize'! At the other side, normally the C++ library has no idea how many and what types of C++ objects are allocated by java code. What will happens with the remaining allocated memory when our java application terminates, will Android release automatically the whole heap, used from the native library, when the OS unloads the library? A: At the end of the process lifetime, all process memory (both Java and C++ heap) will be freed and reclaimed by the system. One thing is though, Android activity closing does not necessarily end the process. I'm not sure what's the process shutdown policy there. On the other hand, relying on the garbage collection and finalize() sounds like solid design to me. You claim - "Android does not guarantee finalize()". Do you have a cite for that? 'Cause if it comes with a disclaimer of "when the object is freed as a part of process shutdown...", then we're still good. And if you're super-paranoid, you can write your own malloc()/free()/realloc() wrapper, store a list of all allocated objects, and introduce a cleanup function that walks the list and frees them all. The containing Java objects, however, might end in a weird zombie state where the memory has been freed from under them. This is a tricky proposition that is very easy to get wrong. So I'd still say - have faith in the garbage collector. Lack thereof would be... disturbing. A: Due to the difference in paradigms, you have to incorporate explicit destruction into your Java objects that are implemented under the hood using C++ resources. So a close() or other such method. The same issue comes up with the JNI, so answers to those questions will apply to you: Force Java to call my C++ destructor (JNI) As for the memory issue on closing, it's generally best in my opinion to not rely on this. If you get to a clean state, valgrind and such can make sure you weren't leaking. But from a technical standpoint--since Android is based on Linux, I'd imagine it does the usual thing and will free all the memory when the process closes. Taking advantage of that can make your program exit faster than explicitly freeing memory (for experts only who use other methods to ensure this maintains program correctness and they aren't leaking at runtime). A: We are using JNIs and we had a problem like that Actually, the problem resided in the fact that we were overloading finalize() to do the clean up. We solved our problems by removing our finalize() and creating a clean() instead. This clean() calls the JNI function that does the appropriate deletes (and set the C++ pointers to null, just in case). We call clean() just as you would in C++ with delete (e.g. when the variable goes out of scope). That worked for us. I hope it works for you. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7520283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ASP.net is not using other locale resource files i have a Default.aspx file where i fetch localized values: Default.aspx: <asp:Localize meta:resourcekey="lblTitle" runat="server">Welcome</asp:Localize> i then create a matching fallback resource file: Default.aspx.resx: lblTitle.Text Welcome to Stackoverflow Localized And that works: Now i want to create, for example, a French localization: Default.aspx.fr.resx: lblTitle.Text Bienvenue Stackoverflow And i change my browser to send a french language locale: (which it does): GET http://stackoverflow.com/ HTTP/1.1 Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */* Accept-Language: fr-CH,qps-ploc;q=0.5 User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E) Accept-Encoding: gzip, deflate Connection: Keep-Alive Host: stackoverflow.com Except that it just doesn't work: i'm following what Microsoft says: For example, if you have a page named Default.aspx in the App_LocalResources folder, you might create the following files: * *Default.aspx.resx. This is the default local resource file (the fallback resource file) if no language match is found. *Default.aspx.es.resx. This is the resource file for Spanish, without culture information. *Default.aspx.es-mx.resx. This is the resource file for Spanish (Mexico) specifically. *Default.aspx.fr.resx. This is the resource file for French, without culture information. Why is .NET doing not what .NET should be doing? Update: From MSDN: Selecting Resource Files for Different Languages ASP.NET can set the UICulture and Culture properties for the page to the language and culture values that are passed by the browser. ... For detailed information, see How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization. How can i get ASP.NET to set the UICulture and Culture properties for the page to the language and culture values that are passed by the browser? From How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization: Users can set the UI culture and culture in their browsers. For example, in Microsoft Internet Explorer, on the Tools menu, users can click Internet Options, on the General tab, click Language, and then set their language preference. If the enableClientBasedCulture attribute of the globalization element in the Web.config file is set to true, ASP.NET can set the UI culture and culture for a Web page automatically, based on the values that are sent by a browser. To set the culture and UI culture for an ASP.NET Web page declaratively * *To have ASP.NET set the UI culture and culture to the first language that is specified in the current browser settings, set UICulture and Culture to auto. Alternatively, you can set this value to auto:culture_info_name, where culture_info_name is a culture name. For a list of culture names, see CultureInfo. You can make this setting either in the @ Page directive or Web.config file. A: By default the browser language doesn't affect the application locale. You need to add some code to achieve this. One way is to add some code in Global.asax or a HttpModule, on BeginRequest. To read the language setting from the browser you can use something along the lines of: var languages = Request.UserLanguages if (languages != null) { var lang = languages[0]; Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang); } If you want to also affect the datetime, number formats etc, then also set CurrentCulture. Thread.CurrentThread.CurrentCulture = new CultureInfo(lang); A: Try setting UICulture="auto" and Culture="auto" in the @ Page directive in your .aspx file. How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization Or, you can accomplish the same thing in the web.config, except it would apply to every page: <system.web> <globalization uiCulture="auto" culture="auto" /> </system.web> A: I don't believe that the ASP.NET runtime by default sets the processing thread's UI culture. You have to explicitly assign it. You can do this with your own custom HttpModule, or even in your Global.asax.cs. Something along the lines of: string selectedCulture = browserPreferredCulture; Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedCulture); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedCulture); See http://msdn.microsoft.com/en-us/library/bz9tc508.aspx for an example as a starting point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: should phrases in a multilanguage site be stored in the database or in files? I'm developing a website, and want to make multi language support, but I'm doubting where I should store the phrases. Storing them in a database makes it easier to create systems where you crowdsource the translation, in a similar facion facebook and twitter are doing. The disadvantage is that querying a database for phrases can be slow, especially when there are a lot of phrases on a page. Storing them in a file makes retrieval faster, but makes them harder to manage and maintain. What are some other pros and cons? A: If the phrases need to change often, then store them in a database. If the phrases change infrequently or never, and you are using java, store them in a resource bundle. If you are worried about load time from a db, you can cache the phrases and periodically update the cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are the differences when deploying on Tomcat vs. Websphere? If I were to deploy an application on Tomcat vs. Websphere, what are things that I need to consider? Do I have to develop my Java code differently if developing in one app server vs another? Edit: I will be funneling people from a website into a web app that does credit card processing and e-signatures (cc processing and e-sigs are through separate services). That is its sole job A: You can think as Tomcat as a subset of Websphere, so theoretically everything that works on Tomcat will work in Websphere. But...Deploying in Websphere, in my humble opinion, is a terrible pain, while deploying in Tomcat just works. (And if fails, just delete temporary folders) Without knowing the technologies you are using, that's all I can say. A: You cannot use EJBs on Tomcat (unless you add OpenEJB). If your WebSphere deployment uses EJBs, you'll have to remove them to deploy on Tomcat. If you use any Java EE features beyond servlet/JSP engine and JNDI naming service you'll have to eliminate them from your app. Tomcat accepts WAR packages. If you package your app into an EAR on WebSphere, you'll have to change it to WAR for Tomcat. Both use JNDI for data sources. There might be some nagging differences in naming conventions, but if you stick to the standard they should be portable. If you use any WebSphere specific code in your app, you'll have to remove it to deploy on Tomcat. If your app is servlets, JSPs, and JDBC you can deploy on either one without any problems. A: Depends, what are you trying to deploy? Tomcat isn't a full EE server--are you trying to deploy an EE app? If you're just deploying a web app, it's more important to consider which version of the servlet spec/etc. each server implements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Regex to parse @user mentions I have been using following Regex to parse @username from posts in my application. '/(^|\s)#(\w*[a-zA-Z_]+\w*)/ Can somebody explain me the purpose of (^|\s). What if I omit that part? A: (^|\s) either matches the beginning of a string (^) or a space character (\s). This is in order to prevent hallo#world from matching as a mention. An alternative to that is using \b (a word boundary). It has slightly different semantics, but it should work in this case. A: (^|\s) is either the start of the line or string (^) or (|) a white space character (\s)
{ "language": "en", "url": "https://stackoverflow.com/questions/7520297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating dojox.grid.DataGrid I have a dojox.grid.DataGrid configured and I want to populate a data grid with different values when a user clicks a button. I have tried the following code but it does not work: var employees2 = [ {name:"Jane", department:"engineering"}, {name:"Mary", department:"engineering"}, {name:"Julie", department:"sales"} ]; console.info("grid is "+grid.toString()); employeeStore2 = new dojo.store.Memory({data:employees2, idProperty: "name"}); grid.setStore(employeeStore2); employeeStore2.close(); I have setup the example here: http://jsfiddle.net/nonie/kx72T/ Any help would be great. A: In your example, the event onclick button doesn't work.... I think in showList2 method, you should write something like this **employeeStore2 = new dojo.store.Memory({ data: employees2, idProperty: "name" }); grid.setStore(dojo.data.ObjectStore({objectStore: employeeStore2})); grid.update();**
{ "language": "en", "url": "https://stackoverflow.com/questions/7520299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook app without prompted authentication I've been trying to figure out a way to have my iframe Facebook app (built in PHP) work without requiring separate authentication methods. I am already logged into Facebook, but for some reason I still see all these Oauth notices from the example in the PHP SDK. The only data I need is publicly available even without them "adding" my app. I am looking to collect their Facebook ID (since this is a contest, we need a unique ID for tracking), their name and (optionally) their email address as well. The problem is, I cannot use the API to fetch the public information unless I already know their Facebook username. Any ideas on how I might be able to get their logged-in username or public handle so I can then fetch the rest of the information? For whatever reason, Oauth is driving me completely insane with Facebook today. Sidenote: I did manage to technically get the Javascript SDK operational, which fed some information to PHP for use. The only issue there is that once I login, I don't see the data. If I refresh...then it shows up. Unsure why the refresh is required, as I wouldn't expect a user to actually have to hit refresh in order to proceed with the app. A: I guess you are a bit confused here, Facebook will NOT share the username, id, full name or email without the user explicitly authorizing/allowing your application (and in the case of the email, requesting the email permission!). Read the official Canvas Tutorial for more information: In order to gain access to all the user information available to your app by default (like the user's Facebook ID), the user must authorize your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read a xml element and write back the new value of element to xml in C# I am trying to read abc.xml which has this element <RunTimeStamp> 9/22/2011 2:58:34 PM </RunTimeStamp> I am trying to read the value of the element which the xml file has and store it in a string and once i am done with the processing. I get the current timestamp and write the new timestamp back to the xml file. Here's my code so far, please help and guide, your help will be appreciated. using System; using System.Collections.Generic; using System.Linq; using System.Text; using log4net; using System.Xml; namespace TestApp { class TestApp { static void Main(string[] args) { Console.WriteLine("\n--- Starting the App --"); XmlTextReader reader = new XmlTextReader("abc.xml"); String DateVar = null; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. Console.Write("<" + reader.Name); Console.WriteLine(">"); if(reader.Name.Equals("RunTimeStamp")) { DateVar = reader.Value; } break; case XmlNodeType.Text: //Display the text in each element. Console.WriteLine(reader.Value); break; /* case XmlNodeType.EndElement: //Display the end of the element. Console.Write("</" + reader.Name); Console.WriteLine(">"); break; */ } } Console.ReadLine(); // after done with the processing. XmlTextWriter writer = new XmlTextWriter("abc.xml", null); } } } A: I personally wouldn't use XmlReader etc here. I'd just load the whole file, preferrably with LINQ to XML: XDocument doc = XDocument.Load("abc.xml"); XElement timestampElement = doc.Descendants("RunTimeStamp").First(); string value = (string) timestampElement; // Then later... timestampElement.Value = newValue; doc.Save("abc.xml"); Much simpler! Note that if the value is an XML-format date/time, you can cast to DateTime instead: DateTime value = (DateTime) timestampElement; then later: timestampElement.Value = DateTime.UtcNow; // Or whatever However, that will only handle valid XML date/time formats - otherwise you'll need to use DateTime.TryParseExact etc. A: linq to xml is the best way to do it. Much simpler and easier as shown by @Jon
{ "language": "en", "url": "https://stackoverflow.com/questions/7520304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamically Add columns to datagrid in Flex I am trying to make a datagrid, that will dynamically add columns to it based on some condition. Now, I am able to add the columns, but I want the newly added column to have button using itemRenderer. I am unable to achieve this though. Getting this error on line 1 Description Resource Path Location Type 1067: Implicit coercion of a value of type mx.controls:Button to an unrelated type mx.core:IFactory. Demo.mxml /Demo/src line 14 Flex Problem Can anyone help ? Here's a code snippet : private function addDataGridColumn(dataField:String):void { var dgc:DataGridColumn = new DataGridColumn(); dgc.itemRenderer = button1; // Line 1 var cols:Array = dataGrid.columns; cols.push(dgc); dataGrid.columns = cols; } A: The itemRenderer and itemEditor properties are of type IFactory. When you set these properties in MXML, the MXML compiler automatically casts the property value to the type ClassFactory, a class that implements the IFactory interface. When you set these properties in ActionScript, you must explicitly cast the property value to ClassFactory You might be looking for this, adds buttons to all rows of newly added column. private function addDataGridColumn(dataField:String):void { var dgc:DataGridColumn = new DataGridColumn(); dgc.itemRenderer = new ClassFactory(Button); var cols:Array = dataGrid.columns; cols.push(dgc); dataGrid.columns = cols; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7520306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java call method of descendant class in abstract superclass I have a big method doComplicateCalculation in abstract class - AbstractClass. Also have small class Descendant that extends AbstractClass. I need to introduce in method doComplicateCalculation small changes like: .............. if (val<0){ continue; } .................. The problem also more difficulta that big method in internal class of abstract class. How it can be done? Thanks. A: This might not be the best answer; but it is the best answer I can give with the information provided. If anything it will get you thinking in the about ways you can address this (because if you're going to be programming for a while, then it won't be the last time you run into problems like this). In your abstract class, put this: if (doContinue(val)){ continue; } Then, define the method in your abstract class... protected boolean doContinue(int val) { // Or, put return true if you always want it to do this return false; } Then, override this method in your concrete class, like this... protected boolean doContinue(int val) { return val < 0; } A: You need to break the big method in pieces, so that you can override the part you need. A: That is a difficult question to try to answer generically. One thing that you could do is to try to break up the algorithm in doComplicateCalculation as much as possible. To add the validation maybe make each class extending doComplicateCalculation implement a public boolean validate You could even do this before or at different times throughout the algorithm. If that isn't possible you could also just override this method (or override some part of the method if you could break it up).
{ "language": "en", "url": "https://stackoverflow.com/questions/7520313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't refactor files in eclipse I'm working on an Android project in eclipse, and whenever I try to move or rename a source file, eclipse says it caught an exception while trying to refactor, that the file doesn't exist, and lets me either undo, or abort. I suspect it has something to do with mercurial because it's happened before, but besides that, I have no idea what is wrong. Anyone know how to fix this? I've already tried refreshing the entire project, cleaning the project, and closing and reopening the project, but I still can't even move a source file from one project to another. UPDATE: I've resorted to using the command prompt to manually move and rename my files. It wasn't that hard, but Eclipse is still not doing what it's supposed to do. I want to know how to fix this. A: Right click on your project and click refresh. This is usually due to files being out of sync with the file system. A: Its possibly related to this: https://bugs.eclipse.org/bugs/show_bug.cgi?id=339866 I found updating both eclipse and hg fixed the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Small but nice differences between VS 2010 Professional and Web Developer Express 2010? I have found similar posts to this one, such as; * *Visual Studio Vs Visual Web Developer, *What are the limitations of Visual Web Developer Express 2010? *What are the differences between visual studio and VS express edition? But I have a encountered a selection of minor differences such as in VWD it's not possible to make conditional breakpoints and you can not hit Ctrl+comma to launch the very time-saving Navigate to-dialog. What more diffences like these are there? It seems impossible to find a comprehensive list of these... Please note that it is the 2010 editions I'm interested in to compare.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problems with incomplete content in forwards from Outlook 2003 I've designed an HTML email (with no css, using tables, etc) that essentially consists of one outer table that contains 3 inner tables. The email renders fine in Outlook 2003 but when the user forwards it, only the top table is preserved in the forward. I've tested this in: * *Outlook 2003 (11.8330.8341) SP3 *Outlook 2003 (11.5608.5606) Any idea what could be going on here? I don't really even know where to start. When I look at the HTML content of the forward, it is mangled beyond belief. UPDATE: There's a setting in MS Outlook 2003 under Tools > Options > Mail Format that says "Use microsoft office word 2003 to edit email messages". When the user does not have Outlook installed (and so the option is unchecked and grayed out) or when this is simply not checked, the forward appears correctly. However, checking this option brings up the composer in an instance of Word. Word completely screws up the HTML - creating actual data loss, not just formatting problems. UPDATE 2: Found this question. Although the answer didn't help me, anyone on this question might want to check it out: HTML E-mail Layouts Breaking When Forwarded - Make it Survive the Word 2003 HTML Editor QUESTION: What is happening here? Is there any information about certain HTML that Word will strip? I'm using only the most basic elements and styles I can find. What is happening here? A: Word stripped everything inside divs. I didn't do robust enough testing to determine whether or not this would be true of any div. I converted them to tables and everything now works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to use JavaScript's variable in PHP? Possible Duplicate: Access a JavaScript variable from PHP theVariable = String.fromCharCode(theVariable).toLowerCase(); is it possible to use theVariable in PHP codes ? How? A: Not really... you can send it to a PHP script using AJAX or an HTML form. I strongly recommend you get a clearer understanding of what JavaScript is vs. PHP, particularly what it means that JavaScript runs on the client-side (i.e. in the browser), and PHP runs server-side. A: Only if the the variable is sent via ajax to a PHP page. You see PHP is executed first, then the page is served to the client. Then the client executes the javascript. So the javascript is executed long after the PHP has been executed. A: The only way to pass a variable from JavaScript to PHP is to pass it by an AJAX call. A: To use a variable that is in JavaScript in PHP, you have to send an Ajax request to a PHP page passing that variable in. This probably isn't the effect you're looking for. JavaScript executes on the viewer's computer. PHP executes on the server. To send a JavaScript variable to PHP, you need to send some packet of information from the client to the server. This is done as a GET/POST request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Android/Java text file read problem I'm currently trying to read a file from (res/raw) by using an InputStream that I dimension like such: InputStream mStream = this.getResources().openRawResource(R.raw.my_text_file_utf_8); I then put that into this method to return the values: public List<String> getWords(InputStream aFile) { List<String> contents = new ArrayList<String>(); try { BufferedReader input = new BufferedReader(new InputStreamReader(aFile)); try { String line = new String();//not declared within while loop while ((line = input.readLine()) != null ){ contents.add(line); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents; } My problem: It reads all the values as it should, but say if the file is 104 lines long, it will actually return a value of something like 134 total lines with the remaining 30 lines being full of null?? Have checked: Already using UTF-8 format, and double checked that there are literally no blank lines within the document itself... I thought the way the while loop was written that it couldn't record a line=null value to contents List? Am I missing something here? Thanks for any constructive information! I'm pretty sure I'm overlooking some simple factoid here though... A: Why dont you create HTML for your information and then parse it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I loosely couple a process to a user interface for VBA and/or .Net? This question came to mind when I asked to put a progress bar on a long running process where the process has no concept of a user interface. In fact, the process is being written into a library to be pulled in from other applications. However, how do I provide a way for a WinForm to subscribe to the process to update as the process gets executed? I've open this question from both VBA/VB6 and .Net because its part of the gamut for UI development. It's also worth mentioning that these are subroutines and not classes that are running the methods, so event raising appears to be out of the question. Should I expose incrementing variables as public? Thanks in advance. Adam: Should we be eating of forbidden fruit? Eve: Yes. I think so. Go ahead Adam. Serpant: Stop with the chit-chat and expose those variables already.... God: Noooooooooooo!!! A: There's now need to expose your variables. How about writing a ProcessCompletionStatus subroutine which looks at those incrementing variables and tells how much has been done?
{ "language": "en", "url": "https://stackoverflow.com/questions/7520333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WebView next/previous page transitions I'm generating a book app, of sorts, that displays pages in a WebView. I have Next/Previous ImageButtons and a GestureOverlay to detect left/right swipes. When I want a page change I call: private void changePage(int delta) { currentPageIndex = currentPageIndex + delta; if (currentPageIndex < 0) { // negative index currentPageIndex = 0; } else if (currentPageIndex >= listOfPages.length) { // index requested is out of range of the list currentPageIndex = listOfPages.length - 1; } else { // set values for page load filename = listOfPages[currentPageIndex]; mWebView.loadUrl("file:///android_asset/" + filename); } } 'listOfPages' is a string array of my filenames and loadUrl() works great, but is there any way that anyone knows of to be able to have a page transition to simulate a simple page turn? A: If anyone's interested, I found a way to do this. I defined Animation variables: Animation slideLeftAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.slide_left); Animation slideRightAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.slide_right); And the slide_left and slide_right xml files are from the Android API tutorials. Then, for left or right swipes, I used mWebView.startAnimation(leftOrRightAnimation); before my mWebView.loadUrl(url); call. Hope this helps anyone else! Chris
{ "language": "en", "url": "https://stackoverflow.com/questions/7520337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Conditional formatting of a column based off having any text in the first column of the same row I'm not sure if this is even possible without going to VB, but I was trying to do it through conditional formatting. Basically I have a column (Column K) that will always be the same value (345) if there is a record entered in that row. Basically when I populate my reports I simply want the value (345) to be entered into Column K if there is any data in that row. I was trying to just use Column A as a reference. I was messing with =IF(ISTEXT(Col.A location),"345","") but that's getting nowhere. So, I'm looking for ideas outside of vba, but if there are no possibilities then vba is the way to go I suppose. :) A: Assuming your data is in columns A to J, and that it starts in row 2, enter this in K2 and copy down as necessary: =IF(COUNTA(A2:J2),345,"") Edit: For a conditional formatting formula you don't need the "If" part, because the formatting is already ... conditional: =COUNTA(A2:J2) A: Will this work? =IF(ISBLANK(A1),"","345") A: This code works to tell whether column A has something in it or not COUNTA(INDIRECT("$A$"&ROW()))>0, but I don't think you can set the value of the cell using conditional formatting. But with conditional formatting you have to know ahead of time how far down your data is going to go unless you just put it in all the rows. Why don't you just put it in your VBA code when you are copying, you can find out what the last row is then put the IF() formula in. You can use this code: Dim r1 As Range Set r1 = Range("K1") r1.NumberFormat = "General" r1 = "=IF(COUNTA(INDIRECT(""$A$""&ROW())>0,""345"","""")" r1.AutoFill Destination:=Range(r1, r1.Offset(200))
{ "language": "en", "url": "https://stackoverflow.com/questions/7520343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Positioning QPushButtons via qss in QT I have a set of five buttons that I am trying to position in a qss file. The default position that I have set up in the ui file works for one of the layouts I need. However, I want to group the buttons differently in the other theme. I am new to qss files and have been experimenting, but cannot figure out if some things are possible. The "left" property is defined here: http://doc.qt.io/archives/4.6/stylesheet.html#left-attr but nothing happens when I try to use it. margin-left actually moves the button, but only relationally. So, if the buttons are positioned in the ui file with a gap of 100 between them, a margin-left for the second button in the list is offset by 100. What am I doing wrong? Could it be some setting in the ui file that is preventing it from moving? I already "broke layout" and it doesn't seem to matter. Is there a good resource you'd suggest? Here is a sample of my qss file. The left has no effect. QPushButton#Button_1 { min-width: 50; max-width: 50; min-height: 50; max-height: 50; position:absolute; subcontrol-origin: border; left:200; } EDIT: I've figured out that I can change the position of the button by deriving a class from QPushButton and making a "GeomX" qproperty. This seems to work, but I am running into an odd issue now. When I first load my app, it draws the buttons as they are positioned on the ui file. When I use the "change theme" option that I've coded, and select the currently loaded theme, it moves the buttons as I'd expect. However, resizing the app dumps them back to the ui positions and restarting also places them back in their ui positions. Is there a setting in the ui file that I could alter to get it to stop moving them? Is there a load-order issue that I need to address? Is it possible to even address this? What is going on? A: Generally speaking, style sheets in Qt are used to alter the way a widget is drawn, not where it is positioned (except to add padding/margin). As the documentation you've referenced mentions, the "left" property is specific to sub-controls (that is, components within a widget and not the widget itself). What it sounds like you're trying to accomplish (change the layout depending on the theme) would likely require a different approach. A couple of options would be to react to when the theme changes by: * *Moving around your spacers in your layout to move the buttons to the desired position *Using a stacked widget, one page in the stack for each layout you desire, and change which page in the stack you're showing depending on what theme you're using.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: drupal 7 hook_form_form_id_alter I'm trying to hook into a form with ID equal to "block-admin-configure," mymodule_form_block_admin_configure_alter(&$form, $form_state, $form_id) is not being triggered. When I use mymodule_block_view_block_admin_configure_alter(&$data, $block), it works perfectly. My goal is to add some additional configuration options to a regular drupal block. A: hook_block_configure() etc are only called in modules for blocks that that pareticular module defines in hook_block_info(), so if you're trying to hook into a block defined by another module you'll definitely have to user a form_alter function. Just a note, hook implementations are cached in Drupal 7 so any time you declare a new hook you have to clear the caches before it'll get called.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Weird error: The URI you submitted has disallowed characters with permited uri chars set to blank? Well i know its dangerous to set the permited_uri_chars to blank but i did this in order to find the error which so far i havent figured out the thing is that im getting this error The URI you submitted has disallowed characters on this URL localhost/A&OS/products, it works well with /localhost/A&OS/ and it does display the default controller called "home" but as soon as i pass a controller name to the url it keeps showing the error no matter what the controller is! this is my config.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | If this is not set then CodeIgniter will guess the protocol, domain and | path to your installation. | */ $config['base_url'] = ''; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'AUTO' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'AUTO' Default - auto detects | 'PATH_INFO' Uses the PATH_INFO | 'QUERY_STRING' Uses the QUERY_STRING | 'REQUEST_URI' Uses the REQUEST_URI | 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO | */ $config['uri_protocol'] = 'AUTO'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify with a regular expression which characters are permitted | within your URLs. When someone tries to submit a URL with disallowed | characters they will get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; // experimental not currently in use /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | If you have enabled error logging, you can set an error threshold to | determine what gets logged. Threshold options are: | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ folder. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | system/cache/ folder. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class or the Session class you | MUST set an encryption key. See the user guide for info. | */ $config['encryption_key'] = ''; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_cookie_name' = the name you want for the cookie | 'sess_expiration' = the number of SECONDS you want the session to last. | by default sessions last 7200 seconds (two hours). Set to zero for no expiration. | 'sess_expire_on_close' = Whether to cause the session to expire automatically | when the browser window is closed | 'sess_encrypt_cookie' = Whether to encrypt the cookie | 'sess_use_database' = Whether to save the session data to a database | 'sess_table_name' = The name of the session database table | 'sess_match_ip' = Whether to match the user's IP address when reading the session data | 'sess_match_useragent' = Whether to match the User Agent when reading the session data | 'sess_time_to_update' = how many seconds between CI refreshing Session Information | */ $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_expire_on_close'] = FALSE; $config['sess_encrypt_cookie'] = FALSE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 300; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists. | */ $config['cookie_prefix'] = ""; $config['cookie_domain'] = ""; $config['cookie_path'] = "/"; $config['cookie_secure'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or 'gmt'. This pref tells the system whether to use | your server's local time as the master 'now' reference, or convert it to | GMT. See the 'date helper' page of the user guide for information | regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy IP | addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR | header in order to properly identify the visitor's IP address. | Comma-delimited, e.g. '10.0.1.200,10.0.1.201' | */ $config['proxy_ips'] = ''; /* End of file config.php */ /* Location: ./application/config/config.php */ it is the only CI proyect on localhost that its causing this error , at the beggining i tought it was because this char '&' but i have this other proyect called alpha&omeha and it works like a charm so i dont know what could be causing the error! A: You should really be URL encoding your parameters before you render links or redirect to a URI. Look here: http://php.net/manual/en/function.urlencode.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7520353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cocos2D ccTouchesMoved Sprites and Objects I have been struggling with this for a bit. I am trying to avoid have multiple classes for the objects I am trying to create. Basically I have a 'Letter' class that has a letter property. When I initialize the object I set the letter type to A, B, C...I am doing this all in a loop. Everything seems fine. The issue is when I am firing the ccTouchesMoved event I would like to know if I am moving the Letter object of type A or B etc..I cannot figure this one out. Here are some snippets to show what I am doing: Letter Class @implementation Letter - (id)init { if ((self = [super init])) { gamePieceType = kLetterNotAssigned; } return self; } My Layer Init for (int x=0; x < NUMBER_OF_ITEMS; x++) { int randomX = random() % 1024; [self createPuzzlePieceAtLocation:ccp(randomX, 600) withPiece:x]; } The createPuzzlePieceAtLocation method - (void)createPuzzlePieceAtLocation:(CGPoint)location withPiece:(int)tagValue { switch (tagValue) { case 1: letterSprite = [[Letter alloc] initWithSpriteFrameName:@"upper_a.png"]; letterSprite.gamePieceType = kLetterA; break; ... } [self createBodyAtLocation:location forSprite:letterSprite isBox:FALSE]; [sceneSpriteBatchNode addChild:letterSprite]; Any thoughts? I get the touchLocation in ccTouchesMoved but how can I get the object? A: You have to determine what letter has been touched. The simplest way is to iterate over all your letters (put them in array when creating) and checking for the letters that accepts touch. The fastest way is to use physics engine for fast searching (Box2D and chipmunk engines are coming with cocos2d). When letter is determined simply check it's type
{ "language": "en", "url": "https://stackoverflow.com/questions/7520354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing to see if an env variable is set in bash In a bash script, I'm trying to test for the existence of a variable. But no matter what I do, my "if" test returns true. Here's the code: ignored-deps-are-not-set () { if [ -z "${ignored_deps+x}" ] then return 0 fi return 1 } ignored_deps=1 ignored-deps-are-not-set echo "ignored-deps function returns: $?" if [ ignored-deps-are-not-set ] then echo "variable is unset" else echo "variable exists" fi Here is the output as written: ignored-deps function returns: 1 variable is unset And the output when I comment out the line where ignored_deps is set. ignored-deps function returns: 0 variable is unset No matter what, it says the variable is unset. What am I missing? A: This line: if [ ignored-deps-are-not-set ] tests whether the string 'ignored-deps-are-not-set' is empty or not. It returns true because the string is not empty. It does not execute a command (and hence the function). If you want to test whether a variable is set, use one of the ${variable:xxxx} notations. if [ ${ignored_deps+x} ] then echo "ignored_deps is set ($ignored_deps)" else echo "ignored_deps is not set" fi The ${ignored_deps+x} notation evaluates to x if $ignored_deps is set, even if it is set to an empty string. If you only want it set to a non-empty value, then use a colon too: if [ ${ignored_deps:+x} ] then echo "ignored_deps is set ($ignored_deps)" else echo "ignored_deps is not set or is empty" fi If you want to execute the function (assuming the dashes work in the function name), then: if ignored-deps-are-not-set then echo "Function returned a zero (success) status" else echo "Function returned a non-zero (failure) status" fi A: You're not actually executing the function: if ignored-deps-are-not-set; then ... Withing [] brackets, the literal string "ignored-deps-are-not-set" is seen as true. A: if [ ${myvar:-notset} -eq "notset" ] then ... A: --edit-- just realized that it's a function tha tyou're trying to call, convention is wrong. See: Z000DGQD@CND131D5W6 ~ $ function a-b-c() { > return 1 > } Z000DGQD@CND131D5W6 ~ $ a-b-c Z000DGQD@CND131D5W6 ~ $ echo $? 1 Z000DGQD@CND131D5W6 ~ $ if a-b-c; then echo hi; else echo ho; fi ho Z000DGQD@CND131D5W6 ~ $ if [ a-b-c ]; then echo hi; else echo ho; fi hi Z000DGQD@CND131D5W6 ~ --edit end-- Fix the variable name (see my comment to your post) then See Parameter Expansion section in man bash. ${parameter:?word}: Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted. A: Yet another way to test for the existence of a variable: if compgen -A variable test_existence_of_var; then echo yes else echo no fi
{ "language": "en", "url": "https://stackoverflow.com/questions/7520356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: force base class to use its own method and not overrided method here is my scenario: class SomeBaseClass { public void foo(String str) { ....... } public void foo(String strs[]) { ....... } } class MyClass extends SomeBaseClass { public void foo(String str) { super.foo(str); } public void foo(String strs[]) { throw new RuntimeException("only one input please!"); } } The logic is pretty simple. "SomeBaseClass" is 3rd party tool that i cannot modify. I want to limit its functionality and don't want to allow foo(String strs[]). the problem is that inside SomeBaseClass foo(Sting str) internally calls foo(String strs[]). Hence when i call foo(String str) of MyClass, I get a runtime exception. How can I tell the SomeBaseClassclass to use SomeBaseClass::foo(String strs[]) and all other classes to use MyClass ::foo(String strs[]) A: Consider writing a wrapper class MyClass extends SomeBaseClass { private SomeBaseClass impl = new SomeBaseClass (); public void foo(String str) { impl.foo(str); } public void foo(String strs[]) { throw new RuntimeException("only one input please!"); } } A: Perhaps over engg but inside MyClass.foo(String strs[]) you can check if the caller is SomeBaseClass.foo(String str), if yes, let the call go thru to super.foo(String) else throw RuntimeException. To find the caller check StackTrace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jquery fade and slide simultaneously I'm trying to both slide/fade a div simultaneously on a hover, then slide/fade it out at the end of the hover, using JQuery. The slide/fade out work properly, but the slide/fade in doesn't. It just slides in without the fade. Any ideas? #myDiv { display: none; height: 110px; position: absolute; bottom: 0px; left: 0px; } $('#anotherDiv').hover(function() { $('#myDiv').stop(true, true).slideDown(slideDuration).fadeIn({ duration: slideDuration, queue: false }); }, function() { $('#myDiv').stop(true, true).slideUp(slideDuration).fadeOut({ duration: slideDuration, queue: false }); }); A: Why not use jQuery to slide, and CSS transitions to fade, so they do not interfere with each other. Degrades nicely! JS: $('#myDiv').addClass("fadingOut"); $('#myDiv').slideUp(600,function(){ $('#myDiv').removeClass("fadingOut"); }); CSS: .fadingOut { transition:opacity 0.6s linear; opacity:0; } A: idk if this helps or not, but you can skip the slideUp and fadeIn shortcuts and just use animate: http://jsfiddle.net/bZXjv/ $('#anotherDiv').hover(function() { $('#myDiv') .stop(true, true) .animate({ height:"toggle", opacity:"toggle" },slideDuration); }); A: The answer is that once either effects activate, it takes the inline css property "display=none" off of the element. These hide effects require the display property to be set to "none". So, just rearrange the order of methods and add a css-modifier in the chain between fade and slide. $('#anotherDiv').hover(function() { $('#myDiv').stop(true, true).fadeIn({ duration: slideDuration, queue: false }).css('display', 'none').slideDown(slideDuration); }, function() { $('#myDiv').stop(true, true).fadeOut({ duration: slideDuration, queue: false }).slideUp(slideDuration); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7520366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: About index in sql server Is it a simple question. I have a table Named Car for stock car specifications. On of my field is year for stock year of each car. So is it a good idea to indexing - (non- clustered) this fields if its can have 25 cars registered at 2009? Thank's for yours helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7520370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error message when modal is empty I have a couple of modal popups on my page that hold checkboxes. The checkboxes are different items that can be added to a specific product. Some products, however, have all of one type of item assigned to them. I need a way to show a message in the modal when the modal is empty. I have tried using a Label inside the modal that says "All features are currently associated with this product." But the label leaves a space in the modal when it's visibility is set to hidden and that was annoying so I ditched that idea. What is a good way to have a hidden message that shows up when the modal is empty? <asp:LinkButton ID="FeatureButton" runat="server">Feature</asp:LinkButton> <asp:Panel ID="FeaturePanel" runat="server" CssClass="modalPopup" Style="display:none"> <div class="PopupHeader">Add a Feature</div> <asp:CheckBoxList ID="cbxAddFeature" runat="server" DataSourceID="dsNewFeatures" DataTextField="FeatureTitle" DataValueField="FeatureID"></asp:CheckBoxList> **<asp:Label ID="FeatureError" runat="server" Text="All features are currently associated to this product." Display="none"></asp:Label>** <asp:Button ID="SubmitFeatures" runat="server" Text="Submit" /> <asp:Button ID="CancelSubmitFeatures" runat="server" Text="Cancel" /> </asp:Panel> <asp:ModalPopupExtender ID="FeatureModal" runat="server" BackgroundCssClass="modalBackground" CancelControlID="CancelSubmitFeatures" DropShadow="True" DynamicServicePath="" Enabled="True" PopupControlID="FeaturePanel" TargetControlID="FeatureButton"> </asp:ModalPopupExtender> Protected Sub SubmitFeatures_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitFeatures.Click FeatureModal.Hide() For Each feature As ListItem In cbxAddFeature.Items **FeatureError.Visible = False** If feature.Selected Then 'SQL INSERT: Marketing Table Dim strSQL As String = "INSERT INTO Marketing (ProductID, MarketingTypeID, MarketingTitle, MarketingData) VALUES (@ProductID, 3, 'Feature', @MarketingData)" Using cn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString) Using cmd As New SqlCommand(strSQL, cn) cmd.Parameters.Add(New SqlParameter("@ProductID", ProductID.Value)) cmd.Parameters.Add(New SqlParameter("@MarketingData", feature.Value)) cn.Open() cmd.ExecuteNonQuery() End Using End Using End If **If (dsNewFeatures) == DBNull.Value Then FeatureError.Visible = True End If** Next Response.Redirect(Request.RawUrl) End Sub <asp:SqlDataSource ID="dsNewFeatures" runat="server" ConnectionString="<%$ ConnectionStrings:ProductsConnectionString %>" ProviderName="<%$ ConnectionStrings:ProductsConnectionString.ProviderName %>" SelectCommand="SELECT DISTINCT f.FeatureID, f.FeatureTitle FROM Feature f LEFT JOIN Category c ON c.CategoryID = f.CategoryID WHERE f.CategoryID IN (SELECT CategoryID FROM CategoryLink WHERE ProductID = @ProductID) AND f.FeatureID NOT IN (SELECT m.MarketingData FROM Marketing m WHERE m.MarketingTypeID = 3 AND m.ProductID = @ProductID) ORDER BY f.FeatureTitle"> <SelectParameters> <asp:QueryStringParameter Name="ProductID" QueryStringField="id" /> </SelectParameters> <SelectParameters> <asp:QueryStringParameter Name="CategoryID" QueryStringField="id" /> </SelectParameters> </asp:SqlDataSource> All **** items are pieces of the label, the If, End If statement doesn't work, does anyone know how I can change that to get it to find an empty modal for the error message? This is what it looks like now, notice the label showing. I don't know why it won't go away! EDIT 9/29/11 Protected Sub dsNewFeatures_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsNewFeatures.Selected If FeatureError.Text = String.Format("rows count: {0}", e.AffectedRows) Then FeatureError.Visible = True Else FeatureError.Visible = False End If End Sub It almost works! The label is not visible just based off of this code, but I can't get it to unhide when I empty the modal A: When you say it's visibility is set to hidden you refer to the CSS visibility property? If so, try using display:none instead and that should fix the spacing issue that you dislike. If that doesn't do it (I think it will), simply set the Visible property of the label to false in code behind when you trigger the event that pops up the dialog. I believe ASP.NET doesn't render elements when the Visible property is false so this definitely should work. What I mean is this: annoyingLabel.Visisble=False You can toggle the Visible property accordingly depending on whether you need to display the message or not. Hope this helps. UPDATE: How about this? Dim showNextTime As Boolean = False If feature.Selected Then '' your code here Else showNextTime =True End If FeatureError.Visible = showNextTime Since you are iterating through all items and checking whether they are selected or not all you need to do is set a flag that will become true the moment one of the items is not selected (meaning, there will be at least one item left to be added). If there are no items to go through, then by default FeatureError.Visible should be false. Does that work for you? UPDATE 2 Dim showNextTime As Boolean = False If feature.Selected Then '' your code here Else showNextTime =True End If ' Add this condition to make it visible if Items.Count==0 FeatureError.Visible = (showNextTime Or cbxAddFeature.Items.Count==0) UPDATE 3 Now try this: Add an OnCLick event to your FeatureButton as so: <asp:LinkButton OnClick="FeatureButton_Click" ID="FeatureButton" runat="server">Feature</asp:LinkButton> And on your code Behind: Sub FeatureButton_Click(sender As Object, e As EventArgs) FeatureError.Visible = (cbxAddFeature.Items.Count=0) End Sub We will make this work. UPDATE 4: Change your OnSelected code to this (I don't know why were you comparing text): Protected Sub dsNewFeatures_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsNewFeatures.Selected If e.AffectedRows=0 Then FeatureError.Visible = True FeatureError.Text= "All features are currently associated to this product." Else FeatureError.Text= "" FeatureError.Visible = False End If End Sub A: You're getting white space because of how asp.net controls visibility behind the scenes. When the control is rendered to the browser it's css style is set to visibility: hidden which will leave white space in the document where the element should be. If you want to remove the white space then you must use the css style display: none. So, in your code: Change <asp:Label ID="FeatureError" runat="server" Text="All features are currently associated to this product." Display="none"></asp:Label> To <asp:Label ID="FeatureError" runat="server" Text="All features are currently associated to this product."></asp:Label> Change For Each feature As ListItem In cbxAddFeature.Items **FeatureError.Visible = False** .... To For Each feature As ListItem In cbxAddFeature.Items FeatureError.Attributes.Add("Style", "Display: None;") ... Change **If (dsNewFeatures) == DBNull.Value Then FeatureError.Visible = True End If** To Dim dv as DataView dv = CType(dsNewFeatures.Select(DataSourceSelectArguments.Empty), DataView) If(dv.Count == 0) FeatureError.Attributes("Style") = "Display: Inline;" End If You could also refactor the styles to be in a stylesheet if you wanted. Reference: Visibility vs Display in CSS
{ "language": "en", "url": "https://stackoverflow.com/questions/7520377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make VBScript copy permissions along with files This is all in Windows XP utilizing VBScript. I have a directory with several files inside. The files have varying permissions set. I need to be able to copy the files to a new directory while retaining the permissions. Using the script below the copy works fine but the permissions are overwritten by the new parent folder. I am aware of xcopy but I am unsure how to make it work within the script. Using robocopy is a slight possibility but should be avoided if at all possible. Other utilities are out of the question due to network contraints. Any help is greatly appreciated. Dim CopyFromPath, CopyToPath Const WINDOW_HANDLE = 0 Const NO_OPTIONS = 0 Const OverwriteExisting = TRUE Set objShell = CreateObject("Shell.Application") Set objFolder = objShell.BrowseForFolder(WINDOW_HANDLE,"Select folder to copy:",NO_OPTIONS,ssfDRIVES) if (not objFolder is nothing) then Set objFolderItem = objFolder.Self CopyFromPath = objFolderItem.Path else Set objShell = nothing WScript.Quit(0) end if Set objFolder = objShell.BrowseForFolder(WINDOW_HANDLE, "Where should the folder be copied to?:", NO_OPTIONS, ssfDRIVES) if (not objFolder is nothing) then Set objFolderItem = objFolder.Self CopyToPath = objFolderItem.Path else Set objShell = nothing WScript.Quit(0) end if Set objFolder = nothing Set objFolderItem = nothing Set objShell = nothing Set objFSO = CreateObject("Scripting.FileSystemObject") objFSO.CopyFile CopyFromPath & "\*.*", CopyToPath & "\", OverwriteExisting msgbox "The folder has now been copied to " & CopyToPath A: xcopy is a good idea for it. An example to how make it work within vbscript. Set oWSHShell = CreateObject("WScript.Shell") oWSHShell.Exec "xcopy C:\source C:\destination /O /X /H /K /Y" Set oWSHShell = Nothing
{ "language": "en", "url": "https://stackoverflow.com/questions/7520389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query execution order/optimization Given the view create view MyView as select Id, ExpensiveFunction(Name) as Expr from MyTable If used in the query select * from AnotherTable a inner join MyView b on b.Id = a.Id Is ExpensiveFunction computed for every row in MyTable, or is SQL Server smart enough to join to AnotherTable first, and then call ExpensiveFunction for only the filtered rows? Would it behave differently if MyView is a subquery or TVF? A: ExpensiveFunction will only be called when it is relevant. If your final select statement does not even include it at all, the function will, in turn, not be called. Similarly, if the final select only selects one tenth of the table, the function will only be called on that one tenth. This works the same way in sub-queries and inline views. You could specify a function for a field in a sub-query, and if the field is never used, the function will never be executed. It is true that scalar functions are notoriously expensive. It might be possible to reduce the overhead by instead using a table valued function: SELECT MyTable.*, ExpensiveFunction.Value FROM MyTable CROSS APPLY MyFunction(MyTable.field1, MyTable.field2) as ExpensiveFunction Provided that ExpensiveFunction is an inline (i.e. not multi-statement) function, and that it only returns one row, it will usually scale better than scalar functions do. If you use a multi-statement table valued function that returns multiple rows, it will call ExpensiveFunction for every row. Generally, though, you shouldn't have TVFs that return records that will later be discarded. Inline functions, on the other hand, since they can be expanded inline, as if they were a SQL macro, will only call ExpensiveFunction when necessary, like the view. In the example in your question, ExpensiveFunction should only be called when necessary. To be sure, though, you should definitely look at your query execution plan and use an SQL profiler to optimize performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get URL backlinks I am trying to create a script to get the amount of backlinks to particular URLs - the method I am currently using is to query the google search API for link:example.com/foo/bar which returned the amount of results - I used that value to estimate the backlinks. However, I am looking for alternate solutions. A: The most basic approach would be to log $_SERVER['HTTP_REFERER'] on every incoming request, which is the URL of the site linking to your site. I'm sure there are some caveats to this approach (i.e. conditions under which Referer is not sent, potential for being spammed through bogus Referer URLs), but I can't speak to all of them. The Wikipedia page may be a good starting point. There are also pingbacks/trackbacks, but I wouldn't rely on them. A: Pingbacks / Trackbacks are to determine hits from a particular website. These are manual, rather than automatic, and are meaningful when there is a HIT from them. However, the approach you did till now, is something that involves a huge cache of links and backlinks. Either there must be some kind of database to track the nodes of connection between two pages, or you must start builiding your own. Use the available ones, and better build a mashup of more than one database. But, if you want to have strong system built, then verify the backlink from your system, and then maintain the cache at your end too. The cache should include the verified backlinks only. I hope this works. A: I think http://www.opensiteexplorer.org/ and their api might be of more help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What is Windows Azure Storage Analytics? Someone explain to me what it is and how the Windows Azure Storage Analytics works and how I can use it in conjunction with storage. A: Windows Azure Storage Analytics offers profiler like capabilities for Azure Storage (which includes Tables, Blobs and Queues). You can find a very good overview of Azure Storage Analytics directly on MSDN. Then, for digging deeper and also getting some code samples, you can go here related to the logging functionality and here for the metrics one. A: Check out the new Windows Azure Storage Analytics App for Windows 8 in the app store: http://apps.microsoft.com/windows/en-US/app/azure-storage-monitor/e9292e05-c469-403d-a787-63645b861593
{ "language": "en", "url": "https://stackoverflow.com/questions/7520399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: suppress Toast when setting AlarmClock im programming an android app which sets my AlarmClock. Intent i = new Intent(AlarmClock.ACTION_SET_ALARM); i.putExtra(AlarmClock.EXTRA_MESSAGE, "Google Cal Alarm"); i.putExtra(AlarmClock.EXTRA_HOUR, l.getHours()); i.putExtra(AlarmClock.EXTRA_MINUTES, l.getMinutes()); the problem is, that I'm doing that in a background service, but the AlarmClock pops up toasts every time the Clock is set. Can i prevent that? Thanks a lot A: From the docs for AlarmClock... The AlarmClock provider contains an Intent action and extras that can be used to start an Activity to set a new alarm in an alarm clock application. Applications that wish to receive the ACTION_SET_ALARM Intent should create an activity to handle the Intent that requires the permission com.android.alarm.permission.SET_ALARM. Applications that wish to create a new alarm should use Context.startActivity() so that the user has the option of choosing which alarm clock application to use. This suggests to me that AlarmClock is designed to be used in a UI context. Is there a reason why you are using it rather than AlarmManager?
{ "language": "en", "url": "https://stackoverflow.com/questions/7520402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS Button styling I'm still new in CSS, sorry for the long post. I have the following code <style type="text/css"> .btn { float: left; clear: both; background: url(images/btn_left.png) no-repeat; padding: 0 0 0 10px; margin: 5px 0; } .btn a{ float: left; height: 40px; background: url(images/btn_stretch.png) repeat-x left top; line-height: 40px; padding: 0 10px; color: #fff; font-size: 1em; text-decoration: none; } .btn span { background: url(images/btn_right.png) no-repeat; float: left; width: 10px; height: 40px; } .btn_addtocart { background-color: green; } .btn_checkout { background-color: red; } </style> </head> <body> <div class="btn btn_addtocart"><a href="#">Add to Cart</a><span></span></div> <div class="btn btn_checkout"><a href="#">Check Out</a><span></span></div> </body> </html> I'm trying to center each button in the middle of the page (horizontal alignment), how can I accomplish that? I tried playing with the padding and the margin but it messes my background image. Here is jsFiddle A: You can text-align:center the links inside the divs (which are block-level elements) to center them inside their containers but you will have to make a couple of tweaks. Try this: .btn { clear: both; background: url(images/btn_left.png) no-repeat; padding: 0 0 0 10px; margin: 5px 0; text-align:center; } .btn a { height: 40px; background: url(images/btn_stretch.png) repeat-x left top; line-height: 40px; padding: 10px; color: #fff; font-size: 1em; text-decoration: none; } .btn span { background: url(images/btn_right.png) no-repeat; float: left; width: 10px; height: 40px; display: block; } .btn_addtocart a { background-color: green; } .btn_checkout a { background-color: red; } Demo http://jsfiddle.net/andresilich/UtXYY/1/ A: try margin auto, text-align center, fixed width for middle part.. oh ..and get rid of the float, and dont forget the ';' edit code.. .btn { clear: both; background: url(images/btn_left.png) no-repeat; padding: 0 0 0 10px; display: block; margin: 5px auto; text-align: center; width: 120px; } .btn a { height: 40px; background: url(images/btn_stretch.png) repeat-x left top; line-height: 40px; padding: 0 10px; color: #fff; font-size: 1em; text-decoration: none; } .btn span { background: url(images/btn_right.png) no-repeat; width: 10px; height: 40px; } .btn_addtocart { background-color: green; } .btn_checkout { background-color: red; } A: A couple things you can do .btn { display: block margin-left: auto; margin-right: auto; } By default a button is an inline element, so margins will no work. Setting display to block, will make it act like a div.btnParent { text-align:center } The other method is to have the button's containing element text-align center. The may not necessarily always work, as there may be more content in this container that you do not want to be centered. A: I can't fully see from your code snippet but to centre somthing in the middle of its parent, you need to set its margin to auto. margin: auto and its width width: 100px: EDIT: Also remove any float: styles you have on the element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a free php search engine that doesn't use MySQL? I've found several paid options and several options with PHP/MySQL, but does anyone know a free option for implementing a site search option on my page that doesn't use a MySQL database? A: If you want to programme the search functionality yourself and you're using PHP, then you could try the Lucene component that's in Zend Framework. It'll create a file-based index for you, so no MySQL, and you can use a variety of search syntax on it. The index file should also be compatible with the Java implementation of Lucene. http://framework.zend.com/manual/en/zend.search.lucene.html http://framework.zend.com/manual/en/learning.lucene.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7520406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Enrollment Challenge to retrieve UDID from iPhone Ad hoc testing facilities like TestFlight and HockeyApp use a part of the iOS OTA enrollment process to retrieve UDIDs (and possibly other device information, such as device type). How do these services achieve this? I've already figured out how to provide an initial "profile service" payload to send to the phone. I receive a valid response from the phone via a POSt request. After that, I'm clueless, I keep getting an "Invalid profile" error. What am I supposed to send back? Do I really have to set up a complete SCEP process (highly doubtful)? Any hints are greatly appreciated! A: Yes, you have to set up a complete SCEP process. It is documented by Apple with sample ruby code on this URL: http://developer.apple.com/library/ios/#featuredarticles/FA_Wireless_Enterprise_App_Distribution/Introduction/Introduction.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7520407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What's the overhead of TPanel over TBevel I'm working on a project where they essentially used TPanel for the only purpose of displaying a bevel (And maybe the design time convenience Panel have over Bevels). Ok, I know TPanel is heavier than TBevel. Amongs other things, each TPanel create a user objects, which is a limited resource. What I would like to know, beyond user objects, what's the overhead of TPanel? Is it next to non-existent (Especially on modern day machines). If you were working on such a system, would you suggest : * *Going back and changing all TPanel to TBevel. *Say "Ok it was bad. Lets not do it again in the future" or *it's too small a concern and the design time convenience is well worth it. A: I wouldn't know if this design is intentional but, there's a slight navigational behavior difference when controls are grouped together in a window. If the focus is changed by arrow keys, after the one having the last tab order the first control will be focused (down/right), or vice-versa (up/left). IOW the focus will be wrapped in the parent. That's of course if any of the controls do not need the arrow keys. Regarding the question, as it is already stated in the comments, apart from using up a count in an object pool, there're other resources associated with a window. It will also waste a few CPU cycles. There'll be one more level in the clipping chain or the messaging or keeping one more z-order list etc.. MSDN puts it as (I guess navigational aspect is being referred rather than visual partitioning): For best performance, an application that needs to logically divide its main window should do so in the window procedure of the main window rather than by using child windows. Nevertheless, as again already stated in the comments, most probably, no one will be able to tell the performance or resource difference caused by a few panels.. A: The correct answer is choice #3, so if that's the project's design approach, don't change it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the best way to distribute multiple copies of services across servers? We have multiple services that do some heavy data processing that we'd like to put multiple copies of them across multiple servers. Basically the idea is this: * *Create multiple copies of identical servers with the collection of services running on them *a separate server will have an executable stub that will be run to contact one of these servers (determined arbitrarily from a list) to begin the data processing *The first server to be contacted will become the "master" server and delegate the various data processing tasks to the other "slave" servers. We've spent quite a bit of time figuring out how to architect this and I think the design should work quite well but I thought I'd see if anyone had any suggestions on how to improve this approach. A: The solution is to use a load balancer.. I am bit biased here - since I am from WSO2 - the open source WSO2 ESB can be used as a load balancer - and it has the flexibility of load balancing and routing based on different criteria. Also it supports FO load balancing as well... Here are few samples related to load balancing with WSO2 ESB... You can download the product from here... eBay is using WSO2 ESB to process more than 1 Billion transactions per day in their main stream API traffic... A: The first server to be contacted will become the "master" server and delegate the various data processing tasks to the other "slave" servers. That is definitely not how I would build this. I build this with the intent to use cloud computing (regardless of whether it uses true cloud computing or not). I would have a service that would receive requests and save those requests to a queue. I would then have multiple worker applications that will take an item from the queue, mark it in process and do whatever needs done. Upon completion the queue item is updated as done. At this point I would either notify the client that the work is done, or you could have the client poll the server for reading the status of the queue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mockito's @InjectMock annotation I'm a little confused with @RunWith(MockitoJUnitRunner.class) and @InjectMock annotations and how they are related to each other. As per my understanding by giving @RunWith(MockitoJUnitRunner.class) we don't need to initialize the mock like mock(ABC.class). On the other hand @InjectMocks injects the mock automatically with getters and setters. The documentation says: @InjectMocks currently it only supports setter injection. If you prefer constructor injection - please contribute a patch.... What I don't understand is that when I remove @InjectMocks below I get nullpointer exception for the tests as dependency is null. Does that mean construtor based inject is supported? Or does it has something to do with @RunWith(MockitoJUnitRunner.class) Here's the code @RunWith(MockitoJUnitRunner.class) public class MyClassTest { @Mock private Dependency dependency; @InjectMocks private MyClass cls = new MyClass(dependency); //... } class MyClass { private Dependency dependency; MyClass(Dependency dependency) { this.dependency = dependency; } //... } A: As of the latest release, Mockito supports constructor injection. See the latest javadoc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Configuring WSS4J with CXF I was doing pretty well with setting up a contract first set of web services using CXF until I started adding in the WSS4J piece. I'm trying to debug sending a password and login in the soap header. I am getting null when I call getPassword() in the WSPasswordCallback class. I can see from the soap envelope that a password was sent. This post, http://old.nabble.com/PasswordDigest-and-PasswordText-difference-td24475866.html, from 2009, made me wonder if I am missing (need to create) a UsernameTokenHandler. And if that is true, can someone point me to how I would configure it in the spring/cxf bean xml file? Any advice or suggestions would be appreciated. Here's the Java file in question: package com.netcentric.security.handlers; import java.io.IOException; import javax.annotation.Resource; import javax.com.urity.auth.callback.Callback; import javax.com.urity.auth.callback.CallbackHandler; import javax.com.urity.auth.callback.UnsupportedCallbackException; import org.apache.ws.com.urity.WSPasswordCallback; public class ServicePWCallback implements CallbackHandler { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { try { for (int i = 0; i &lt; callbacks.length; i++) { if (callbacks[i] instanceof WSPasswordCallback) { WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; sString login = pc.getIdentifier(); String password = pc.getPassword(); // password is null, not the expected myPASSWORD**1234 int n = pc.getUsage(); // this is 2 == WSPasswordCallback.USERNAME_TOKEN //... The CXF/Spring configuration file: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd" default-dependency-check="none" default-lazy-init="false"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <bean id="serverPasswordCallback" class="com.netcentric.security.handlers.ServicePWCallback"/> <bean id="wss4jInInterceptor" class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor"> <constructor-arg> <map> <entry key="action" value="UsernameToken"/> <entry key="passwordType" value="PasswordText"/> <entry key="passwordCallbackRef"> <ref bean="serverPasswordCallback"/> </entry> </map> </constructor-arg> </bean> <jaxws:endpoint id="FederationImpl" implementor="com.netcentric.services.federation.FederationImpl" endpointName="e:federation" serviceName="e:federation" address="federation" xmlns:e="urn:federation.services.netcentric.sec"> <jaxws:inInterceptors> <bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor"/> <ref bean="wss4jInInterceptor"/> </jaxws:inInterceptors> </jaxws:endpoint> </beans The soap message: <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header> <wsse:comurity xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wscomurity-comext-1.0.xsd" soapenv:mustUnderstand="1"> <wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wscomurity-utility-1.0.xsd" wsu:Id="Timestamp-16757598"> <wsu:Created>2011-09-22T18:21:23.345Z</wsu:Created> <wsu:Expires>2011-09-22T18:26:23.345Z</wsu:Expires> </wsu:Timestamp> <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wscomurity-utility-1.0.xsd" wsu:Id="UsernameToken-16649441"> <wsse:Username>pam</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">myPASSWORD**1234</wsse:Password> </wsse:UsernameToken> </wsse:comurity> </soapenv:Header> <soapenv:Body> <getVersion xmlns="urn:federation.services.netcentric.com"> <getVersionRequest/> </getVersion> </soapenv:Body> </soapenv:Envelope> A: If using CXF 2.4.x, I would recommend reading: http://coheigea.blogspot.com/2011/02/usernametoken-processing-changes-in.html and seeing if that helps provide some extra information. Colm's blog is a treasure trove of useful info about recent WSS4J releases. A: Thanks for all your help. I have made progress on this. I am using CXF 2.4.2 and WSS4J 1.6.2. The framework now takes care of checking the password for you. So the correct inside section is if (callbacks[i] instanceof WSPasswordCallback) { WSPasswordCallback pc = (WSPasswordCallback) callbacks[i]; sString login = pc.getIdentifier(); String password = getPassword(login); pc.getPassword(login); //... } Instead of retrieving the password from the soap header to compare against the expected value, you lookup the expected value and pass it to the framework to do the comparison. A: I add this : // set the password on the callback. This will be compared to the // password which was sent from the client. pc.setPassword("password"); ==> the password between "" will be compared with password sended by client. Client side: write login = bob ; Password = bobPassword (will be digested) Server side: Catch user = bob and the function user.setPassword(bobPassword) verify if the password received is correct or no.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving Flickr Photosets How can I save each photoset to a folder on my server where the the name of the folder would be the title of the photoset. A: Take a look at PHPFlickr. It makes it easy to interface to the Flickr API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tool to Find Out What The Browser is Downloading My PHP Apache website starts to load a part of the content, then it seems to stop loading and then it appends the rest of the page. I would like to know if there is any tool to find out what exactly is being load at the moment by my browser. I prefer Firefox, but any browser works. A: Following the advice of @Ehtesham, I am using Firebug for this purpose. I didn't know that it had this functionality. To download firebug for Firefox: Download Page
{ "language": "en", "url": "https://stackoverflow.com/questions/7520417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hudson - Run console app and fail build if exit code is anything other than 0 I want to run a console app utility as a Windows Batch Command step in my Hudson build. If the console application returns anything other than an exit code of 0, I want to fail my Hudson build. Is this possible? A: That's the default behaviour, so it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sorting small list (10 items) in PHP vs. MySQL and then returning? I'm curious what the runtime cost of sorting a small set of elements returned by a MySQL query is in PHP in contrast to sorting them in MySQL. Reason I can't sort them in MySQL is because of the groups of data being returned, (actually 2 queries and then bringing data together PHP side). Thanks! A: There will be no difference for ten elements. But generally you should always sort in MySQL, not PHP. MySQL is optimized to make sorting fast and has the appropriate data structures and information. PS: Depending on the nature of the data you want to combine: Look at JOINs, UNIONs and subqueries. They'll probably do it. A: My opinion: The overhead is negligible in either case. Optimize your productivity and do whichever is easier for you. The computer is there to help you, not vice versa. If you really want to optimize the host, have you considered letting the client do it in javascript? I'd probably do it in SQL too, but mainly to keep the logic in one place (increase cohesion, reduce coupling). A: you could combine the queries with a union and then sort it with mysql Q1 UNION Q2 ORDER BY X
{ "language": "en", "url": "https://stackoverflow.com/questions/7520422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS unrecognized selector sent to instance - adding NSDictionary to NSMutableArray Apologies for the masses of code but people usually ask for lots in the end anyway. I'm getting the following error when trying to add an NSDictionary to an NSMutableArray 2011-09-22 18:52:54.153 NPT[4788:1603] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x72f1280 2011-09-22 18:52:54.154 NPT[4788:1603] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI addObject:]: unrecognized selector sent to instance 0x72f1280' Call stack at first throw: ( 0 CoreFoundation 0x028e5919 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x02a335de objc_exception_throw + 47 2 CoreFoundation 0x028e742b -[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x02857116 ___forwarding___ + 966 4 CoreFoundation 0x02856cd2 _CF_forwarding_prep_0 + 50 5 NPT 0x00007197 -[Search addPlateToFinals:withSubCount:] + 791 6 NPT 0x0000626f -[Search makeNumberedPlatesForPass:] + 1132 7 NPT 0x0000401f __-[FirstViewController improveSearch]_block_invoke_1 + 173 8 libSystem.B.dylib 0x96f02a24 _dispatch_call_block_and_release + 16 9 libSystem.B.dylib 0x96ef4cf2 _dispatch_worker_thread2 + 228 10 libSystem.B.dylib 0x96ef4781 _pthread_wqthread + 390 11 libSystem.B.dylib 0x96ef45c6 start_wqthread + 30 ) terminate called after throwing an instance of 'NSException' This is the code throwing the error, as far as I can tell from the stack trace and using line breaks: NSDictionary *dPlateToAdd = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; [self.aFinals addObject:dPlateToAdd]; self.aFinals is decalared in the interface, and then as a property, then synthesized and then initialized as follows: Search.h @interface Search : NSObject { ... NSMutableArray *aFinals; ... } ... @property (nonatomic, retain) NSMutableArray *aFinals; ... @end Search.m ... @synthesize aFinals; ... -(id)initWithTerm:(NSString *)thisTerm andPrevResults:(NSMutableArray *)aPrevResults { ... self.aFinals = [aPrevResults copy]; ... } The aPrevResults that is passed in, was a property of a previous search object that has since been released, but has been copied to a property of the view controller, and sent back into a new search object, to add more results. The line that is throwing the error works fine on the first pass, but is only causing a problem on this second run, when I reuse the array that is now aPrevResults. What have I done wrong? Does any of this make sense as at all? A: -copy returns immutable object even if you call it on a mutable array. To get mutable copy you must call mutableCopy method: -(id)initWithTerm:(NSString *)thisTerm andPrevResults:(NSMutableArray *)aPrevResults { ... self.aFinals = [aPrevResults mutableCopy]; ... } Also since you're using retaining property you need to compensate extra increment to retain count occurring on copy: self.aFinals = [[aPrevResults mutableCopy] autorelease]; Or, probably the best and the cleanest solution using convenience class method: self.aFinals = [NSMutableArray arrayWithArray:aPrevResults];
{ "language": "en", "url": "https://stackoverflow.com/questions/7520424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I write a COM dll? To better myself I am attempting to make my dll's COM compliant, I thought I'd just need to extend/implement a few interfaces and job done but now I am at a cross roads, 1) Should I learn MIDL? 2) Should I install the ATL (I am running VC++Express)? 3) Carry on reading the C++ tutorials (http://progtutorials.tripod.com/COM.htm) and hope my Express edition is too limited? A: I was interested in transferring native C++ to Android and Java and read that the libraries would need to expose either static 'C' style functions or implement COM. Android is Linux based operating system... It does not support DLLs and COM. So no you can't go via COM. You need to learn how to use JNI. A: 1) Yes. If you are going to define new interfaces, you pretty much have to. It's not impossible to do without MIDL, but it's way harder than to learn basic MIDL. 2) Yes, please do. It'll hide much of the boiler plate code (which is tedious to write, and error prone). 3) I would recommend the book Essential COM by Don Box. It's awesome. Also, a great companion to that book is Essential IDL by Martin Gudgin. As for VC++ Express - I have never used them. I guess it's possible to do COM with it, but with limited tool/library support.
{ "language": "en", "url": "https://stackoverflow.com/questions/7520426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }