text
stringlengths
8
267k
meta
dict
Q: Disabling specific cells on an NSTableView I have a tableview with 4 columns. The fist one has some text and the other 3 are checkboxes. I need to disable 2 of the 3 checkboxes in one particular row. I keep the row number on an NSInteger variable. I've implemented: - (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex Where I check the columns identifier to know whether I am at the right column, once I know that I check if the row is correct and set the cell to disable. Code follows: - (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex { if(([[aTableColumn identifier] isEqualToString:@"column1"]) || ([[aTableColumn identifier] isEqualToString:@"column2"])) { if (rowIndex == myindex) // myindex holds the row index where I need to disable the cells { [aCell setEnabled:NO]; } } else { return; } } What happens is strange. Colum1 and Colum2 for my specific row are disabled until I click another row, then all the rows get these two columns disabled. How do I disable these two very specific cells (only in myindex row and only column1 and column2)? this is a Mac OS X app, not an iOS app. Thanks A: You have to explicitly set the enabled property each time for both cases. //... else { [aCell setEnabled:YES]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7613990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Parsing a "rgb (x, x, x)" String Into a Color Object Is there an effecient way/existing solution for parsing the string "rgb (x, x, x)" [where x in this case is 0-255] into a color object? [I'm planning to use the color values to convert them into the hex color equivilience. I would prefer there to be a GWT option for this. I also realize that it would be easy to use something like Scanner.nextInt. However I was looking for a more reliable manner to get this information. A: For those of use who don't understand regex: public class Test { public static void main(String args[]) throws Exception { String text = "rgb(255,0,0)"; String[] colors = text.substring(4, text.length() - 1 ).split(","); Color color = new Color( Integer.parseInt(colors[0].trim()), Integer.parseInt(colors[1].trim()), Integer.parseInt(colors[2].trim()) ); System.out.println( color ); } } Edit: I knew someone would comment on error checking. I was leaving that up to the poster. It is easily handled by doing: if (text.startsWith("rgb(") && text.endsWith(")")) // do the parsing if (colors.length == 3) // build and return the color return null; The point is your don't need a complicated regex that nobody understands at first glance. Adding error conditions is a simple task. A: As far as I know there's nothing like this built-in to Java or GWT. You'll have to code your own method: public static Color parse(String input) { Pattern c = Pattern.compile("rgb *\\( *([0-9]+), *([0-9]+), *([0-9]+) *\\)"); Matcher m = c.matcher(input); if (m.matches()) { return new Color(Integer.valueOf(m.group(1)), // r Integer.valueOf(m.group(2)), // g Integer.valueOf(m.group(3))); // b } return null; } You can use that like this // java.awt.Color[r=128,g=32,b=212] System.out.println(parse("rgb(128,32,212)")); // java.awt.Color[r=255,g=0,b=255] System.out.println(parse("rgb (255, 0, 255)")); // throws IllegalArgumentException: // Color parameter outside of expected range: Red Blue System.out.println(parse("rgb (256, 1, 300)")); A: I still prefer the regex solution (and voted accordingly) but camickr does make a point that regex is a bit obscure, especially to kids today who haven't used Unix (when it was a manly-man's operating system with only a command line interface -- Booyah!!). So here is a high-level solution that I'm offering up, not because I think it's better, but because it acts as an example of how to use some the nifty Guava functions: package com.stevej; import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; public class StackOverflowMain { public static void main(String[] args) { Splitter extractParams = Splitter.on("rgb").omitEmptyStrings().trimResults(); Splitter splitParams = Splitter.on(CharMatcher.anyOf("(),").or(CharMatcher.WHITESPACE)).omitEmptyStrings() .trimResults(); final String test1 = "rgb(11,44,88)"; System.out.println("test1"); for (String param : splitParams.split(Iterables.getOnlyElement(extractParams.split(test1)))) { System.out.println("param: [" + param + "]"); } final String test2 = "rgb ( 111, 444 , 888 )"; System.out.println("test2"); for (String param : splitParams.split(Iterables.getOnlyElement(extractParams.split(test2)))) { System.out.println("param: [" + param + "]"); } } } Output: test1param: [11]param: [44]param: [88]test2param: [111]param: [444]param: [888] It's regex-ee-ish without the regex. It is left as an exercise to the reader to add checks that (a) "rgb" appears in the beginning of the string, (b) the parentheses are balanced and correctly positioned, and (c) the correct number of correctly formatted rgb integers are returned. A: And the C# form: public static bool ParseRgb(string input, out Color color) { var regex = new Regex("rgb *\\( *([0-9]+), *([0-9]+), *([0-9]+) *\\)"); var m = regex.Match(input); if (m.Success) { color = Color.FromArgb(int.Parse(m.Groups[1].Value), int.Parse(m.Groups[2].Value), int.Parse(m.Groups[3].Value)); return true; } color = new Color(); return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7613996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Kohana Database Configuration System I am trying to get the database configuration functionality working with kohana 3.2. I want to attach the Config_Database as source: Kohana::$config->attach(new Config_Database, False); Described here: http://kohanaframework.org/3.2/guide/kohana/config I attach the new source after loading the modules (so the database module is loaded before attaching the source). But when I have attached the new source it seems as if kohana does not want to load any controller using the Auth module with ORM driver. Then the browser loads and loads but only a white page appears. All other controller, not using the ORM or Auth module, function properly. Can anyone give a short explanation how to use the Config_Database functionality, or give a alternative. A: Update ORM module to 3.2/develop
{ "language": "en", "url": "https://stackoverflow.com/questions/7613997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET file download - detect if user cancelled download? I have an ASP.NET application which lets users download files from my web server. I track the downloads, and only allow so many downloads of a file. I have the following code to invoke the download for my users (on click of a button): string sURL = sExternalSequenceFullPath + Session["sFilename"].ToString(); FileInfo fileInfo = new FileInfo(sURL); Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.Flush(); Response.WriteFile(fileInfo.FullName); My problem is that the browser presents the user with the ability to download (save/saveas) or cancel. Is there a way to know if the user cancelled? If they did cancel, I don't want to count the download against them. If not, is there another way to do with [without adding something to the client's machine]. A: There is no way that I know of this can be done. I would present the user with a dialog, that would call your download code. If they selected "Yes" to the dialog, I would count that against them. The other option is to write a plugin(Silverlight, Flash...etc) so that you have control. A: Not sure it is still helpful, but I have pretty much the same code for managing downloads, except mine is wrapped in a try..catch block, due to being in a referenced assembly for my site and the need to throw the exception up to my global error handler. when a user cancels the download, i get a 'The remote host closed the connection.' exception and i step into my catch block. I may be way off the mark (I have only been coding for a year :) ) but perhaps it could be something as simple as decrementing the download count in a catch block? A: Have you tried to handle the cancel button's click event? A: you can use Sockets and download the file using the HTTP protocol (or FTP but would still need to access by using UserName and Password). If you do utilize Sockets though, the user will not be shown the Browser's download window. This might make users distrust your site. I don't think it is possible to achieve by using the Browser's download Dialog, I will keep checking on this thread however to see if it's possible at all. Check this out to find some Socket programming examples. Good luck on this task. Hanlet EDIT: I just found This check it out, maybe it might help you. A: How about this: Response.BufferOutput = false; Response.TransmitFile(fileInfo.FullName); //increment download count If you disable response output buffering then it won't move past the line of code that sends the file to the client until the client has finished receiving it, so you can safely increment the download count in the next line of code. As SamV said in his answer if they cancel the download even half way through it throws a HttpException so the increment download count code doesn't get run. I also suggest using the TransmitFile method instead of the WriteFile method since it doesn't load the entire file into memory wasting server resources.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iOS - Using NSMutableDictionary for grouping I have a method which is passed a dict (whose values themselves consist of nested dicts), and I am using recursion to traverse this dict, and I want to store only the information I need in another dict which is also passed to the method as the second argument. So, the method (ignoring some optional arguments that's needed to aid recursion) looks like: -(NSMutableDictionary*) extractData: (NSDictionary*)complicatedDict intoSimpleDict:(NSMutableDictionary*)simpleDict { // do recursive traversal of complicatedDict and return simpleDict } I am facing two problems: a. I need to pass an empty dict initially when I first call the method. How do I initialize an empty NSMutableDictionary to pass as the simpleDict parameter? b. I am trying to group values having common key in the simpleDict. In JS (which is my most familiar language), I will implement it like: if( !simpleDict.hasOwnProperty('some_key') ) { simpleDict['some_key'] = []; } simpleDict['some_key'].push("value"); The above code would initially an array in each index of the dict, and push the value to it. How do I do this in objective-c? A: a. Create an empty mutable dictionary simply like this NSMutableDictionary *empty = [NSMutableDictionary dictionary]; b. This is equivalent to your JS example if(![[simpleDict allKeys] containsObject:@"some_key"]) [simpleDict setObject:[NSMutableArray array] forKey:@"some_key"]; [[simpleDict objectForKey:@"some_key"] addObject:@"value"]; A: a. You have a couple options here. For one, you could simply call your method like this: [myObject extractData:complicatedDict intoSimpleDict:[NSMutableDictionary dictionary]]; That will create an autoreleased dictionary object that you can manipulate in your method body and return. Just remember that whoever needs to keep that dictionary should retain it. The other way is to just create the dictionary in the method body: -(NSMutableDictionary*) extractData:(NSDictionary*)complicatedDict { NSMutableDictionary *simpleDict = [NSMutableDictionary dictionary]; // do recursive traversal of complicatedDict and return simpleDict return simpleDict; } b. Just saw @Joe posted and has a good solution for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this good or bad practice to use non-nested classes in same source file under same name space Possible Duplicate: C# classes in separate files? I came to a new company and found that a C# project had in it a single source file.., that had within it two interfaces and two public classes. (Truth is this is how they do things in most of their projects.) Neither of the three classes were nested. They did however have a chain of inheritance.., starting with on of the two classes using dependency injection. Question 1: So my question really is NOT regarding the pattern as much as what is good practice regarding whether or not each of these interfaces should be in on single source file or a source file per class or interface? Question 2: Is there a good blog, forum, link, or book addressing this issue? I don't instantly like this kind of practice with a single source file being used. I'm use to single a source file per class or interface. I like a source file per class or interface because it gives me file level browse regarding encapsulation possibilities. Also the name of the file starts with ISomething and then has two public classes in it. :( A: It is a bad practice only if it violates name-matches-content rule. So if you have Foo.cs and inside you got class Foo and Bar, then that would be a problem. However it is totally cool to have to have Vehicles.cs with classes Car and Truck inside. This is just my personal rule that served me well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I force Google Chrome to ignore built-in keystrokes and pass them to jquery I'm developing commerce system. I want the system to be as lightweight as possible. I develop it on linux, of course. I want to achieve this: I want to develop something like a desktop environment, just in HTML5/CSS3/jQuery. I'm in a early phase of development, I'm testing several possibilities. Now I know, I can boot right to google chrome in kiosk mode. I can therefore develop anything I want, the only limitation is the screen resolution. I've been testing jQuery Hotkeys. Now I know I can handle pretty much any hotkey, except for those like Alt-F4, Ctrl-W, and so on. Is it possible to force these hotkeys to be ignored by chrome and passed to script? Thanks for any help A: No. Script can never override browser behavior. It is not possible to catch browser-defined keyboard shortcuts. If your application is to be used on systems you have control over (in other words, it's an internal app), you could write a wrapper for the WebKit engine that does not have its own keyboard shortcuts, or perhaps use an existing one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable the JavaScript for current page by using JavaScript I have an unusual problem. I've made a page filled with some JS. Old browsers simply mess it up. A lot of it is included directly in the page, not in separate files and not inline. I wonder if there is a way to generate (using PHP) some JS that would make the browser ignore all the following scripts? Otherwise I have to make conditional inclusion of all the JS and that is something I really would like to avoid. Thanks for any proposals. A: One way to solve this would be to detect the browser using javascript and then not running certain portions of the javascript if the browser version is one of the ones where you don't want it to run. Another alternative (and possibly slightly easier method) would be to do the browser detection in the php code and only render out the javascript if the browser isnt one of the old one's that you want to avoid. http://www.javascripter.net/faq/browsern.htm is a good link as to how to detect the browser in javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JNA GetExitCodeProcess() working strangely I have a very strange problem with JNA. I am checking if a process exists by using GetExitCodeProcess(). So for example, I know notepad is PID 2084. When I use my method to check if PID 2084 exists, it returns true for PIDs between 2084 and 2087 (even though I am completely sure that PIDs 2085-2087 don't exist). It returns false for other PIDs, like 2083 and 2088. It's almost as if there is some kind of impossible rounding error, and OpenProcess() is opening a handle on a PID that doesn't exist! This is happening with all processes. If I enumerate all the processes and call isRunning(PID), it returns true when PID + 1,2 or 3 exist. It returns false otherwise, so at least it's working partially. The pattern is always the same, it returns true between PID and PID + 3. Example output: [Notepad PID = 2084, cmd.exe PID = 2100] isRunning(2083)=False isRunning(2084)=true isRunning(2085)=true isRunning(2086)=true isRunning(2087)=true isRunning(2088)=false .... false ..... isRunning(2100)=true etc.. Interface code: protected interface Kernel32 extends StdCallLibrary { Kernel32 INSTANCE = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class); public Pointer OpenProcess(int dwDesiredAccess, boolean bInheritHandle, int dwProcessId); int GetLastError(); boolean GetExitCodeProcess(Pointer hProcess, IntByReference lpExitCode); }; Function code: public static boolean isRunning(int pid) { final int PROCESS_QUERY_INFORMATION = 0x0400; final int STILL_ALIVE = 259; final int INVALID_PARAM = 87; Pointer hProcess = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, false, pid); int error = kernel32.GetLastError(); if (error == INVALID_PARAM) return false; //Invalid parameter. IntByReference exitCode = new IntByReference(); kernel32.GetExitCodeProcess(hProcess, exitCode); if (exitCode.getValue() != STILL_ALIVE) return false; else return true; } public static void main(String[] args) { System.out.println(isRunning(2083)); //Proceses with PID 2083, 2085 to 2088 do not exist. System.out.println(isRunning(2084)); //2084 is notepad System.out.println(isRunning(2085)); System.out.println(isRunning(2086)); System.out.println(isRunning(2087)); System.out.println(isRunning(2088)); } A: That's a Windows implementation detail. The 2 least significant bits of the PID are ignored. So in your example, 2084-2087 all refer to the same process. Raymond Chen wrote about this already: Why does OpenProcess succeed even when I add three to the process ID? You would do well to heed the following caveat: Again, I wish to emphasize that the behavior you see in Windows NT-based kernels is just an implementation artifact which can change at any time. A: Answering the question you didn't actually ask, but is the elephant in the room here: I am checking if a process exists by using GetExitCodeProcess(). Bad strategy - process IDs get reused/recycled, so it's entirely possible that once notepad with PID 2084 dies, the PID will be recycled into some other random process, and GetExitCodeProcess could give you the false impression that notepad was still alive (when it's actually some other process that just happens to have the same PID that's now alive). So everything might appear to work fine when you test your code on your machine - but then occasionally fail randomly and mysteriously in the real world. You might be able to make it work [better] if you save more than just the PID - eg save also the exe name (GetModuleFileNameEx), but even then you'll run into trouble if a new instance of the same app gets created. Save the main HWND too for good measure; HWNDs are recycled also, but at a much much much slower rate than PIDs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP: Every X weeks for Calendar, Recurring Events I'm trying to get every X days from a given date for a calendar. I think I have the logic down to an extent, but for a small window of dates I am getting unexpected results. My code below taken from my project: $start_time = 1345935600; //Sept 25th 2011; $end_time = 1355011200; //Dec 9th 2011; $sStartDate = date("Y-m-d", $start_time) . " " . date("H:i:s", strtotime("00:00:00")); $sEndDate = date("Y-m-d", $end_time) . " " . date("H:i:s", strtotime("00:00:00")); $sCurrentDate = $sStartDate; while($sCurrentDate < $sEndDate) { $t_date = strtotime($sCurrentDate); $s_date = strtotime(date("Y-m-d", strtotime("08/30/2011"))); $recurs_every = 60 * 60 * 24 * 2; //occurs every 2 days echo date("Y-m-d H:i:s", $t_date) . " " . date("Y-m-d H:i:s", $s_date) . " " . (($t_date - $s_date) % $recurs_every) . " " . $recurs_every . "<BR>" ; $sCurrentDate = date("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate))); } Outputs (current date - start date - modular) : 2011-09-25 00:00:00 2011-08-30 00:00:00 0 2011-09-26 00:00:00 2011-08-30 00:00:00 86400 .... 2012-10-27 00:00:00 2011-08-30 00:00:00 0 2012-10-28 00:00:00 2011-08-30 00:00:00 86400 2012-10-29 00:00:00 2011-08-30 00:00:00 3600 2012-10-30 00:00:00 2011-08-30 00:00:00 90000 2012-10-31 00:00:00 2011-08-30 00:00:00 3600 2012-11-01 00:00:00 2011-08-30 00:00:00 90000 2012-11-02 00:00:00 2011-08-30 00:00:00 3600 2012-11-03 00:00:00 2011-08-30 00:00:00 90000 2012-11-04 00:00:00 2011-08-30 00:00:00 3600 2012-11-05 00:00:00 2011-08-30 00:00:00 90000 The last few lines are the issue for me. 3600 is one hour and I don't know where this is coming from. Strange thing is, fast forward to march 26 2012 and it starts to work again but same error occurs at Oct 29 2012... I've been at this for a few hours and can't figure this out. Any help really appreciated! Thanks A: In some contries there is a summer & winter time where the clock is converted one hour (@ 27 march & 30 oct). Therefore there is a one hour difference. -> http://en.wikipedia.org/wiki/Daylight_saving_time Example: <? error_reporting(E_ALL); $start_time = 1345935600; //Sept 25th 2011; $end_time = 1355011200; //Dec 9th 2011; $sStartDate = date("Y-m-d", $start_time) . " " . date("H:i:s", strtotime("00:00:00")); $sEndDate = date("Y-m-d", $end_time) . " " . date("H:i:s", strtotime("00:00:00")); $sCurrentDate = $sStartDate; $lastDate = 0; $corr = 0; while($sCurrentDate < $sEndDate) { $t_date = strtotime($sCurrentDate); $s_date = strtotime(date("Y-m-d", strtotime("08/30/2011"))); $recurs_every = 60 * 60 * 24 * 2; //occurs every 2 days echo date("Y-m-d H:i:s", $t_date) . " " . date("Y-m-d H:i:s", $s_date) . " " . (($t_date - $s_date + $corr) % $recurs_every) . " " . $recurs_every . "<BR>" ; $lastDate = strtotime($sCurrentDate); $sCurrentDate = date("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate))); if(strtotime($sCurrentDate) - $lastDate != 60 * 60 * 24) { $corr -= strtotime($sCurrentDate) - $lastDate - 60 * 60 * 24; } } ?> A: I have given you the answer for answering the question and the effort. In the end, I had a rethink and did more googling and this is what I have come up with. $start_time = 1316905200; $end_time = 1320537600; $sStartDate = date("Y-m-d", $start_time); $sEndDate = date("Y-m-d", $end_time); $sStartDate = new DateTime($sStartDate); $sEndDate = new DateTime($sEndDate); $sCurrentDate = $sStartDate; $recurs_every = 60 * 60 * 24 * 2; //occurs every 2 days while($sCurrentDate->format('U') < $sEndDate->format('U')) { $s_date = new DateTime("08/30/2011"); echo $sCurrentDate->format('Y-m-d') . " " . $s_date->format('Y-m-d') . " " . ceil(($sCurrentDate->format('U') - $s_date->format('U') - (chkTransitions($sCurrentDate->format('U')) == 'GMT' ? 3600 : 0)) % $recurs_every) . "<BR>"; $sCurrentDate->add(new DateInterval('P1D')); } function chkTransitions($dt) { $timezone = new DateTimeZone("Europe/London"); $transitions = $timezone->getTransitions($dt, $dt); $offset = $transitions[0]['offset']; $abbr = $transitions[0]['abbr']; return $abbr; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7614021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error while calling function from linq query Here the code which i have written, I am getting error as soon as i added the line to call the second function which is ValidCodes = GetValidCodes(bv.Variable_Id) public IQueryable<BvIndexRow> GetBenefitVariableIndex(int healthPlanId) { var q = from bv in Db.BenefitVariables where bv.Private == "N" || (bv.Private == "Y" && bv.Health_Plan_ID == healthPlanId) join bao in Db.baObject on bv.Variable_Id equals bao.ba_Object_id join servicetype in Db.BenefitVariableServiceTypes.Where(bvst => bvst.Key_Service_Type == "Y" && bvst.isActive == 1) on bv.Variable_Id equals servicetype.Variable_Id into groupedBvst where bv.isActive == 1 && bao.isActive == 1 from bvst in groupedBvst.DefaultIfEmpty() select new BvIndexRow { // some code here too ValidCodes = GetValidCodes(bv.Variable_Id) }; return q; } public string GetValidCodes(int varID) { // some code here return "None"; } A: Linq to Sql cannot resolve the method call GetValidCodes(..) into an operation in the context of the database - you will have to fill in that property once you have brought back your results into memory or alternatively fill in the corresponding linq to sql statements directly. A: Another poster has answered why, but not what to do. The why is that the method call cannot be translated by Linq-to-SQL into SQL, as it's... not part of SQL! This makes perfect sense! So an easy way to fix this is: public IQueryable<BvIndexRow> GetBenefitVariableIndex(int healthPlanId) { var q = (... your query ... select new BvIndexRow { Type = (bv.Private.ToLower() == "y" ? "Private " : "Public ") + (bao.ba_system_variable_ind ? "System" : "Benefit"), Class = bv.Variable_Classification, ServiceType = bvst.Service_Type.Service_Type_Name ?? string.Empty, LineOfBusiness = bv.LOB, Status = bv.Status.ToLower() == "p" ? "Production" : "Test", Name = bao.ba_object_Code, Description = bao.ba_Object_Desc, Id = bv.Variable_Id, }).ToArray(); foreach (var bvIndexRow in q) { bvIndexRow.ValidCodes = GetValidCodes(bvIndexRow .Variable_Id); } return q; } This should give you want you want! EDIT: By the by, you probably also want to call .ToList() or .ToArray() on your list of BvIndexRows. This has the effect of causing immediate evaluation and will prevent a multiple enumeration. If you don't want immediate evaluation you may need to edit your question to explain why that's the case. I've added a .ToArray() to the example above, but I also wanted to explain why!
{ "language": "en", "url": "https://stackoverflow.com/questions/7614025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: waiting for swfobject.js to load gives me an infinite loop I have a javascript script that uses SWFobject to embed a flash player. When i got to embed the flash player with swfobject.embedSWF(..) i get an error reading that swfobject is undefined. I believe this is happening because our website caches the javascript for my application but doesn't cache the swfobject.js file, so myApp.js, which calls swfobject.embedSWF(..) loads long before swfobject.js. I currently can't change what's being cached, so i came up with this work around: while(!$(that.mediaPlayer).find('#'+that.playerID)[0]){ console.log(that.playerID+' not defined'); that.embedFlashPlayer(1,1); } ... this.embedFlashPlayer = function (width, height){ var that = this; var playerID = that.playerID; var server = document.URL.replace(/^.*\/\//,'').replace(/\..*$/,''); var flashvars = {}; var flashSrc = "/flash/AS3MediaPlayer.swf?server"+server+"&playerID="+playerID; //parameters var params = {}; params.movie = flashSrc; params.quality = "high"; params.play = "true"; params.LOOP = "false"; params.wmode = "transparent"; //attributes var attr = {}; attr.classid = "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"; attr.codebase = "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,16,0"; attr.width = "" + width; attr.height = "" + height; attr.id = playerID; //console.log("embedding flash object with id "+playerID); //command to embed flash object try{ swfobject.embedSWF(flashSrc, "no-flash", width, height,"9.0.0","",flashvars,params); }catch(err){ // I DON'T KNOW WHAT TO DO HERE } return true; } My code checks to see if the flash object has been written. If it hasn't, it calls embed this.embedFlashPlayer() repeatedly in a while loop until the the div containing the swf can be found. The trouble is that this just loops forever. Any suggestion on what i can do in the try-catch block if swfobject is undefined? I am 90% sure this is because my script loads faster and is running the embedSwfObject command before the library has loaded, but i may be wrong. My script runs in $(function(){...}) command. Any theories, suggestions, ideas as to how i can resolve this would be appreciated. A: while ...? Use window.setInterval: ... var interval = window.setInterval(function(){ //Code to check whether the object is ready or not. if($(that.mediaPlayer).find('#'+that.playerID).length){ clearInterval(interval); } }, 100); //Each 100ms = 10 times a second. ... You're trying to use while for polling. setInterval is usually used instead of while, because (as you may have noticed), while causes the browser to "hang".
{ "language": "en", "url": "https://stackoverflow.com/questions/7614028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Single Page loads all Reports from Reporting Services - Security and Performance issues? I am migrating an extensive set of reports from classic asp web application into Reporting Services, and I've hit an interesting design issue. My planned architecture consists of an IIS application server running a Classic ASP application and a database server running SQL Server 2008 Reporting Services. The basic problem is maintaining security during the transition from the asp application to the reports in SSRS. The asp application collects information from the user and generates parameters which it will then post to the Report Server. This setup would require that the Report Server accept anonymous requests for Reports, essentially defeating the built in Active Directory security. This means a malicious user could create his own html page with his own report parameters and post to my Report Server, allowing him complete access into the data in my database. As it stands this architecture would result in a pretty significant security breach. My classic ASP already defines user accounts and roles, so I'd like to use those accounts to restrict access to the reports. My plan is to add a .NET application to my application server which load reports for the user using the Report Viewer control. The user session can be transferred securely from classic asp to asp.net in a number of ways. Then the Report Viewer can authenticate against the Report Server using the ASP.NET process account. This design however, results in all of my users being routed to a single page for all of the reports in the system. Will this result in a performance hit to the website? It seems like the performance gain I get from moving all the reports into SSRS will be lost if I then serve them all up through the IIS app server. And I'm not sure what the effect will be if 90% of my web traffic gets routed down to one asp.net page. Are these legitimate concerns? Am I going about this all wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/7614029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: python, create a filtered list from a text document Every time I try to run this program, Python IDLE responds by telling me that it is not responding and has to close. Any suggestions on how to improve this code to make it work the way I want? #open text document #filter out words in the document by appending to an empty list #get rid of words that show up more than once #get rid of words that aren't all lowercase #get rid of words that end in substring 'xx' #get rid of words that are less than 5 characters #print list fin = open('example.txt') L = [] for word in fin: if len(word) >= 5: L.append(word) if word != word: L.append(word) if word[-2:-1] != 'xx': L.append(word) if word == word.lower(): L.append(word) print L A: Some general help: Instead of fin = open('example.txt') You should use with open('example.txt', 'r') as fin: then indent the rest of the code, but your version will work. L = [] for word in fin: It doesn't iterate by word, but by line. If there is one word per line, each will still have a newline at the end, so you should do word = word.rstrip() to clear any whitespace after the end of the word. If you actually want to do this one word at a time, you need two for loops, like: for line in fin: for word in line.split(): and then put the logic inside the inner loop. if len(word) >= 5: L.append(word) With stripping the whitespace, that will add any word five letters or longer to the list. if word != word: L.append(word) word will always be equal to word, so this does nothing. If you want to eliminate duplicates, make L a set() and use L.add(word) instead of L.append(word) for words you want to add to the list (assuming order doesn't matter). if word[-2:-1] != 'xx': L.append(word) If you're trying to see if it ends with 'xx', use if not word.endswith('xx'): instead, or word[-2:] without the -1, otherwise you're just comparing to the next-to-last-letter rather than the whole thing. if word == word.lower(): L.append(word) This adds the word to the list if the word is all lowercase. Keep in mind, all of these if tests will be applied to every word, so you will add the word to the list once for each test it passes. If you only want to add it once, you can use elif instead of if for all the tests except the first one. Your comments also imply you're somehow "getting rid" of words by adding them to the list -- you're not. You're keeping the ones you add to the list, and the rest just go away; you're not changing the file in any way. A: import re def by_words(it): pat = re.compile('\w+') for line in it: for word in pat.findall(line): yield word def keepers(it): words = set() for s in it: if len(s)>=5 and s==s.lower() and not s.endswith('xx'): words.add(s) return list(words) To get 5 words from War and Peace: from urllib import urlopen source = urlopen('http://www.gutenberg.org/ebooks/2600.txt.utf8') print keepers(by_words(source))[:5] prints ['raining', 'divinely', 'hordes', 'nunnery', 'parallelogram'] This does not take much memory. War and Peace only had 14,361 words that fit your criteria. The iterators work on very small chunks. A: I did your homework for you, i was bored. there might be a bug. homework_a_plus = [] #open text document with open('example.txt', 'r') as fin: for word in fin: #get rid of words that show up more than once if word in homework_a_plus: continue #get rid of words that aren't all lowercase for c in word: if c.isupper(): continue #get rid of words that end in substring 'xx' if word[-2:] == 'xx': continue #get rid of words that are less than 5 characters if len(word) < 5: continue homework_a_plus.append(word) print homework_a_plus EDIT: like Wooble said, your logic is way off in the code you provided. Compare your code with mine and I think you will understand why yours has a problem. A: words = [inner for outer in [line.split() for line in open('example.txt')] for inner in outer] for word in words[:]: if words.count(word) > 1 or word.lower() != word or word[-2:] == 'xx' or len(word) < 5: words.remove(word) print words A: If you want to write this more as a filter... I would take a slightly different approach. fin = open('example.txt','r') seenList = [] for line in fin: for word in line.split(): if word in seenList: continue if word[-2:] == 'xx': continue if word.lower() != word: continue if len(word) < 5: continue seenList.append(word) print word This has the side benefit of showing you each line as it's output. If you want to output to a file instead, modify the print word line appropriately, or use shell redirection. EDIT: If you really don't want to print ANY duplicated words (the above just skips every instance after the first), than something like this works... fin = open('example.txt','r') seenList = [] for line in fin: for word in line.split(): if word in seenList: seenList.remove(word) continue if word[-2:] == 'xx': continue if word.lower() != word: continue if len(word) < 5: continue seenList.append(word) print seenList A: Do it the easy way with a regex: import re li = ['bubble', 'iridescent', 'approxx', 'chime', 'Azerbaidjan', 'moon', 'astronomer', 'glue', 'bird', 'plan_ary', 'suxx', 'moon', 'iridescent', 'magnitude', 'Spain', 'through', 'macGregor', 'iridescent', 'ben', 'glomoxx', 'iridescent', 'orbital'] reg1 = re.compile('(?!\S*?[A-Z_]\S*(?=\Z))' '\w{5,}' '(?<!xx)\Z') print set(filter(reg1.match,li)) # result: set(['orbital', 'astronomer', 'magnitude', 'through', 'iridescent', 'chime', 'bubble']) If the data aren't in a list but in a string: ss = '''bubble iridescent approxx chime Azerbaidjan moon astronomer glue bird plan_ary suxx moon iridescent magnitude Spain through macGregor iridescent ben glomoxx iridescent orbital''' print set(filter(reg1.match,ss.split())) or reg2 = re.compile('(?:(?<=\s)|(?<=\A))' '(?!\S*?[A-Z_]\S*(?=\s|\Z))' '\w{5,}' '(?<!xx)' '(?=\s|\Z)') print set(reg2.findall(ss))
{ "language": "en", "url": "https://stackoverflow.com/questions/7614039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax multiple requests at the same time recently I developed a project were I send multiple ajax requests at a single aspx page. I also put a timer were this request is happening with interval 5 seconds. Everything seems to work fine until suddenly the responses mix up. I know that I could do the same thing with one request, but I wonder why this is happening. I looked around the internet but I can't find any solution yet. I now actually adopted this style of coding like making one request with multiple results, but I wonder and I really want to know how to make multiple ajax request were the response will not mix up. This is my sample Code: $(document).ready(function () { var a = setInterval("request1()", 5000); var b = setInterval("request2()", 5000); }); function request1() { $.ajax({ url: 'ajaxhandler.aspx?method=method1' , beforeSend: function (xhr) { xhr.overrideMimeType('text/plain; charset=utf-8'); }, success: function (data) { alert(data); } }); } function request2() { $.ajax({ url: 'ajaxhandler.aspx?method=method2' , beforeSend: function (xhr) { xhr.overrideMimeType('text/plain; charset=utf-8'); }, success: function (data) { alert(data); } }); } A: If you need the requests to happen in order, you shouldn't be using AJAX (the first "a" is for "asynchronous"). To address this you can call request2() in the callback for the "success" of your first request. function request1() { $.ajax({ url: 'ajaxhandler.aspx?method=method1' , beforeSend: function (xhr) { xhr.overrideMimeType('text/plain; charset=utf-8'); }, success: function (data) { request2(); } }); } A: This is not JavaScript fault, it's messed up because you are calling a single page in same time. If you had two server side page for your two AJAX files then it would be fine. Try to create two different aspx file for you different methods to have them called together. But that would not be a good practice. Why don't sent the method as an parameter and have a condition in your aspx file for different methods? Then if you have two (or more) methods used at the same time, then simply send both to server with an single call. You will save a HTTP header and call delay for your call. function requestAll() { $.ajax({ url: 'ajaxhandler.aspx' , data: ['method1', 'method2'], beforeSend: function (xhr) { xhr.overrideMimeType('text/plain; charset=utf-8'); }, success: function (data) { alert(data); } }); } A: As has been stated, you cannot guarantee the order that the results return in. But if it is necessary to be able to determine this, you could conceivably create a unique identifier for each asynchronous request that is made, then sort out the incoming responses accordingly. An example where I see such a solution being useful is when performing actions on keystroke (e.g. onkeyup). When doing something like this, you may wish to encode a timestamp, version number, or similar, so that you can guarantee some sort of order. If the user is attempting to search "test", it is possible that the autocomplete response for "tes" would be returned before the response for "te". If you simply overwrite the autocomplete data, then this will obviously not be the desired behavior, as you could display incorrect results for the current search token(s). Encoding a timestamp (or unique ID, counter, version number, key, etc.) will allow you to check this to verify that you have the most up-to-date response, or sort the results by timestamp if you need to guarantee order, etc. A: The function below will accept an array of urls for JSON requests, and invoke the callback with an array of results once all requests have completed. It can be easily adapted to non-JSON use. The idea is to stash incoming responses into an array as they arrive, and then only invoke the callback once all results are in. This approach is a nice way to batch updates to the DOM and to avoid having a timer for each node you want to update. function multi_getJSON(urls, callback) { // number of ajax requests to wait for var count = urls.length; // results of individual requests get stuffed here var results = []; // handle empty urls case if(count === 0) { callback(results); return; } urls.forEach(function(url, index) { $.getJSON(url, function(data) { results[index] = data; count = count - 1; // are we finished? if(count === 0) { callback(results); } }); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7614042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: iphone sqlite insert... EXC_BAD_ACCESS First of all, I'm fairly new to iPhone development, and brand new to incorporating sqlite3 in my app. I have used it in my Android and Blackberry apps, so I know basic commands and such. Here is my problem: I created a db and table programmatically (both were created correctly). Here is the code I used to creative the table: const char *sql_stmt = "CREATE TABLE IF NOT EXISTS EXPENSES (id integer primary key autoincrement, unix_date integer, date_time text, purpose text, start_mile text, end_mile text, distance text, fees text, party_id integer)"; The table was created properly. This the function I used to save data: - (void) saveData { sqlite3_stmt *statement; const char *dbpath = [databasePath UTF8String]; NSString *timestamp = [NSString stringWithFormat:@"%d", (long)[[NSDate date] timeIntervalSince1970]]; if (sqlite3_open(dbpath, &expenseDB) == SQLITE_OK) { NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO EXPENSES (timestamp, date_time, purpose, start_mile, end_mile, distance, fees, party_id) VALUES (\"%d\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%d\")", 9, @"date", @"purpose", @"start", @"end", @"miles", @"tolls", 0]; const char *insert_stmt = [insertSQL UTF8String]; sqlite3_prepare_v2(expenseDB, insert_stmt, -1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_DONE) { // status.text = @"Contact added"; } else { // status.text = @"Failed to add contact"; } sqlite3_finalize(statement); sqlite3_close(expenseDB); } [timestamp release]; } When I run this code, I get a EXC_BAD_ACCESS from the main thread. I thought this error generally showed up when an NSString value was assigned as string value? Any thoughts? A: Don't release timestamp, you're not allocating or retaining it. [timestamp release];
{ "language": "en", "url": "https://stackoverflow.com/questions/7614046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP | imagecopymerge() won't work $dest = imagecreatefromjpeg('image.jpg'); $src = imagecreatefrompng('image2.png'); // Copy and merge imagecopymerge($dest, $src, 50, 50, 0, 0, 30, 30, 75); imagepng($dest, '1.png'); imagedestroy($dest); imagedestroy($src); $dest = 50x50 $src = 30x30 1.png only shows the $dest image with out the $src on top of it. Thanks in advance. A: If dest is 50x50, then you're trying to copy from the bottom right corner, which has 50, 50 as coordinates. +-----------------------+ | | | | | you should copy | | | | | | | | there | | | | | | | | | +-----------------------+-----------------------+ | | | | | you're copying | | | | | | | | | | here | | | | | | | | | +-----------------------+
{ "language": "en", "url": "https://stackoverflow.com/questions/7614048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Append variable to end of each result I am using Codeigniter for my framework and I have went over the documentation and I have not found a solution. Now that I have the the data selected from the database I need to get the distance to be displayed at the end of each record retrieved. Example of json: {"details":[{"country":"United States","_id":"3892","lat":"39.954559","lng":"-82.837608","admin_level_1":"Ohio","locale":"Columbus"}]} This is what it needs to be, keep in mind that distance is not in the database, it is calculated on the fly. Example of json: {"details":[{"country":"United States","_id":"3892","lat":"39.954559","lng":"-82.837608","admin_level_1":"Ohio","locale":"Columbus", "distance": "1.2 Mi"}]} Any ideas on how to get ths distance that is caculcated to be appended to the end of each result? $dbStations->select('lat'); $dbStations->select('lng'); $dbStations->select('_id'); $stations = $dbStations->get('stDetails'); foreach ($stations->result() as $station) { $lat2 = $station->lat; $lng2 = $station->lng; $stId = $station->_id; $distance = $this->distance->gpsdistance($lat1, $lng1, $lat2, $lng2, "M"); if ($distance <= $rad) { //at this point the code has determined that this id is within //the preferred distance. $stationArr[] = $stId; } } $dbStations->select('country, _id, lat, lng, admin_level_1, locale'); $dbStations->where_in('_id', $stationArr); $stations = $dbStations->get('stationDetails'); echo json_encode(array('stations' => $stations->result())); } A: You could try to do everything at once. This query should give you the stations within the radius $rad, according to what is possible to know your table. The variables $lat1 and $lng1 must be defined. $query= "select country, _id, lat, lng, admin_level_1, locale, (acos(sin(radians($lat1)) * sin(radians(lat)) + cos(radians($lat1)) * cos(radians(lat)) * cos(radians($lng1) - radians(lng))) * 6378) as distance from stationDetails where (acos(sin(radians($lat1)) * sin(radians(lat)) + cos(radians($lat1)) * cos(radians(lat)) * cos(radians($lng1) - radians(lng))) * 6378)<=$rad order by distance desc"; echo json_encode($this->db->query($query)->result_array()); Note: The distance is in meters. A: Assuming that $dbStations->get('stDetails') and $dbStations->get('stationDetails') are querying the same table, you could do something like this: $dbStations->select('country, _id, lat, lng, admin_level_1, locale'); $stations = $dbStations->get('stDetails'); $output = array(); foreach ($stations->result() as $station) { $lat2 = $station->lat; $lng2 = $station->lng; $distance = $this->distance->gpsdistance($lat1, $lng1, $lat2, $lng2, "M"); if ($distance <= $rad) { $station->distance = $distance; $output[] = $station; } } echo json_encode($output); I haven't tested this and it may not give you exactly what you want so you may have to tweak it a little bit. The important thing is how I am doing it. Grab all the data at the beginning and and then validate each row. If the row is valid (within a certain distance), add the distance to the array and save it to be outputted. When there are no more rows left, output the valid stations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending booleans over the internet (Windows & Linux) I'm sending information from my server to clients and back again using packed structs (obviously there are a lot more data in the structs) #pragma pack(push, 1) struct other_data_struct { int hp; int wp; char movetype; } struct PlayerStats { int playerID; other_data_struct data; bool friendly; //<-this one messes up how the others are going to be packed on the 2 systems } #pragma pack(pop) That works fine for all fixed sized variables, ints and chars and even other structs. The boolean doesn't work well though when the server is compiled with gcc for Linux and the client is compiled with MSVC for windows... I have thought of making some sort of container (ie. a unsigned char with 8 boolean get/set functions or similar) but it seems as quirky as inelegant. Is there some way to 'pack' structs containing boolean variables exactly the same on Windows and Linux or should I bite the sour apple and use a char for each boolean? A: You could use Google Protocol Buffers instead of your own packed structures. Or you could eschew bool to avoid the incompatibility. If I really had to start from where you are and make it work, I'd make a little program with the structs in it and start experimenting with additional padding fields until I came up with something that looked precisely the same on the two systems. A: Whenever you transfer data between different systems, you should not rely on how these systems represent the data in memory, because the memory representation may vary with the processor architecture, the compiler options, and many other things. You should use some library for serialization instead, since the authors of that library have already put many thoughts into all kinds of problems that you are probably not interested in. A: In the general case, you should not make assumptions about endianess, size of fields, structure packing etc. For general application or library development, it would be bad practice to do this kind of thing. That said, I do this kind of thing fairly often when working on embedded systems where 1) memory (both RAM & executable ROM) is a precious resource, so unnecessary libraries need to be avoided and 2) I know my code will only target one platform, and 3) don't want to take the performance hit of packing/unpacking. Even then, it's probably not a 'best' practice. If you are aware of the risks of doing things this way, I think you answered this one yourself. Define your own type for the boolean if you want to be 100% sure. Also beware that the size of long differs between a 32-bit and 64-bit platform. I usually stick with "stdint.h" types for every numeric primitive, that way you know what size you're dealing with. A: Why don't you just serialize while calling ntohl, htonl, ntohs, htons, etc. This will convert the endian-ness fine - and it's a little safer than what you're doing. You have to worry more about compiler dependent things if you're using structs than if you're using core types of known sizes. The functions put data in network byte order which is the standard for network transport between communicating devices. Other network programmers will understand your code better too for maintenance purposes :) A: You could try bitfields, that way your packed struct contains 'int', but your code uses a more space-efficient representation. I believe bitfields have some awful performance characteristics, so they may not be the way to go if you care more about access time than space usage. A: I'm not clear on what the problem would be. Both Windows and Linux define bool as a one-byte object. Windows does define BOOL as an int, so if you're putting a BOOL on the wire and reading it as a bool (or putting a bool on the wire and reading it as a BOOL) then you're going to have trouble. That's relatively easy to fix. It may be that Windows and Linux define different values for false and true (more likely, they agree that false is 0, but don't agree on the value used for true; even outside of network programming it's possible to have bool variables that are aren't true orfalse, see below). The Standard requires that bools be at least one byte, and a byte has far more than two possible values. Yes, converting your bools to unsigned chars and sending that over the wire will work fine. Note: "bool variables that are aren't true or false": // obviously this code won't show up in anybody's code base char a = 'a'; bool b = *reinterpret_cast<bool*>(&a); switch (b) { case true: std::printf("true\n"); break; case false: std::printf("false\n"); break; default: std::printf("huh?\n"); break; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7614052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Redirect anything to a single php file with url rewriting I'm trying to redirect anything to my index.php file to do myself the redirection. If i use this: #RewriteRule ^(.+)$ index.php?path=$1%{QUERY_STRING} [L] but that's not working because it is "looping" on the rule. This works : <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?path=$1 [QSA,L] </IfModule> but i want to redirect it even if it is an existing file or directory (i thing i will make specials routes for image, js and so on to redirect on them with php without loading any script. In fact, if there were a "no-loop" flag, that would be fine. Anybody knows the solution ? Thanks A: Here is one way to avoid looping: RewriteRule ^(?!index\.php)(.+)$ index.php?path=$1%{QUERY_STRING} [L] Uses negative lookahead (?!) to see if the string includes index.php. If it doesn't, then carry on with the rewrite! A: Replace the two Cond patterns with a check to see if you're hitting index.php: RewriteCond %{REQUEST_URI} !^index.php RewriteRule ^(.*)$ index.php?path=$1 [QSA,L] that will redirect everything, EXCEPT the hits on index.php (to prevent loops).
{ "language": "en", "url": "https://stackoverflow.com/questions/7614054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP XML: Illegal Offset, but it is in array? $dagen = array( 'Mon' => 'Maandag', 'Tue' => 'Dinsdag', 'Wed' => 'Woensdag', 'Thu' => 'Donderdag', 'Fri' => 'Vrijdag', 'Sat' => 'Zaterdag', 'Sun' => 'Zondag' ); foreach ($xml->verwachtingen->verwachting as $verwachting) { $graden = $verwachting->maxtempGRC - $verwachting->mintempGRC; $graden = $graden / 2; $graden = $graden + $verwachting->mintempGRC; $dag = $verwachting->dagvdweek; echo 'Op '. $dagen[$dag] .' wordt het '. $graden .' graden'; } $xml is the XML document loaded using SimpleXMLElement. Now, help me out here. When i echo $dag it displays 'Fri' because it is Friday. So i try to convert the english words of the days to my language (dutch). But it doesn't seem to work, because i get this: Warning: Illegal offset type in C:\data\home\www\awnl-xml\index.php on line 21 Op wordt het 18.5 graden Warning: Illegal offset type in C:\data\home\www\awnl-xml\index.php on line 21 Op wordt het 18 graden Warning: Illegal offset type in C:\data\home\www\awnl-xml\index.php on line 21 ... Does someone know why i get this error? Thanks. A: $dag will be an object, of type SimpleXMLElement. Objects are not allowed to be used for array keys, which is why you are getting that "Illegal offset type" warning. The object must first be cast to a suitable type before being used like that, in your case it should be a string. $dag = (string) $verwachting->dagvdweek;
{ "language": "en", "url": "https://stackoverflow.com/questions/7614058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3 scope undefined method `includes_values` My model has this scope scope :supported, order("name").collect {|m| m.name}.join(", ") and it throws an error NoMethodError: undefined method `includes_values' for "blah, blahblah":String I'm thinking that it's because I'm trying to return a string as an ActiveRecord object, thoughts on how to fix it? Actually I have this code already working in the view but thought it might be better in the model, maybe not? EDIT Moving it into a non-scope class method works def supported order("name").collect {|m| m.name}.join(", ") end Here's a related question that better clarifies the difference between scope vs. self class methods. A: what are you trying to do exactly?, if you want to return a string, use class methods. if you want to define a chainable ARel scope, well i'd always recommend to use class methods too, but some prefer the "explicit" way via scope. def self.supported order('name').to_a * ", " end
{ "language": "en", "url": "https://stackoverflow.com/questions/7614059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find whats the same in two arrays I have two arrays: 1) Array ( [0] => 162 [1] => 163 [2] => 98 [3] => 13 ) 2) Array ( [0] => 22 [1] => 45 [2] => 163 [3] => 80 ) I want to find which values are the same in the these two arrays: So that $thesame = 163 in this example Thanks. A: Try array_intersect() ... http://uk3.php.net/manual/en/function.array-intersect.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7614070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone 7 Button Left-Top from Code How can i use android style gravity, and gavityTop=20px, Left=30px in Windows Phone 7? Button btn = new Button() { Content="newbutton "+i, Margin=new Thickness(20) }; id like something to control my button's left/top margin from the top/left A: If I understood you right, you want something like this: HorizontalAlignment = HoriztontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(30,20,0,0),//left 30, top 20, right 0, bottom 0 P.S.: untested, maybe including typos. don't have a SDK on this PC
{ "language": "en", "url": "https://stackoverflow.com/questions/7614071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A PHP math expression generator? I'm looking for a plugin or function or whatever that can take -sin 3t + xy' - (3t^2 - 5)/(18t) = 21 (negative sine of 3t plus x times y prime minus the quotient of the difference of 3 times t squared and 5 and 18t equals 21) or lim (x -> 0^-) ((3x+8)/x) = +inf (the limit as x approaches 0 from the left of the quotient of the sum of 3x and 8 and x is positive infinity) and generate an image that looks like a mathematical expression or equation. I have found another plugin that uses LaTeX but this seems needlessly complicated. I've seen simpler math expression generators; for example, I do my math homework online by plugging in operations similar to these and it formats the results correctly. Any ideas? A: So you want something to render a nice image for a math formula. I've googled "php formula render" for you and found, so far, this: http://www.phpclasses.org/package/3612-PHP-Render-mathematical-formulas-as-images.html Check it out :) And this: http://www.xm1math.net/phpmathpublisher/ which looks fine. The language (see this guide) doesn't seem to be outstandingly simple but it is fairly easy I think. This other stuff seems not in PHP; but you can try to figure out how it works: http://www.algebra.com/services/rendering/ Seems like you can just use the website itself to render the formulas. It's an outsourced service. If you plan to use it, please have a look at the terms of usage. Hope it helps, man...
{ "language": "en", "url": "https://stackoverflow.com/questions/7614075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I tell what are the ids and classes of a rail html.erb component? So in the tutorial example in Agile Web Development v.4, I was trying to change the css style of the table populated by line_items in the cart menu. So I thought the id should be #cart, but apparently the id should be #store? I don't know how to access the id information of a particular .html.erb block. A: You access the id information in an .html.erb file just as you would in a normal .html file, it is still just basic HTML. You would set the id of your or just like you would in normal HTML. Just set the id property of your HTML element, and add your CSS for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My vb.net code can not Call my VB6 DLL when deployed I have some code that creates a reference to a vb6 dll and Uses that reference to call the object. I am having a problem because in Debug and on my machine it works great. But when i deploy it to the server which is a windows 2008 64 Server it doesn't work. I get this error: "Retrieving the COM class factory for component with CLSID {C259F578-EC04-4C0F-A13B-AA440F13CB73} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))." Here is my code. ClasstoInstantiate = ExportObject If UCase(pRow("TypeVB6").ToString()) = "TRUE" Then classType = Type.GetTypeFromProgID(ClasstoInstantiate, True) Else classType = Type.GetType(ClasstoInstantiate, True) End If Dim o As Object = Activator.CreateInstance(classType) A: VB6 is only going to be able to build 32bit dlls. If your VB.Net code is built for ANY CPU then it is going to run as a 64bit app on a 64bit system and cannot see the 32bit com object. Retarget your assembly from VB.Net to the x86 platform. It should start as a 32 bit process then on the x64 system and be able to see the 32bit com object. Also make sure that you are using the correct regsvr32 command to regsiter your vb6 object. There are 2 different versions on 64bit systems. One in %systemroot%\system32 (64bit version) and %systemroot%\SysWOW64 (32bit). You should use the system32 version on 64bit com objects/dlls and the SysWOW64 version of 32bit com objects/dlls. A: The DLL may be registered on your machine, but not on the server. You can use REGSVR32 to register the DLL manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the fatest way of getting the maximum values element-wised of "n" matrices in Python/Numpy? I had like to know the best fatest/optimized way of getting the maximum values element-wised of "n" matrices in Python/Numpy. For example: import numpy as np matrices=[np.random.random((5,5)) for i in range(10)] # the function np.maximum from numpy only works for two matrices. max_matrix=np.maximum(matrices[0],matrices[1]) max_matrix=np.maximum(*matrices) # <- error How would you overcome this problem? A: Use reduce: reduce(np.maximum, matrices) From the docs: reduce(function, iterable[, initializer]) Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. A: import numpy as np matrices=[np.random.random((5,5)) for i in range(10)] np.max(np.hstack(matrices)) Will give you the maximum value from all of the n matrices. This basically merges all of the matrices in matrices into a single array using np.hstack and then takes the max of that new array. This assumes that all of your matrices have the same number of rows. You can also use np.vstack or np.concatenate to achieve a similar effect. Edit I re-read your question and you might actually want something more like: np.max(np.dstack(matrices),axis=2) This will stack all of your matrices along a third axis and then give you the max along that direction, returning a 5x5 matrix for your case. Edit #2 Here are some timings: In [33]: matrices = [np.random.random((5,5)) for i in range(10)] In [34]: %timeit np.dstack(matrices).max(2) 10000 loops, best of 3: 92.6 us per loop In [35]: %timeit np.array(matrices).max(axis=0) 10000 loops, best of 3: 90.9 us per loop In [36]: %timeit reduce(np.maximum, matrices) 10000 loops, best of 3: 25.8 us per loop and for some larger arrays: In [37]: matrices = [np.random.random((200,200)) for i in range(100)] In [38]: %timeit np.dstack(matrices).max(2) 10 loops, best of 3: 111 ms per loop In [39]: %timeit np.array(matrices).max(axis=0) 1 loops, best of 3: 697 ms per loop In [40]: %timeit reduce(np.maximum, matrices) 100 loops, best of 3: 12.7 ms per loop Steven wins!
{ "language": "en", "url": "https://stackoverflow.com/questions/7614084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android No Break Space - how to? I have a bug, where only on HTC Evo 4g text in EditText shows up with underscores instead of spaces Jack_Johnson, instead of Jack Johnson. The data comes from a server. How do I incorporate \u00A0 or &nbsp into the code below? Will that even fix my problem? editName.setText(recipient.name); A: Try this: editName.setText(Html.fromHtml(recipient.name)); A: So you actually want to unescape the exported from the server escaped special characters? If so, Html.fromHtml won't work, but you can use StringEscapeUtils from the apache commons lang library - http://commons.apache.org/lang/
{ "language": "en", "url": "https://stackoverflow.com/questions/7614085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to update information on a table through a query? I have phone information coming from multiple tables, colating into one query that lists all the pertinant phone information that I regularly need. Now most of this information is coming from a export from out very old phone system. Some of it is coming from tables I created. For instance, I created a table with every phone extension in it, and wether or not that phone extension will be listed in the directory via a query. What I would like to be able to to, is while I am looking at the query, I would like to be able to change that Listed check box, from with-in the query. With out having to open the Listed table, and find the extension that is assciated with the person under that extension. A: I would create a form for this (forms are for editing data, query datasheets) are not for anything other than quick-and-dirty examination of the results of a query), rather than just using a query datasheet, for a query, you can add a lookup field. In the QBE, right click on the field you want and choose PROPERTIES. Select the LOOKUP tab, and change the display type to Combo Box, then define the properties appropriately to display the user-friendly data you want display. A: Sounds like you've got a union query combining the two tables with phone info in it. If that's the case, you won't be able to edit the data via the query alone. See the following link for more details on the circumstances of when you can and can't edit data in a query: http://office.microsoft.com/en-us/access-help/edit-data-in-a-query-HA010097876.aspx If both tables have primary keys (or unique indexes) whose values could differentiate which table they came from --for instance if Table A had all keys that start with the letter 'A' or a '1', and Table B never had keys that start with the same character as Table A's keys-- then you could make a form that, depending on how you programmed it, would pop up an edit box for whichever field you designate, grab the current record's key value, determine which table the key belongs to, and then issue an update command to that table. Personally... that's a bit too convoluted for me, and I'd probably opt for a redesign of some of the tables, possibly involving a periodic import of all pertinent data into one table that could then be updated easily. However, you of course know whether that's feasible in your situation or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Text overflow fades when longer than container and scrolls across on hover I had a jquery/css question. I was wondering if you knew how to make a link in a list item (one that is longer that its container) not wrap to a new line and instead stay on 1 single line and fade/cut off the overflowing rest of the link. Also, the link would "ticker" (right to left) across to show the remainder of the text when the user rolled over it (on hover). Also, the text doesn't have to be necessarily "faded out" but could just be cut off a few pixels from the edge of the container. .list_wrapper li { display: block; height: 23px; margin: 0px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .list_wrapper li:last-child { margin-bottom: 5px; } .list_wrapper li:nth-child(odd) { background:#FAFAFA; border-top: 1px solid #FAFAFA; border-bottom: 1px solid #FAFAFA; } .list_wrapper li:nth-child(even) { background:#FFFFFF; border-top: 1px solid #FFF; border-bottom: 1px solid #FFF; } .list_wrapper li:hover { cursor: default; background: #F3F3F3; border-top: 1px solid #E9E9E9; border-bottom: 1px solid #E9E9E9; } .list_wrapper a { color: #145F92; font: 400 11px/23px "Lucida Grande", tahoma, verdana, arial, sans-serif; margin-left: 13px; -webkit-transition: color .3s ease; -moz-transition: color .3s ease; -ms-transition: color .3s ease; transition: color .3s ease; } .list_wrapper a:hover { text-decoration: underline; } .article_list { float:left; display: block; width:100%; } Have any ideas how I could achieve this? Wanted look: http://i1132.photobucket.com/albums/m563/carrako/link_face.jpg A: To "cut off" the text, use the following CSS: .list_wrapper li { overflow: hidden; } .list_wrapper li a { white-space: nowrap; position: relative; // Needed for the animation! } Then, for the "ticker"-animation, use an animation-framework, e.g. jQuery, to "move" the <a> element (animate the CSS left-property) when it's hovered; but only, if offsetWidth of the element exceeds the width of the parent node (otherwise we don't need to scroll). On mouseout, we stop the animation and move the element back. Example, using jQuery: $('.list_wrapper li a').mouseover( function() { if( this.offsetWidth > this.parentNode.offsetWidth ) { $(this).animate({'left': '-'+(this.offsetWidth)+'px'}, 5000, function(){this.style.left='0px';}); } } ).mouseout( function() { $(this).stop(); this.style.left = '0px'; } ); For this JavaScript-Snippet to work, you would need to embed the jQuery-framework to your website. The snippet should be executed when the page finished loading: either you put it at the very end of your HTML (just before the </body>), or you trigger it window.onload. For a running example, see here: http://jsfiddle.net/z7V7d/2/ Edit: Actually, I don't like doing the homework for others; but I had fun doing it so I guess it's okay. I updated the code to your wishes. ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7614090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Caching Images, JS and CSS in Apache using deflate I am currently caching my CSS, JS and images using deflate in my Apache configuration. Here's my code: AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript Now when I check my header I see: Host www.domain.com User-Agent Mozilla/5.0 (X11; Linux i686; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language en-us,en;q=0.5 Accept-Encoding gzip, deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Connection keep-alive If-Modified-Since Fri, 30 Sep 2011 01:05:01 GMT If-None-Match "124741af-1c4b9-4ae1136f3f9d0" Cache-Control max-age=0 Everything looks good, the Accept-Encoding is gzip, deflate which is what I want but now I see the Cache-Control is max-age=0. Will that defeat the purpose of caching using deflate? Is that mean it's only caching for 1 day and the next day it won't cache it or it will have to reload it? Note: My images rarely change, my CSS and JS change once a week. A: These are 2 independent things: mod_deflate and mod_expires Here's some articles you will find interesting: http://developer.yahoo.com/performance/rules.html LiveHttpHeaders: which cache-control info is right
{ "language": "en", "url": "https://stackoverflow.com/questions/7614107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Java 1.5 Enum: Why can't I use 'findBy' with 1.5 enums? Given the code below, import java.util.Date; import java.util.HashMap; import java.util.Map; public enum SearchDataTypes { FIELD_DATATYPE_TEXT(String.class,"_t"), FIELD_DATATYPE_INT(Integer.class,"_i"), FIELD_DATATYPE_LONG(Long.class,"_l"), FIELD_DATATYPE_FLOAT(Float.class,"_f"), FIELD_DATATYPE_DOUBLE(Double.class, "_d" ), FIELD_DATATYPE_DATE(Date.class,"_dt"); SearchDataTypes(final Class<?> clazz, final String affix) { this.affix = affix; this.clazz = clazz; getAffixMap().put(affix, this); getClassMap().put(clazz, this); } public String getFieldName(String objectFieldName) { return objectFieldName+affix; } public String getObjectFieldName(String FieldName) { int len = FieldName.length(); len -= this.affix.length(); return FieldName.substring(0, len); } public static SearchDataTypes findByAffix(String affix) { SearchDataTypes obj = getAffixMap().get(affix); assert obj != null; return obj; } public static SearchDataTypes findByClass(Class<?> clazz) { SearchDataTypes obj = getClassMap().get(clazz); assert obj != null; return obj; } private String affix; private Class<?> clazz; private static Map<Class<?>, SearchDataTypes> classMap = new HashMap<Class<?>, SearchDataTypes>(); private static Map<String, SearchDataTypes> affixMap = new HashMap<String, SearchDataTypes>(); private static Map<Class<?>, SearchDataTypes> getClassMap() { return classMap; } private static Map<String, SearchDataTypes> getAffixMap() { return affixMap; } } The enum class is not getting instantiated (using the enum throws NoClassDefFoundError) because the there is NullPointerException during initialization. I assume that the JVM is thinking either map is null. But why?? How else can I implement a finder for enums? I prefer not to use java.util.EnumMap class mainly because I want to better understand the innerworking of enums. thank you A: Think of the enum constants as public static final members of the Java class. Like all static members, they are initialized in source order. So the constants are being initialized before the maps, thus you'll get the null pointer exception when referencing the map in the constructors, because the map hasn't been initialized yet. Though not possible with java syntax, the simple solution would be to declare the maps before the enums--but since that's not possible, the next best thing is to just initialize the maps in a static block after the constants: e.g. public enum SearchDataTypes { ... FIELD_DATATYPE_DATE(Date.class,"_dt"); private static final Map<String,SearchDataTypes> affixMap = new HashMap<String,SearchDataType>(); private static final Map<Class<?>, SearchDataTypes> classMap = new HashMap<Class<?>, SearchDataTypes>() static { for (SearchDataType value : values()) { map.put(value.affix, value); map.put(value.clazz, value); } } SearchDataTypes(final Class<?> clazz, final String affix) { this.affix = affix; ... } A: The instances are getting constructed before the static initialization of the rest of the enum. Use "getters" for the maps that will construct them if they are null. Because it's all happening within static initialization of the enum class, it's intrinsically thread-safe - you don't have to use a synchronize block.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using the pow()-method in Java I am writing a program in Java in which the user is supposed input an integer, n. My program should then create an array where the entries are [1.25^0], [1.25^1], . . ., [1.25^n]. In order to make this work I have attempted to use the pow()-method. My code for creating the array is as follows: for (int i = 0; i < n; i++) { functionG[i] = pow(1.25, n); } This is, however, giving me the error message: "the method pow(double, int) is unidentified for the type Functions" (Functions is the name of my class). Does anyone know how I can fix this? I am pretty sure I am on the right track, I just need to get the method to work properly. Any help will be greatly appreciated! A: Sure, you just need to call Math.pow(...), as it's a static method in the Math class: for (int i = 0; i < n; i++) { functionG[i] = Math.pow(1.25, i); } Note that I've changed it to use i rather than n as the second argument. You could also get your original code to compile using: import static java.lang.Math.pow; in the import statements at the top of your code. See the Java Language Specification, section 7.5.3 for details of how this works. A: Use Math.pow(double, double), or statically import pow as such: import static java.lang.Math.pow; A: that would be because pow is a static method in the Math(java.lang.Math) class. You have to use Math.pow instead. A: You can solve this problem, as others have noted, with importing of Math.pow or explicitly calling it. However, seeing as you're always using integers as your powers, Math.pow() is a fairly expensive call compared to straight multiplication. I would suggest a method like so. It may give you slightly different results, but it should be sufficient. /** * Make a double[] that gives you each power of the original * value up to a highestPow. */ double[] expandedPow(double orig, int highestPow) { if(highestPow < 0) return new double[0]; if(highestPow == 0) return new double[] { 0.0 }; double[] arr = new double[highestPow + 1]; arr[0] = 0.0; arr[1] = orig; for(int n = 2; n < arr.length; n++) { arr[n] = arr[n-1] * orig; } return arr; } A: A solution I made that may help you understand a few things more clearly. // Make it ready for the loop, no point calling Math.pow() every loop - expensive import static java.lang.Math.pow; public class MyPattern { public void showTree(int treeDepth) { // Create local method fields, we try to avoid doing this in loops int depth = treeDepth; String result = "", sysOutput = ""; // Look the depth of the tree for( int rowPosition = 0 ; rowPosition < depth ; rowPosition++ ) { // Reset the row result each time result = ""; // Build up to the centre (Handle the unique centre value here) for( int columnPosition = 0 ; columnPosition <= rowPosition ; columnPosition++ ) result += (int) pow(2, columnPosition) + " "; // Build up from after the centre (reason we -1 from the rowPosition) for ( int columnPosition = rowPosition - 1 ; columnPosition >= 0 ; columnPosition-- ) result += (int) pow(2, columnPosition) + " "; // Add the row result to the main output string sysOutput += result.trim() + "\n"; } // Output only once, much more efficient System.out.print( sysOutput ); } // Good practice to put the main method at the end of the methods public static void main(String[] args) { // Good practice to Create Object of itself MyPattern test = new MyPattern(); // Call method on object (very clear this way) test.showTree(5); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7614109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to copy files to a Linux server from ASP.NET with permissions problems? My question is more about how to overcome a permissions problem. There is an Apache application that creates a new folder each time a new employee is added. I am working on an application that can copy files into each of these folders. Unfortunately, the folders are created with write permissions only for the owner (Apache Daemon). I am currently trying to accomplish this using Samba. I don't have access to the Apache application, but have full access to change anything on the server. However, I can't write into these directories even when connecting as root through Samba. Is there a way to do this? A: I had removed the read only = Yes option, not realizing that it was still the default. Added writeable = Yes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring LDAP Template Usage Please take a look at the test class below. I am trying to do an LDAP search with Spring LDAP Template. I am able to search and produce a list of entries corresponding to the search criteria without the Spring LDAP template by using the DirContext as shown in the method searchWithoutTemplate(). But when I use a LdapTemplate, I end up with a NPE as shown further below. I am sure I must be missing something. Can someone help please? import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.LdapName; import org.springframework.ldap.core.AttributesMapper; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.DefaultDirObjectFactory; import org.springframework.ldap.core.support.LdapContextSource; public class LDAPSearchTest { //bind params static String url="ldap://<IP>:<PORT>"; static String userName="cn=Directory Manager"; static String password="password123"; static String bindDN="dc=XXX,dc=com"; //search params static String base = "ou=StandardUser,ou=XXXCustomers,ou=People,dc=XXX,dc=com"; static String filter = "(objectClass=*)"; static String[] attributeFilter = { "cn", "uid" }; static SearchControls sc = new SearchControls(); public static void main(String[] args) throws Exception { // sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(attributeFilter); searchWithTemplate(); //NPE //searchWithoutTemplate(); //works fine } public static void searchWithTemplate() throws Exception { DefaultDirObjectFactory factory = new DefaultDirObjectFactory(); LdapContextSource cs = new LdapContextSource(); cs.setUrl(url); cs.setUserDn(userName); cs.setPassword(password); cs.setBase(bindDN); cs.setDirObjectFactory(factory.getClass ()); LdapTemplate template = new LdapTemplate(cs); template.afterPropertiesSet(); System.out.println((template.search(new LdapName(base), filter, sc, new AttributesMapper() { public Object mapFromAttributes(Attributes attrs) throws NamingException { System.out.println(attrs); return attrs.get("uid").get(); } }))); } public static void searchWithoutTemplate() throws NamingException{ Hashtable env = new Hashtable(11); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, url); //env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userName); env.put(Context.SECURITY_CREDENTIALS, password); DirContext dctx = new InitialDirContext(env); NamingEnumeration results = dctx.search(base, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); System.out.println(attrs); Attribute attr = attrs.get("uid"); } dctx.close(); } } Exception is: Exception in thread "main" java.lang.NullPointerException at org.springframework.ldap.core.support.AbstractContextSource.getReadOnlyContext(AbstractContextSource.java:125) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:287) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:237) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:588) at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:546) at LDAPSearchTest.searchWithTemplate(LDAPSearchTest.java:47) at LDAPSearchTest.main(LDAPSearchTest.java:33) I am using Spring 2.5.6 and Spring LDAP 1.3.0 A: A quick scan showed that it's the authenticationSource field of AbstractContextSource that is the culprit. That file includes the following comment on the afterPropertiesSet() method: /** * Checks that all necessary data is set and that there is no compatibility * issues, after which the instance is initialized. Note that you need to * call this method explicitly after setting all desired properties if using * the class outside of a Spring Context. */ public void afterPropertiesSet() throws Exception { ... } That method then goes on to create an appropriate authenticationSource if you haven't provided one. As your test code above is most definitely not running within a Spring context, and you haven't explicitly set an authenticationSource, I think you need to edit your code as follows: ... cs.setDirObjectFactory(factory.getClass ()); // Allow Spring to configure the Context Source: cs.afterPropertiesSet(); LdapTemplate template = new LdapTemplate(cs);
{ "language": "en", "url": "https://stackoverflow.com/questions/7614114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery livesearch and rails I'm trying to implement some live search function on my index view. I found this plugin http://www.mikemerritt.me/blog/livefilter-1-3-jquery-plugin/ but can't adapt to rails. I'm trying to reproduce the demo but can't make it work. can someone explain how to adapt the demo to rails (3.1) environment. Thanks A: you could also use jQuery-UIs autocomplete. there are a ton of questions / tutorials and i think even gems to feed this autocomplete from a rails backend.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xmlbeans.xmlexception. illegal XML character 0x0 I create an xml document in C# by converting a string to bytes via System.Text.UTF8Encoding(). I then send this to my java program for xmlbeans to parse via a TCP connection. No matter what i try, i am getting this error: org.apache.xmlbeans.XmlException: error: Illegal XML character: 0x0 org.apache.xmlbeans.impl.piccolo.io.IllegalCharException: Illegal XML character: 0x0 I have attempted to sanitize the the string on the C# side, yet it does not find any instance of 0x0. I have looped through and output each byte in the byte[] that i receive on the java side, and there is absolutely nothing that has a 0x0. This is my java side code: public void parseBytes(byte[] bytes, int length, String source) { System.out.println("***************BmsDrawingGatewayParser - ParseBytes " + length); String foundData = null; try { foundData = new String(bytes, 0, length, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } switch (readState) { case STATE_NEW_MSG: // if contains the if (foundData.contains(startMessageTag)) { if (foundData.contains(endMessageTag)) { byteStream.write(bytes, 0, length); parseXml(byteStream.toByteArray()); if (byteStream.size() > 0) { byteStream.reset(); } } else { readState = DrawingDeviceParserState.STATE_READING_MSG; } } else { System.out.println("Couldn't find start tag"); System.out.println(foundData); } break; case STATE_READING_MSG: byteStream.write(bytes, byteStream.size(), length); if (foundData.contains(endMessageTag)) { System.out.println("Now going to parse"); //parseXml(xmlString.toString()); parseXml(byteStream.toByteArray()); byteStream.reset(); readState = DrawingDeviceParserState.STATE_NEW_MSG; } else { System.out.println("Couldn't find end tag"); System.out.println(foundData); } break; } } private void parseXml(byte[] xmlData) { System.out.println(xmlData); //EventDocument.Factory.parse ByteArrayInputStream sid = new ByteArrayInputStream(xmlData); try { EventDocument eventDoc = EventDocument.Factory.parse(sid); if (eventDoc.validate()) { System.out.println("Document is valid"); } else { System.out.println("Document is INVALID"); } EventDocument.Event myEvent = eventDoc.getEvent(); EventDocument.Event.Detail[] myDetailArray = myEvent.getDetailArray(); //myDetailArray[0]. //BmsDrawingDocument drawingDoc = myEvent.getDetail(); System.out.println("MY UID: " + myEvent.getUid()); } catch(Exception xmlException) { System.out.println(xmlException.toString()); xmlException.printStackTrace(); } } Does anyone know what i might be doing wrong? Is there more information that i can provide? A: It happened to me and found out to be corrupted lib files, so replace the libs with uncorrupted or old copy. It solved my issue. A: public void parseBytes(byte[] bytes, int length, String source) { String foundData = null; try { foundData = new String(bytes, 0, length, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } switch (readState) { case STATE_NEW_MSG: // if contains the if (foundData.contains(startMessageTag)) { if (foundData.contains(endMessageTag)) { byteStream.write(bytes, 0, length); parseXml(byteStream.toByteArray()); if (byteStream.size() > 0) { byteStream.reset(); } } else { readState = DrawingDeviceParserState.STATE_READING_MSG; } } else { System.out.println("Couldn't find start tag"); System.out.println(foundData); } break; case STATE_READING_MSG: byteStream.write(bytes, byteStream.size(), length); if (foundData.contains(endMessageTag)) { System.out.println("Now going to parse"); //parseXml(xmlString.toString()); parseXml(byteStream.toByteArray()); byteStream.reset(); readState = DrawingDeviceParserState.STATE_NEW_MSG; } else { System.out.println("Couldn't find end tag"); System.out.println(foundData); } break; } } private void parseXml(byte[] xmlData) { System.out.println(xmlData); //EventDocument.Factory.parse ByteArrayInputStream sid = new ByteArrayInputStream(xmlData); try { EventDocument eventDoc = EventDocument.Factory.parse(sid); if (eventDoc.validate()) { System.out.println("Document is valid"); } else { System.out.println("Document is INVALID"); } EventDocument.Event myEvent = eventDoc.getEvent(); EventDocument.Event.Detail[] myDetailArray = myEvent.getDetailArray(); //myDetailArray[0]. //BmsDrawingDocument drawingDoc = myEvent.getDetail(); System.out.println("MY UID: " + myEvent.getUid()); } catch(Exception xmlException) { System.out.println(xmlException.toString()); xmlException.printStackTrace(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7614118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why can't I place a variable into my array? Is it possible to have a variable in an array as a value in PHP. For example: 'arraykey' => "$varname", It does not seem to work and I can't find any info about this anywhere. Maybe because its just not possible? Any insight is appreciated. Thanks. A: Yes you can, but not using double quotes. It will cause the value of the variable to be inserted in the string instead. Use this: $cow = "Mooo"; $varname = 'cow'; $a = array('arrayitem' => '$varname'); $var = $a['arrayitem']; echo $$var; Or rather: don't use it. It won't make your code very readable. But it's possible, as you can see. :) A: $array[] = $var; $array['item'] = $var; Dont use $variables inside "" and ''s A: It is entirely possible, but you do not need the quotes around the variable name. $x = 1; $y = 2; $z = "pasta"; $myVars = array( 'x' => $x, 'y' => $y, 'z' => $z ); print_r($myVars); A: Do you mean: $array['item'] = $varname; There are lots of use-cases in the spec: http://php.net/manual/en/language.types.array.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7614119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XSD to MySQL Schema I need to convert an XML to a MySQL DB Schema. I have been able to generate the XSD from the XML. Now i want to use the XSD to generate the DB schema in MySQL or PostgreSQL. Can anyone tell me how can i do this or point to any tools which i can use for this? A: There is a command-line tool called XSD2DB, that generates database from xsd-files, available at sourceforge. For more info: please refer to this existing question How can I create database tables from XSD files?
{ "language": "en", "url": "https://stackoverflow.com/questions/7614121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: flex4 1195 error when calling a function (not get or set) I have a class called S3Uploader which extends Sprite, which has a private function init, which looks sometihng like this: private function init(signatureUrl:String, prefixPath:String, fileSizeLimit:Number, queueSizeLimit:Number, fileTypes:String, fileTypeDescs:String, selectMultipleFiles:Boolean, buttonWidth:Number, buttonHeight:Number, buttonUpUrl:String, buttonDownUrl:String, buttonOverUrl:String ):void { //do stuff } In my flex app, I am trying to display the sprite and call the init function when the app is loaded. my code so far is this: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" initialize="init();"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ import S3Uploader; function init() { var s3upload:S3Uploader = new S3Uploader(); s3upload.init('/s3_uploads2.xml', '', 524288000, 100, '*.*', 'All Files', true, 100, 30, '/images/upload-button.png', '/images/upload-button.png', '/images/upload-button.png'); uploader.addChild(s3upload); } ]]> </fx:Script> <s:SpriteVisualElement id="uploader" /> </s:Application> however, on the line where i call s3upload.init, i get a 1195 error saying "1195: Attempted access of inaccessible method init through a reference with static type S3Uploader." When i looked up this error, it seems like almost everyone getting this was trying to call a function with set or get. However, I am not doing this and i have no idea why i am getting this error. Does anyone know what I am doing wrong? A: You should learn the basics of OOP. You cannot call private functions from not within function owner objects. Mark it as public.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: doing a show() does not let gui update until resize window doing a show() does not let gui update until resize window. I have a window that I hide for a while,(has to be over 30 min. or maybe after screensaver kicks in) then when I try to do a show and the gui pops up but it does not update. I am making correct updates to the gui, but they aren't seen until i physically resize the window. I'm thinking somehow the gui doesn't focus anymore. If I don't let it sit idle for a long time it never has a problem. Is there something I can do to force it to gain focus when I do the show()? thank you very much A: To answer your question directly: You can also do a Focus() to make the window focus (in theory anyway). But I don't think this is your problem. Have you been able to reproduce this behavior on multiple computers?
{ "language": "en", "url": "https://stackoverflow.com/questions/7614132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compiling CUDA exampels with Visual Studio 2010 express I am trying to set up a CUDA dev env on a Windows 7 32bit computer with Visual Studio 2010 Express. But I keep getting the following error when I try to compile the bandwithTest project that follow with the CUDA SDK! 1>------ Build started: Project: cutil, Configuration: Release Win32 ------ 2>------ Build started: Project: shrUtils, Configuration: Release Win32 ------ 2>LINK : fatal error LNK1104: cannot open file 'lib\Win32\shrUtils32.lib' 1>LINK : fatal error LNK1104: cannot open file 'lib\Win32\\cutil32.dll' 3>------ Build started: Project: bandwidthTest, Configuration: Release Win32 ------ 3>LINK : fatal error LNK1104: cannot open file '../../bin/win32/Release//bandwidthTest.exe' ========== Build: 0 succeeded, 3 failed, 0 up-to-date, 0 skipped ========== A: Follow this guide: How to Run CUDA In Visual Studio 2010 A: Check my answer to this question: cuda sdk example bandwidthTest - build failed If they are already built then check if they are correctly listed in the additional library directories in the solution properties, linking tab.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery library include order causes error I have a problem with jQuery UI Dialog - it is not closing when I click the X button. I have detected that the problem goes away if I change the order of my javascript includes: If I include files in the following order then the problem appears: <script src="../../Scripts/jquery-1.6.4.min.js" type="text/javascript"></script> <script src="../../Scripts/jquery-ui-1.8.7.min.js" type="text/javascript"></script> <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script> If I include files in the following order then the problem disappears: <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script> <script src="../../Scripts/jquery-1.6.4.min.js" type="text/javascript"></script> <script src="../../Scripts/jquery-ui-1.8.7.min.js" type="text/javascript"></script> This seems really strange - I thought that you should include the core jQuery stuff right at the top of the file? Presumably jquery.validate.min.js has dependencies upon the core jquery libs. But, this issue would suggest that jquery.validate.min.js has some sort of conflict with the core? Anyone know the best way of dealing with this? Apologies that this may appear to be a dupe of jQuery UI Dialog will not close - I wanted to raise a new issue as it seems to be a slightly different problem to the one I originally raised. Thanks very much.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When using Phonegap, can we deploy our sqlite db with the application and access it from within the application? I am building out an app that will be used primarily by BB OS5. I am considering Phonegap, and I wanted to find out if we can deploy our sqlite db with the application and access it from within the application? If so, is there a size limit on the database? and how is the performance? A: PhoneGap Database API requires BlackBerry WebWorks (OS 6.0 and higher) But I would also like to point you to a toolkit that you may find useful in building a database backed webapp. Supporting Gears using HTML5 in BlackBerry WebWorks applications The JavaScript® toolkit provides the following HTML5 interfaces as a simple layer on top of the Gears API’s currently available in BlackBerry Device Software 5.0: * *Geolocation *Timer *Database *Worker *XMLHttpRequest A: @Ray Vahey, phonegap support OS 5.0+ not complete but in part... You can use Phonegap + gears in your app in order to use storage on OS 5, for OS 6+ you can use the Phonegap API: http://docs.phonegap.com/en/1.1.0/phonegap_storage_storage.md.html#Storage
{ "language": "en", "url": "https://stackoverflow.com/questions/7614143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mediaelement volume control is invisible on IE8 When using mediaelement.js on http://hanselminutes.com, the volume button is invisible on IE8. It seems that perhaps it's being covered up by the other audio controls being too wide? Oddly, if you click in the area that it should be, it's kind of there, although too far left. The volume icon never shows up. A: I know nothing about mediaelement.js but if you add the following to the bottom of your hanselminutes.css it appears to fix it: .mejs-time-rail{ max-width: 370px; } .mejs-time-total { max-width: 348px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7614147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to merge multiple dataviews into one? I have three dataviews (dataview1, dataview2, and dataview3). These are of type System.Data.DataView, and all three have the same columns. Is there an easy way to merge them into one, so I have one dataview with rows from dataview1, followed by dataview2, and then dataview3? A: DataTable datatableMerge = dataview1.ToTable(); datatableMerge.Merge(dataview2.ToTable()); The result includes only the rows according to the the DataViews' Filters. A: Dim dataview1 As DataView = new DataView() Dim dataview2 As DataView = new DataView() '' given the tables are not null you can then merge like this dataview1.Table.Merge(dataview2.Table)
{ "language": "en", "url": "https://stackoverflow.com/questions/7614150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Convert iPhone unique identifier to integer I have made a web service that gets an integer as a unique identifier for a Phone. Later, i realised that an iPhone UID is an NSstring in that format: 5DE31FA12-XXXXX-XXXXX-XXXXXXX. So i would like to convert this value to an integer. Here is the way i get the UID in a NSString format. CFUUIDRef theUUID = CFUUIDCreate(NULL); CFStringRef string = CFUUIDCreateString(NULL, theUUID); CFRelease(theUUID); NSString *theUID = (NSString *)string; How can i convert NSString *theUID into an integer value, so as to send it to the webservice? EDIT: As CocoaFu correctly mentioned , it is impossible to fit that value in an int. Could I somehow convert it to an NSString with a format like "ddddddddddddddddddddddddddd" (where d = 0-9) so as to hash it and then send it? It is impossible to change the webservice now. A: The largest integer is 8 bytes or 64 bits. The UUID you show has 26 hex characters which is 104 bits. It just won't fit in an integer. Use the string. CFUUIDCreate returns a string with 32 hex characters, that is 128 bits or 16 bytes. Ignore the '-' characters, they are just for human readability. Here is an example from CFUUIDCreate: BDFC3FE6-3A5E-48C0-B18D-E42B8E275428 A: UDID won't fit in an int. The format you have listed is what the simulator gives you. Device UDID is 40-characters long alpha-numeric.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ReaderWriteLockSlim or Lock I m using ConcurrentBag to store object in run time. At some point I need to empty the bag and store the bag content to a list. This is what i do: IList<T> list = new List<T>(); lock (bag) { T pixel; while (bag.TryTake(out pixel)) { list.Add(pixel); } } My Question is with synchronization, As far as I read in the book lock is faster than others synchronization methods. Source -- http://www.albahari.com/threading/part2.aspx. Performance is my second concern, I d like to know if I can use ReaderWriterLockSlim at this point. What would be the benefit of using ReaderWriterLockSlim? The reason is that, I dont want this operation to block incoming requests. If yes, Should I use Upgradable Lock? Any ideas ? Comments? A: I'm not sure why you're using the lock. The whole idea behind ConcurrentBag is that it's concurrent. Unless you're just trying to prevent some other thread from taking things or adding things to the bag while you're emptying it. Re-reading your question, I'm pretty sure you don't want to synchronize access here at all. ConcurrentBag allows multiple threads to Take and Add, without you having to do any explicit synchronization. If you lock the bag, then no other thread can add or remove things while your code is running. Assuming, of course, that you protect every other access to the bag with a lock. And once you do that, you've completely defeated the purpose of having a lock-free concurrent data structure. Your data structure has become a poorly-performing list that's controlled by a lock. Same thing if you use a reader-writer lock. You'd have to synchronize every access. You don't need to add any explicit synchronization in this case. Ditch the lock. A: Lock is great when threads will do a lot of operations in a row(bursty - low contention) RWSlim is great when you have a lot more read locks than write locks(read heavy - high read contention) Lockless is great when you need a multiple readers and/or writers all working at the same time(mix of read/write - lots of contention)
{ "language": "en", "url": "https://stackoverflow.com/questions/7614156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JSF2 error [org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage] Error Rendering View[//WEB-INF/*.xhtml]: java.lang.NullPointerException I have an error in Jboss 7.0.2 Arc, JSP 2.1(Myfaces), Richfaces 4, this is my web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- Log4j configurated in spring!!!, before any code directly calling log4j (calling through commons logging doesn't count)? Jing Xue --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j-webapp.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>1000</param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>myWebapp-instance-root</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <display-name>richfaces-application</display-name> <!-- Listener para crear el Spring Container compartido por todos los Servlets y Filters (WebApplication Context)--> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:META-INF/spring/spring-master.xml WEB-INF/spring/spring-security.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- For JSF --> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <!-- Jboss not use it bundle integrated JSF --> <context-param> <param-name>org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL</param-name> <param-value>true</param-value> </context-param> <!-- Facelets, tell JSF to use Facelets --> <context-param> <param-name>org.ajax4jsf.VIEW_HANDLERS</param-name> <param-value>com.sun.facelets.FaceletViewHandler</param-value> </context-param> <!-- Spring JavaServiceFaces framework ApacheMyfaces --> <listener> <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class> </listener> <!-- Spring Security, for all --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- RichFaces Framework --> <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>blueSky</param-value> </context-param> <!-- For control of skins --> <context-param> <param-name>org.richfaces.CONTROL_SKINNING_CLASSES</param-name> <param-value>enable</param-value> </context-param> <!-- Servlets for JSF--> <servlet> <servlet-name>faces</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>faces</servlet-name> <url-pattern>*.xhtml</url-pattern> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <!-- Servlet for Dispatcher of flows --> <servlet> <servlet-name>transportes</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/spring/transportes-servlet.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>transportes</servlet-name> <url-pattern>/flows/*</url-pattern> </servlet-mapping> <!-- Servlet register for SpringFaces, SpringJavaScript --> <servlet> <servlet-name>resources</servlet-name> <servlet-class>org.springframework.js.resource.ResourceServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>resources</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping> <!-- Page That control SpringWeb --> <welcome-file-list> <welcome-file>/WEB-INF/flows/inscripcion/login.xhtml</welcome-file> </welcome-file-list> </web-app> and the error: 12:58:15,480 INFO [org.apache.myfaces.util.ExternalSpecifications] (http--127.0.0.1-8080-2) MyFaces Unified EL support enabled 12:58:15,596 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/projvehimerc]] (http--127.0.0.1-8080-2) No state saving method defined, assuming default server state saving 12:58:15,737 SEVERE [org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage] (http--127.0.0.1-8080-2) Error Rendering View[//WEB-INF/flows/inscripcion/login.xhtml]: java.lang.NullPointerException at org.springframework.faces.webflow.FlowViewStateManager.saveView(FlowViewStateManager.java:181) [spring-faces-2.3.0.RELEASE.jar:] at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1554) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:281) [myfaces-impl-2.1.1.jar:] at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:59) [myfaces-api-2.1.1.jar:] at org.springframework.faces.webflow.FlowViewHandler.renderView(FlowViewHandler.java:99) [spring-faces-2.3.0.RELEASE.jar:] at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:85) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239) [myfaces-impl-2.1.1.jar:] at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191) [myfaces-api-2.1.1.jar:] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:90) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) [spring-web-3.0.5.RELEASE.jar:] at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [spring-web-3.0.5.RELEASE.jar:] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:139) [jboss-as-web-7.0.2.Final.jar:7.0.2.Final] at org.jboss.as.web.NamingValve.invoke(NamingValve.java:57) [jboss-as-web-7.0.2.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:154) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:667) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:952) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at java.lang.Thread.run(Thread.java:662) [:1.6.0_25] 12:58:15,766 SEVERE [org.apache.myfaces.renderkit.ErrorPageWriter] (http--127.0.0.1-8080-2) An exception occurred: javax.faces.FacesException: java.lang.NullPointerException at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.wrap(ExceptionHandlerImpl.java:241) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:156) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:258) [myfaces-impl-2.1.1.jar:] at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191) [myfaces-api-2.1.1.jar:] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:90) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149) [spring-security-web-3.0.2.RELEASE.jar:] at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) [spring-web-3.0.5.RELEASE.jar:] at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [spring-web-3.0.5.RELEASE.jar:] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:139) [jboss-as-web-7.0.2.Final.jar:7.0.2.Final] at org.jboss.as.web.NamingValve.invoke(NamingValve.java:57) [jboss-as-web-7.0.2.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:154) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:667) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:952) [jbossweb-7.0.1.Final.jar:7.0.2.Final] at java.lang.Thread.run(Thread.java:662) [:1.6.0_25] Caused by: java.lang.NullPointerException at org.springframework.faces.webflow.FlowViewStateManager.saveView(FlowViewStateManager.java:181) [spring-faces-2.3.0.RELEASE.jar:] at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1554) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:281) [myfaces-impl-2.1.1.jar:] at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:59) [myfaces-api-2.1.1.jar:] at org.springframework.faces.webflow.FlowViewHandler.renderView(FlowViewHandler.java:99) [spring-faces-2.3.0.RELEASE.jar:] at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:85) [myfaces-impl-2.1.1.jar:] at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239) [myfaces-impl-2.1.1.jar:] ... 44 more A: Here's the root cause (the bottommost part of the trace): Caused by: java.lang.NullPointerException at org.springframework.faces.webflow.FlowViewStateManager.saveView(FlowViewStateManager.java:181) [spring-faces-2.3.0.RELEASE.jar:] The 1st Google hit on this line leads us to SWF bug report 1461. This is apparently an acknowledged bug in SWF 2.3.0. According to the linked bug report, it's been fixed in SWF 2.3.1. So, upgrading should do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do ruby exceptions cause mutices to unlock? Recently, I have been working with Ruby's threads, and have uncovered a slightly unexpected behaviour. In a critical section, calling raise causes the mutex to release. I could expect this of the synchronize method, with its block, but it also seems to happen when lock and unlock are called separately. For example, the code below outputs: $ ruby testmutex.rb x sync y sync ...where I'd expect y to be blocked until the heat death of the universe. m = Mutex.new x = Thread.new() do begin m.lock puts "x sync" sleep 5 raise "x err" sleep 5 m.unlock rescue end end y = Thread.new() do sleep 0.5 m.lock puts "y sync" m.unlock end x.join y.join Why is the y thread allowed to run even though the m.unlock in the x thread is never executed? A: Note that if you remove the raise and the unlock from x the behavior is the same. So you have a situation where the x thread locks the mutex, and then the thread ends, and the mutex is unlocked. m = Mutex.new Thread.new{ m.lock; p m.locked? }.join #=> true p m.locked? #=> false Thus we see that the situation is unrelated to raise. Because you have a begin/rescue block around your raise, you just exit the x thread 5 seconds earlier than you would have otherwise. Presumably the interpreter keeps tracks of any mutexes locked by a thread and automatically and intentionally unlocks them when the thread dies. (I cannot back this up with source-code inspection, however. This is just a guess, based on behavior.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7614163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MySQL query uses too much CPU I use the following query to find users that I need to send daily reminders based on their settings and timezone. It works but turned up that it uses about 50% CPU and its really heavy even when I add Limit 0,100. (It even causes phpMyAdmin to crash or something) Users table: 3000 records, Posts table: 12000+ records, Settings table: 3000 records, Reminders table: 80000 records (Keeps user_id and date to prevent duplicates) SELECT u.`id`, u.`fullname`, u.`email`, u.`hash`, s.`timezone` FROM `users` u LEFT JOIN `reminders` rm ON rm.`user_id` = u.`id` AND rm.`date` = CURDATE() LEFT JOIN `settings` s ON s.`user_id` = u.`id` LEFT JOIN `posts` p ON p.`user_id` = u.`id` AND p.`date` = DATE(CONVERT_TZ(UTC_TIMESTAMP, 'UTC', s.`timezone`)) WHERE HOUR(CONVERT_TZ(UTC_TIMESTAMP, 'UTC', s.`timezone`)) = s.`notify_hour` AND s.`notify` = 1 AND u.`active` = 1 AND rm.`id` IS NULL AND p.`id` IS NULL GROUP BY u.`id` LIMIT 0,100 I run this query every 10 minutes and I'm sending reminders through sendgrid.com SMTP server. Can you please help me optimize this query so that it doesn't use this much resource? Thank you (and sorry for my English) A: Do you have the fields properly indexed? here is a suggestion: Try to index the user_id field on all the tables it should make it faster. Also the conversion of dates is eating up the cpu time, you should store the dates in UTC format in your database this way you will avoid a huge overhead
{ "language": "en", "url": "https://stackoverflow.com/questions/7614166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is jQuery.data() modifying the HTML5 data-x attribute value? I have just encountered some very disturbing behavior in jQuery 1.6.2 that I hope someone can explain. Given the following markup... <div id="test" data-test=" 01">Test</div> Can someone tell me why accessing the attribute through .data() causes it to be parsed to an int? var t = $("#test").data("test"); alert(t); // shows "1" t = $("#test").attr("data-test"); alert(t); // shows " 01" Of course I have proof on jsFiddle of this behavior. A: From the doc for data(key): Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. Since your example string CAN be converted to a number, it is. Edit: As Joseph points out, this only applies when reading data straight from the element, like you're doing in this example. If you could set it first (i.e. data(key,value) before reading), then the behavior disappears. The getter, when reading from the actual DOM element, performs type coercion. A: jQuery people say: As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification. Every attempt is made to convert the string (html5 data attribute value) to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. From this page: http://api.jquery.com/data/ A: To add to Paul Equis's answer, If you want to access it as a string, use the .attr() method. var t = $("#test").attr("data-test"); Edit: here's a demonstration showing one of the benefits of jQuery interpreting the data attribute. http://jsfiddle.net/FzmWa/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7614167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: I am unable to add a reference to System.Windows.Media in my .net 3.5 project I'm using VS 2008, with .net 3.5. I need access to System.Windows.Media.Color, but when I try to "Add Reference...", System.Windows.Media is not listed. I'm not sure where to go next since the MSDN documentation seems to think I should have access to it by default, and doesn't give any additional information on how to include it. Just adding "using System.Windows.Media" turns up an error saying I'm probably missing a reference. A: See this link: http://msdn.microsoft.com/en-us/library/system.windows.media.color.aspx It's in the PresentationCore.dll. (Look at the very top of the page). Namespaces aren't always in individual .dll files, a lot of times they are bundled as a larger dll like this. A: Add PresentationCore, which you should find under the .NET tab of Add Reference dialog box.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can dates and random numbers be used for evil in Javascript? The ADsafe subset of Javascript prohibits the use of certain things that are not safe for guest code to have access to, such as eval, window, this, with, and so on. For some reason, it also prohibits the Date object and Math.random: Date and Math.random Access to these sources of non-determinism is restricted in order to make it easier to determine how widgets behave. I still don't understand how using Date or Math.random will accomodate malevolence. Can you come up with a code example where using either Date or Math.random is necessary to do something evil? A: I don't think anyone would consider them evil per se. However the crucial part of that quote is: easier to determine how widgets behave Obviously Math.random() introduces indeterminism so you can never be sure how the code would behave upon each run. What is not obvious is that Date brings similar indeterminism. If your code is somehow dependant on current date it will (again obviously) work differently in some conditions. I guess it's not surprising that these two methods/objects are non-functional, in other words each run may return different result irrespective to arguments. In general there are some ways to fight with this indeterminism. Storing initial random seed to reproduce the exact same series of random numbers (not possible in JavaScript) and supplying client code with sort of TimeProvider abstraction rather than letting it create Dates everywhere. A: According to a slideshow posted by Douglas Crockford: ADsafe does not allow access to Date or random This is to allow human evaluation of ad content with confidence that behavior will not change in the future. This is for ad quality and contractual compliance, not for security. A: According to their website, they don't include Date or Math.random to make it easier to determine how third party code will behave. The problem here is Math.random (using Date you can make a psuedo-random number as well)- they want to know how third party code will behave and can't know that if the third party code is allowed access to random numbers. By themselves, Date and Math.random shouldn't pose security threats. A: At a minimum they allow you to write loops that can not be shown to be non-terminating, but may run for a very long time. The quote you exhibit seem to suggest that a certain amount of static analysis is being done (or is at least contemplated), and these features make it much harder. Mind you these restrictions aren't enough to actually prevent you from writing difficult-to-statically-analyze code. A: I agree with you that it's a strange limitation. The justification that using date or random would make difficult to predict widget behavior is of course nonsense. For example implement a simple counter, compute the sha-1 of the current number and then act depending on the result. I don't think it's any easier to predict what the widget will do in the long term compared to a random or date... short of running it forever. The history of math has shown that trying to classify functions on how they compute their value is a path that leads nowhere... the only sensible solution is classifying them depending on the actual results (black box approach).
{ "language": "en", "url": "https://stackoverflow.com/questions/7614174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to show a div with initial width equal min-width in IE but can expand as necessary? I want to have a div to have an initial width equal to a min-width say 800px and expand in width as elements inside grow in width. I did a <div style="min-width: 800px".. /> but in IE the div starts with a width less than 800px, sum of widths of inner elements. How can this be done for IE? I can't use width:800px because elements inside can't expand beyond 800px. I use jQuery. Addition: I am using IE8. I just created a new page with an outer div with just min-width and inner div with a width. The outer width used the whole screen width. Not same issue but related. I will have to find out why my page behaves differently. A: How about using CSS expressions: div { display: inline-block; width: inherit; /* min-width for good browsers */ min-width: 800px; /* CSS expression for older IE */ width: expression(document.body.clientWidth < 800? "800px": "auto"); } Example here: min-width CSS expression hack. The yellow background is the outer div the dotted line is the inner element so the div keeps size properties of it's child :) A: In IE6 min-width, max-width, min-height and max-height properties does not work. You can create a conditional stylesheet and use width for IE6 and min-width for the other browsers. A: You can target IE6 by using underscore hack. Example: <div style="min-width:800px;_width:800px;">...</div> For max-width/height, you have to use IE-proprietary expression() property: http://www.svendtofte.com/code/max_width_in_ie/
{ "language": "en", "url": "https://stackoverflow.com/questions/7614175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customizing the installation Wizard in .net My application involves lot of questions to be asked to the installer, the visual studio allows only a predefined set of controls for the installation wizard, Is there a way to add lot more controls to our Installation Wizard. can you help me out here? A: vdproj's are getting deprecated and are no longer supported. Your best bet (which will also address your concern here) is to migrate to Wix. It's a steep learning curve and some of the simplest things have become completely non-trivial, but sadly, the other two options I've pursued haven't worked out: * *InstallShield LE - it freezes my computer and Visual Studio consistently and doesn't build randomly. Just plain doesn't work well. *NSIS - MSIs are a requirement these days for corporate network deployment. That said, Wix is extremely powerful and customizable, so it does have its positives. A: I know this trick works for adding web controls to class library projects, but I'm not sure if it will work for you can do this for installation projects. It's definitely worth a shot though! First, back up your project. Open the project file in an editor, and replace the projecttypeguids setting with the following: <projecttypeguids>{349c5851-65df-11da-9384-00065b846f21};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</projecttypeguids> Here's a link that explains it in more detail: http://www.aaronblake.co.uk/blog/2009/09/28/how-to-add-web-user-controls-to-a-class-library-project/ You might want to check out this article too: http://blogs.microsoft.co.il/blogs/shair/archive/2011/01/15/extending-visual-studio-setup-project-part-1.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7614177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress and Zend Framework I can't get my head around integrating these two in the way I would like to. I have a wordpress installation running a website. I also include the ZF via a plugin so that I can use the codebase. However, I would like to also have the ability to utilise Zend Controllers in the same way I do on my normal Zend Applications... for example, I may want a form to submit to a zend controller so I can handle it there.... How can I do this? I'm just after a little pointer here because I've read all the previous questions on here and none answer my question specifically. A: Are you using this? http://www.leftjoin.net/2011/03/integrating-zend-framework-with-wordpress/ I'm not sure about this but you would need to use Zend_Controller without the URL structure, I don't know if that's easy to reroute...
{ "language": "en", "url": "https://stackoverflow.com/questions/7614180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't (&array)[i] take the address of the ith element? Consider the following code int tab2[2]; tab2[0]=5; tab2[1]=3; std::cout << tab2[1] << std::endl; std::cout << (&tab2)[1] << std::endl; As I have read in other topics, an array can decay to pointer at its first element. Then why doesn't the [] doesn't work the same for tab2 and &tab2 in the above code? What is different? A: It's already "converted" as a pointer. You can use the [] notation with arrays or pointers... (&tab2) means you get the address of your array... In a pointer perspective, it's a pointer to a pointer ( ** ). So you are trying to convert a variable (which is an array) as a pointer. Ok, but then you try to access the [1] element, which of course does not exist, as your pointer points to your array's address... Such a notation would expect a second array. A: This expression: (&tab2)[1] Gets you a pointer to an array of 2 ints. Then uses array syntax on that pointer-to-an-array to get you the 1st 2 element int array after tab2. So you have in memory tab2 0 1 // index into tab2 5 3 // values You get a pointer to the array 0 1 &tab2 -> 5 3 Then you go 1 array of 2 ints past tab2 0 1 2 3 &tab2 -> 5 3 ? ? /|\ (&tab2)[1] A: When you use (&tab2), you are retrieving the address of your array. Your statement itself answers your question. Had you used (*(&tab2)), you would have got what you were expecting as output - 3. A: What you've done by adding address-of (&) to tab2 is given yourself the memory address of the tab2 pointer, or a pointer to a pointer (int**). So logically, yes, indexing it makes sense. However, &tab2 is not the same as tab2. &tab2 points to the pointer itsefl, while tab2 points to the array. By indexing &tab2 with 1, you've told it to look at the next element in sequence, which doesn't exist (or it does exist, but belongs to another variable). Had you indexed it with 0, this would have been fine as you would be looking at the "root" of the memory sequence. Indexing just tab2 is fine as well obviously, because it points to an array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can JProfiler tell me how long queries are taking? Wouldn't it be nice if I could drill down into the JProfiler CPU View, and find a percentage of time running a certain query against the database? Does anyone know if this is possible? A: The call tree in JProfiler shows JDBC queries with the default settings: If this is not the case, open the session settings, go to the probe settings, select the JDBC probe and ensure that "Enabled", "Record on startup" and "Annotate JDBC calls in call tree" are selected: Another way to look at JDBC query strings is the "hot spot" view of the JDBC probe:
{ "language": "en", "url": "https://stackoverflow.com/questions/7614189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: wp7: how to create image button and bind template to ImageSource dependency property I am trying to create a silverlight imagebutton control. the xaml and code-behind will follow, but my problem is that I get an 'unspecified error' when i try a TemplateBinding to the image's source property. I'm hoping that someone can help me preserve my last shreds of sanity and last few scraps of hair on my head. XAML: <Grid x:Name="LayoutRoot"> <Button x:Name="btn" Click="Cancel_Click" Margin="0,0,10,10" Width="{Binding ImageWidth}" Height="{Binding ImageHeight}" > <Button.Template> <ControlTemplate TargetType="Button"> <Grid Background="Transparent"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"/> <VisualState x:Name="Pressed"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground"> <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="33" Margin="{StaticResource PhoneTouchTargetOverhang}"> <Image x:Name="image" Source="{TemplateBinding IconSource}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" /> </Border> </Grid> </ControlTemplate> </Button.Template> </Button> </Grid> </UserControl> Code Behind: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace sltest.controls { public partial class ImageButtonControl : UserControl { public ImageButtonControl() { InitializeComponent(); } private void Cancel_Click(object sender, RoutedEventArgs e) { } public double ImageWidth { get; set; } public double ImageHeight { get; set; } public static readonly DependencyProperty IconSourceProperty = DependencyProperty.Register("IconSource", typeof(ImageSource), typeof(ImageButtonControl), null); public ImageSource IconSource { get { return base.GetValue(IconSourceProperty) as ImageSource; } set { base.SetValue(IconSourceProperty, value); } } } } A: I'm using the following implementation which contains additional functionality to display text, but you can exclude it: ImageTextButtonControl class using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SecureBox.Controls { public class ImageTextButtonControl: Button { /// /// /// public static readonly DependencyProperty ImageHeightProperty = DependencyProperty.Register("ImageHeight", typeof(double), typeof(ImageTextButtonControl), null); public double ImageHeight { get { return (double)GetValue(ImageHeightProperty); } set { SetValue(ImageHeightProperty, value); } } /// /// /// public static readonly DependencyProperty ImageWidthProperty = DependencyProperty.Register("ImageWidth", typeof(double), typeof(ImageTextButtonControl), null); public double ImageWidth { get { return (double)GetValue(ImageWidthProperty); } set { SetValue(ImageWidthProperty, value); } } /// /// /// public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(BitmapImage), typeof(ImageTextButtonControl), null); public BitmapImage ImageSource { get { return (BitmapImage)GetValue(ImageSourceProperty); } set { SetValue(ImageSourceProperty, value); } } /// /// /// public static readonly DependencyProperty TextMarginProperty = DependencyProperty.Register("TextMargin", typeof(Thickness), typeof(ImageTextButtonControl), null); public Thickness TextMargin { get { return (Thickness)GetValue(TextMarginProperty); } set { SetValue(TextMarginProperty, value); } } /// /// /// public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ImageTextButtonControl), null); public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public ImageTextButtonControl() { DefaultStyleKey = typeof(ImageTextButtonControl); } } } Themes\generic.xaml contains: <Style TargetType="local:ImageTextButtonControl"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="local:ImageTextButtonControl"> <Grid Margin="{StaticResource PhoneTouchTargetOverhang}" toolkit:TiltEffect.IsTiltEnabled="True"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Border BorderBrush="White" BorderThickness="0" Opacity="0.9" > <Image Grid.Column="0" Width="{TemplateBinding ImageWidth}" Height="{TemplateBinding ImageHeight}" Source="{TemplateBinding ImageSource}" VerticalAlignment="Top" /> </Border> <TextBlock Grid.Column="1" Margin="{TemplateBinding TextMargin}" Text="{TemplateBinding Text}" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="{TemplateBinding FontSize}" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> Example of usage: <local:ImageTextButtonControl ImageSource="/ImagePath/YourImage.png" Text="YourText" FontSize="50" ImageHeight="128" ImageWidth="128" TextMargin="20,0,0,0"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <Command:EventToCommand Command="{Binding GoTo}" CommandParameterValue="YourCommandParameter" /> </i:EventTrigger> </i:Interaction.Triggers> Note: * *I've inherited the control from Button control. This allows me to subscribe to Click event using MVVMLight framework *Xaml code is located in special place: Themes\generic.xaml file I guess you can try to check whether these notes can fix your the issue in your code or use my one instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pointer to Array of Strings Is Fine in Function but not outside I'm working with PCRE library for C on a linux x86_64 system, though I don't think the PCRE is to blame for the issue I'm having. Basically I have an array of character arrays that holds the result from the PCRE check. I used typedef to keep it clean typedef char *pcreres[30]; And the function that handles checking for matches, etc int getmatch(const char *pattern, char *source, pcreres *res){ const char *error; int erroffset, rc,i; int ovector[30]; pcre *re = pcre_compile(pattern,PCRE_CASELESS | PCRE_MULTILINE, &error,&erroffset,NULL); rc=pcre_exec(re,NULL,source,(int)strlen(source),0,0,ovector,30); if(rc<0){ return -1; } if(rc==0) rc=10; for(i=0;i<rc;i++){ char *substring_start=source+ovector[2*i]; int substring_length=ovector[2*i+1] - ovector[2*i]; *res[i] = strndup(substring_start,substring_length); } return rc; } The code I'm testing has 2 results and if I put a printf("%s",*res[1]) in the function just before the return I get the expected result. However in my main function where I call getmatch() from I have this code; pcreres to; mres=getmatch(PATTERN_TO,email,&to); printf("%s",to[1]); I get an empty string, however to[0] outputs the correct result. I'm somewhat a newbie at C coding, but I'm completely lost at where to go from here. Any help is appreciated! A: Operator precedence. the [] operator is evaluated before the * operator. In your function try this: (*res)[i] = strndup(substring_start,substring_length);
{ "language": "en", "url": "https://stackoverflow.com/questions/7614204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Linear gradients in SVG without defs I can use linear gradient in SVG with defs-section like: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <linearGradient id="myLinearGradient1" x1="0%" y1="0%" x2="0%" y2="100%" spreadMethod="pad"> <stop offset="0%" stop-color="#00cc00" stop-opacity="1"/> <stop offset="100%" stop-color="#006600" stop-opacity="1"/> </linearGradient> </defs> <rect x="0" y="0" width="100" height="100" style="fill:url(#myLinearGradient1)" /> </svg> Can I use linear gradient without defs-section? I find something like this: <rect style="fill:lineargradient(foo)"> A: <defs> is only needed for structuring purposes, the elements in it are not displayed, but since a gradient can only be visible when applied to a shape or another element, you can define it in any place of the document. But you still have to stick to the correct syntax: <rect style="fill:url(#myLinearGradient1)" ... /> A: Yes you can indeed have a gradient without needing to have a defs element; you simply put the gradient element anywhere else in the code instead, for example like this: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <linearGradient id="myLinearGradient1" x1="0%" y1="0%" x2="0%" y2="100%" spreadMethod="pad"> <stop offset="0%" stop-color="#00cc00" stop-opacity="1"/> <stop offset="100%" stop-color="#006600" stop-opacity="1"/> </linearGradient> <rect x="0" y="0" width="100" height="100" style="fill:url(#myLinearGradient1)" /> </svg>
{ "language": "en", "url": "https://stackoverflow.com/questions/7614209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Downloaded files disappearing on update I have an app that downloads several pdfs and images. It all work perfectly fine, I store information of those files in core data. My problem comes when I send out updates of the app, all the information in core data is transferred to the new version correctly but the files are nowhere to be found. I guess I can write a routine to run when users update the app and download the files all over again. I just believe there is a better way to go by preserving the files. Has anybody experience on this? A: You could store the files in the Documents dir, there they will be not deleted unless you remove the app from the device.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Managing conflict in schema.rb created by Git operation I created a migration, ran rake db:migrate, which bumped my db/schema.rb version number. Then I did a git fetch origin master and saw that there were changes from my team members. So I did a git stash and a git rebase FETCH_HEAD, followed by a git stash pop. This resulted in a conflict in db/schema.rb over the version number. Upstream>>> ActiveRecord::Schema.define(:version => 20110930179257) do =========== ActiveRecord::Schema.define(:version => 20110930161932) do <<<Stashed I think the appropriate fix would be to manually increment the version number to something higher than the upstream. Is this sensible, or bad news? Thanks, Max A: If your current database has the correct schema, you should: * *Run pending migrations (if any) rake db:migrate *Overwrite your schema.rb from your current database schema rake db:schema:dump *And commit A: According to this answer, a conflict is guaranteed. The user has to to manually merge, and set the version as the higher of the two. A: Here's what I do when merging master into my feature branch fails over conflicts in db/schema.rb: $ git merge --abort $ git checkout master $ rake db:drop db:create db:migrate $ git checkout -- db/schema.rb $ git checkout my_feature_branch $ rake db:migrate $ git add db/schema.rb $ git commit -m 'Updated schema' $ git merge master A: When I find myself with this conflict, I simply migrate the database. Whether there are pending migrations or not, the conflict will be corrected. A: tldr Accept the Upstream version and run rake db:migrate as you'd normally do. why is that the way to go Don't worry about the migrations you've created (which are below Upstream version 20110930179257). ActiveRecord uses a table schema_migrations where it puts all of the migrations that have been run. If your migrations aren't on the list but in db/migrate directory, then ActiveRecord will run them. Here's the table so you can visualise it better: It's tempting to think that it's actually this line: ActiveRecord::Schema.define(:version => 20110930179257) that defines latest migration run, so no migrations with version below it are going to be run. This is fortunately not true. Rails will run any migrations that are in db/migrate folder and not yet in the schema_migrations table. A: ~/bin/update-schema-rb: #!/usr/bin/env bash git co master bin/rake db:reset db:seed git co - bin/rake db:migrate A: An option is to have a manual version script which is additive only. There you want conflicts. Schema is something that will bite you hard if you don't keep on top of it. So once bitten, twice shy, I don't mind keeping schema and lookup info (list of customer types) with an additive only change management scheme. A: I feel the best approach is to do rake db:drop db:create db:migrate to regenerate schema using migrations that exist only on the current branch. That way migrations from other branches won't leak into your schema file and give you headache later - in case if you switch branches a lot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: JSON to Javascript object literal notation? The methods of the dynamic Google Graph API want Javascript object literals as their argument, but I only have the data as JSON. What do I do? Is there any way that I could convert my JSON to an object literal? The format they want is here: http://code.google.com/intl/sv-SE/apis/chart/interactive/docs/reference.html#DataTable I PHP, and also jQuery front end. I would appreciate front end or back end solutions. In the back end, I actually have the data in associative arrays so I can do anything with it there. A: JSON is designed as a subset of Javascript object literal notation. Any* valid JSON code is already valid to interpret as a JavaScript literal. * Technically, a few rare whitespace characters are treated differently, but this is relevant to almost nobody.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: webpage response using PHP I have a form structure webpage written in PHP. When information is submitted it gives a unique ID. Now I want this unique ID to be used in a file. For Example: $input = "man.id: ".$id; where $id is the response from the webpage. $input is present in the same PHP file. A: Here's an example of how to write (append) text to a file with PHP: $id = GetID(); // GetID can return a value stored on disk that gets incremented $input = "man.id: " . $id; $logfile = "mypage.log"; $file = fopen($logfile, 'a'); // Try to open the file in Append mode if($file) // If the file was opened successfully, i.e. if $file is a valid file pointer { flock($file, LOCK_EX); // Exclusive lock fwrite($file, $input); fclose($file); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7614221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Is BID installed as part of SQL Server of Visual Studio or either? Does Busienss Intelligence Development Studio (BIDS), part of the Visual Studio IDE, come with both SQL Serevr 2008 R2 Developers Edition and also as part of Visual Studio 2008 Developer's Edition? A: BIDS is included with SQL Server. It is not part of the regular Visual Studio install. You can get BIDS by installing just the client tools from SQL Server without having to do a full install of the product.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery Ajax Content Not loading I am pulling my hair out trying to figure this out. I am just doing a simple ajax load on some content however the content is not loading all other functions are working but the content does not show. Any help would be greatly appreciated. Its probably something super simple too but.... Here's the code Main page HTML <ul><li id="content1">click this</li></ul> <div id="ajaxContent"></div> External HTML <div id="content1"><p>some content here</p></div> ...and the JS $(function() { var $items = $('ul li'); $items.bind('click',loadContent); function loadContent() { var toLoad = 'content.html'+' #'+ $(this).attr('id'); var $content = $('#ajaxContent'); $content.append('<span id="load">LOADING...</span>'); $('#load').fadeIn('normal'); $content.load(toLoad,'',showNewContent) function showNewContent() { $content.fadeIn(1000,hideLoader); } function hideLoader() { $('#load').fadeOut('normal'); } } }): A: Your problem is that you are declaring your functions showNewContent and hideLoader inside of your loadContent function. That means that you can't reference them until your loadContent function has been called (but it needs to use them itself). Move the functions showNewContent and hideLoader outside of the loadContent function and it should work. A: The hash (the part from the #) is not sent to the server. If this is the only thing that changes, the browser will not see it as a new url and will not load the page. Change the url to content.html?id=1 or something, and make sure you handle this GET parameter correctly on the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Passing list/array between JSP pages I'm trying to pass a List between two JSP pages that I have. This is a list of objects that is of a class that I wrote. How do I pass this list between JSP pages? request.setAttribute seems to work for strings, but not anything else. And, if this cannot be easily done with a list, I can convert the list to an array and pass it that way, no problem. A: The first thing is that a very bad design will lead to such questions as passing lists between different JSP pages. The "nip the evil at the bud" will be to create a separate java class which contains the list and initializes it, then you can access the list at as many jsp pages as you want. But incase you really want to do, you can put the list in the session. request.getSession().setAttribute("list",myListObject); Then on the other page you can get List<MyType>myListObject=(List<MyType>) request.getSession().getAttribute("list"); And you should clear the list from the session after you do not require it, request.getSession().removeAttribute("list"); A: The simplest answer is: it depends. If you have e.g. one.jsp and you call redirect to second.jsp - you can use request scope <c:set var="list" value="${yourListObject}" scope="request" /> If you have one.jsp and few pages later you want to display your list, then you should use session scope: <c:set var="list" value="${yourListObject}" scope="session" /> to display your list on second.jsp: ${list} yourListObject you can replace by * *<%= Java expression %> *use bean which has this list and just pass the reference here
{ "language": "en", "url": "https://stackoverflow.com/questions/7614239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Give access to an Android service without giving the sources I am creating an Android service that my own app will use, but I also want it to be available to external apps. The service is declared using AIDL files. I have two separate projects, one for the service, one for the application. In Eclipse I reference the service project in the application project to have access to the generated classes from the AIDL files, which works fine. But now, I want to give access to the service to other apps, how do I do it? Should I distribute the AIDL files? The class files? Each project will have to copy my AIDL files into their eclipse project? What if I change the signature of a method of the service? Thanks A: If you expect third parties to access your service you must provide some form of interface for them. This would be AIDL in this case. So you will have to distribute it and service consumers will have to use it. Most likely they will have to include it in their project. If you change signature, they will have to update their code. This is a typical problem in similar cases - welcome to the club! You would need to version your interface definition in some form and then either block incompatible clients or provide some conversion layer so they access your new service using old interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Thread.Start not working I am using the functions of the following class to invoke a messagebox. I am using thread.Start method to show the messagebox. The problem is it is not reaching to the respective function when thread.Start is called. Am i missing anything? class MessageManager { string _message; public MessageManager(string message) { _message = message; } public void ShowBigMessage() { Thread thread = new Thread(DisplayBigMessage); thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA thread.Start(); // thread.Join(); } public void ShowNormalMessage() { Thread thread = new Thread(DisplayNormalMessage); thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA thread.Start(); //thread.Join(); } private void DisplayBigMessage() { BigAppMessage appMessage = new BigAppMessage(_message); appMessage.Show(); } private void DisplayNormalMessage() { AppMessage appMessage = new AppMessage(_message); appMessage.ShowDialog(); } } This is called inside a thread/delegate as below. I added this code into my program becuase it was raising The calling thread must be STA, because many UI components require this. exception before MessageManager message = new MessageManager("This is a test message."); message.ShowBigMessage(); public partial class BigAppMessage : Window { public BigAppMessage(String message) { InitializeComponent(); myControl.setMessage(message); // mycontrol is just user control with a //label on it } } A: The Show() method requires a message loop. Fix: private void DisplayBigMessage() { Application.Run(new BigAppMessage(_message)); } There's already a message loop built into the ShowDialog() method. Using a thread to just display a window has no advantages, only problems. A: In visual studio go to Debug->Exceptions and check the "thrown" box next to CLR exceptions. this will tell you where your problem is. Probably its a cross thread issue since you would ordinarily only interact with the UI on the UI thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: preg_replace REGEX I wanted some help regarding REGEX. I have the following in a string variable after scraping from a website. 16:50 to 17:50 OOPS LAB : Scheduled Class : Shikha Jain : E1-0LA4&amp;nbsp;Download Course materials 15:45 to 16:45 OOPS LAB : Scheduled Class : Shikha Jain : E1-0LA4&amp;nbsp;Download Course materials 14:40 to 15:40 FR - III : Scheduled Class : Ravi Shankar Kumar : E3-218&amp;nbsp;Download Course materials &amp;nbsp; What i want to do is, get rid of the "&nbsp;Download Course materials" part. I tried the str_replace and preg_replace but they all kept failing to replace successfully. Please help. Thanks. A: Note that the ampersand has been replaced by an entity: &amp;nbsp; (thanks Viktor) : $new_string = str_replace('&amp;nbsp;Download Course materials', '', $your_string) Should do the job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert long to System.Int64 throws error? I got a strange error that got me buffeled: I have a function ..uhm... something like this: void someFunctionTakingALong( long ID) { var table = new DataTable(); table .Columns.Add(new DataColumn("RID", Type.GetType("System.Int64"))); table.Rows.Add(ID); //<-- throws err } throws this error: System.ArgumentException: Input string was not in a correct format.Couldn't store in RID Column. Expected type is Int64. ---> System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt) at System.String.System.IConvertible.ToInt64(IFormatProvider provider) at System.Data.Common.Int64Storage.Set(Int32 record, Object value) at System.Data.DataColumn.set_Item(Int32 record, Object value) --- End of inner exception stack trace --- This happens in production, and I don't have logs to see what value of ID is actually passed to the function... but even so.. having the parameter a long should AT LEAST guarantee that ID is a long ... right? So why is this throwing? What values could ID have that are not convertible to a int64 ? EDIT: Here is the actual source : Trhowing column is PropValueID public void AddRule(int PropID, long PropValueID, int type, string Data) { if (!m_HasRule) { m_Rules = new DataTable(); m_Rules.Columns.Add(new DataColumn("RID", Type.GetType("System.Int32"))); m_Rules.Columns.Add(new DataColumn("PropID", Type.GetType("System.Int32"))); m_Rules.Columns.Add(new DataColumn("PropValueID", Type.GetType("System.Int64"))); //m_Rules.Columns.Add(new DataColumn("PropValue", Type.GetType("System.String"))); m_Rules.Columns.Add(new DataColumn("Type", Type.GetType("System.Int32"))); m_Rules.Columns.Add(new DataColumn("Data", Type.GetType("System.String"))); m_HasRule = true; } ToStringSB = null; if (type<2) // a "Is/Not specified property" { if (string.IsNullOrEmpty(Data)) //is specified (0,1) m_Rules.Rows.Add(m_RID, PropID, 0, type, ""); //<<-- here we pass 0 (int32) instead of long.. could this be it? Stack says this is not the line throwing else //is equal to/is not equal to(2,3) m_Rules.Rows.Add(m_RID, PropID, PropValueID,3-type, Data); }else if ((type > 3) && (type < 6)) // a "like/not like" rule { // "Like" or "not like" DATA .. no value ID is provided m_Rules.Rows.Add(m_RID, PropID, PropValueID, type, Data); //<<-- Stack says it throws here } else // a greater/lesser rule { m_Rules.Rows.Add(m_RID, PropID, PropValueID, type, Data); } } There is a suspect line where we pass on literal 0 (an int) but that's not the line number where the stack says it throws. A: Unable to reproduce - this works fine for me: using System; using System.Data; class Test { static void Main() { long x = 10; var table = new DataTable(); table.Columns.Add(new DataColumn("RID", Type.GetType("System.Int64"))); table.Rows.Add(x); } } Note that you can get rid of the call to Type.GetType() by using typeof(long). It looks like for some reason it's converting the value to a string and back, which is really strange... are you sure it's from just that code? If you can come up with a short but complete example like mine but which fails, that would really help. A: Are you sure you are passing a long to the DataRowCollection.Add method? The code snippet you posted doesn't help much, can you post the actual code? The System.Data namespace code pre-dates generics, so there's a lot of boxing and unboxing going on, and I think there's no way around it. From the stack trace we can see that the code is trying to set the value of a DataRow column from an Object value, and that this results in a String parse to Int64. This leads me to believe that the call to table.Rows.Add is not receiving a long value for the RID column. Unless the boxing messed up the long value and ended up as an empty String, which although is not impossible is extremely improbable. By that I mean, I didn't code the .Net Framework, I don't know what does it do internally, in general we trust that Microsoft did a good job, but in all code there's the possibility of error. So either the bug is in your code or in Microsoft's code. The odds are against you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get CMake to create a dll and its matching lib file? I'm using CMake to create a shared library via Visual Studio 2010. The solution outputs a dll file, but not a matching lib file. How do I tell CMake to generate the lib file so I can link other projects to the dll? A: First of all check that you have at least one exported symbol in your shared library. Visual Studio does not generate the .lib file if dll does not exports symbols. Next, check your cmake files - probably you have set CMAKE_ARCHIVE_OUTPUT_DIRECTORY variable or ARCHIVE_OUTPUT_DIRECTORY property of the shared library target. If these variable/property is set then Visual Studio will output .lib files into the different directory specified by that variable/property. (There also can be configuration-specific versions like ARCHIVE_OUTPUT_DIRECTORY_Release.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7614286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Hibernate: enforcing unique data members I am having an issue working with Hibernate and enforcing unique data members when inserting. Here are my abridged Entity objects: Workflow: @Entity public class Workflow { private long wfId; private Set<Service> services; /** Getter/Setter for wfId */ ... @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "workflow_services", joinColumns = @JoinColumn(name = "workflow_id"), inverseJoinColumns = @JoinColumn(name = "service_id")) public Set<Service> getServices() { return services; } Service: @Entity public class Service { private long serviceId; private String serviceName; /** Getter/Setter for serviceId */ ... @Column(unique=true,nullable=false) public String getServiceName() { return serviceName; } @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "service_operations", joinColumns = { @JoinColumn(name = "serviceId") }, inverseJoinColumns = { @JoinColumn(name = "operationId") }) public Set<Operation> getOperations() { return operations; } Operation: @Entity public class Operation { private long operationId; private String operationName; /** Getter/Setter for operationId */ @Column(unique=true,nullable=false) public String getOperationName() { return operationName; } My issue: Although I have stated in each object what is SUPPOSED to be unique, it is not being enforced. Inside my Workflow object, I maintain a Set of Services. Each Service maintains a list of Operations. When a Workflow is saved to the database, I need it to check if the Services and Operations it currently uses are already in the database, if so, associate itself with those rows. Currently I am getting repeats within my Services and Operations tables. I have tried using the annotation: @Table( uniqueConstraints) but have had zero luck with it. Any help would be greatly appreciated A: The unique or uniqueConstraints attributes are not used to enforce the uniqueness in the DB, but create the correct DDL if you generate it from hibernate (and for documentation too, but that's arguable). If you declare something as unique in hibernate, you should declare it too in the DB, by adding a constraint. Taking this to the extreme, you can create a mapping in which the PK is not unique in the DB, and hibernate will throw an exception when it tries to load one item by calling Session.load, and sudently finding that there are 2 items. A: Inside my Workflow object, I maintain a Set of Services. Each Service maintains a list of Operations. When a Workflow is saved to the database, I need it to check if the Services and Operations it currently uses are already in the database, if so, associate itself with those rows. I think you're asking Hibernate to detect duplicate objects when you add them to the Set, yes? In other words, when you put an object in the Set, you want Hibernate to go look for a persistent version of that object and use it. However, this is not the way Hibernate works. If you want it to "reuse" an object, you have to look it up yourself and then use it. Hibernate doesn't do this. I would suggest having a helper method on a DAO-like object that takes the parent and the child object, and then does the lookup and setting for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Run a MATLAB script from Windows DOS prompt I am trying to run a Matlab script from Windows command prompt but I can't execute it sometimes. The script runs fine when manually launched. Matlab version is 2011a and Windows is Server 2003 SP2. Details: Script mytask.m is located inside say E:\Production\Project. This is SAVED on Matlab's path. When I place mytask.m inside bin folder, it executes fine by the command: `C:\Program Files\MATLAB\R2011a\bin>matlab -r mytask` If you delete it and try to access it at its original location, the script doesn't run although Matlab editor window is launched: `C:\Program Files\MATLAB\R2011a\bin>matlab -r "E:\Production\Project\mytask" Any suggestions please? Thanks. A: The syntax for matlab -r is matlab -r "statement" In other words, you need to provide some executable commands as the statement. For example: matlab -r "run E:\Production\Project\mytask" However, it seems that matlab does not load the customized paths in this way. If you have some customized paths, you probably have to define them in startup.m and place this startup.m in the directory where you invoke matlab. I didn't check myself, but if you define E:\Production\Project\ as the path in startup.m, you probably can run matlab -r mytask without problem, as mytask will be recognized as a user function/script. A simple example of startup.m path(path, 'E:\Production\Project\');
{ "language": "en", "url": "https://stackoverflow.com/questions/7614292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Find if an overlay exists on a google map Is there any way to know if an overlay already exist on a map, before we addOverlay to a map. The thing what I want is, I have an application which gets LatLng points from google server Asynchronously, using these points I create Markers and add them to the map. So is there any way to check if that point has been added already to the map. By the way I am using GWT-RPC and Maps. Any help will be appreciated. A: What you can do is before adding the marker to the google map, add the markers in the List, and then iterate through the List to check if the two markers have same latlng point, but before that you need to overwrite the isequals() method as LatLng.isequals does what equals() ought to do, but constrained by the JS overlay rules. Also the following link might help you: How to avoid Java.util.IllegalStateException in the following code?
{ "language": "en", "url": "https://stackoverflow.com/questions/7614293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pile of little functions that call each other. Better way to organize my code? I'm a beginner but I've written my first little project and something about it doesn't really feel right. I hope I can describe the problem clearly. My whole program is basically a pile of little functions that call each other, and then one or two lines of code that call the initial function to start off the 'chain reaction' and return the desired result. It looks kind of like this (I'm using PHP): $result = func_A($args); function func_A($arg1, $arg2){ $localvar1 = blah blah; $value = func_B($localvar1, $arg2); return $value; } function func_B($arg1, $arg2){ $localvar1 = blah; $value = func_C($localvar1, $arg2); $return value; } function func_C($args){ blah blah blah } So when I try to go through my code, I'm hopping around all over the place between functions like crazy. Is there a better way to do this? Should I just be creating local functions within my other functions? This just doesn't feel quite right. A: There is nothing inherently wrong (and in fact a lot right) with this approach, if you're doing procedural programming (as it appears you are). PHP does now support Objects (albeit in a fabulously ugly way, in my opinion) so, there may be an argument for modifying your code to be more OO. However, it makes sense to isolate various tasks into small individual functions that you can then edit. I know this is somewhat controversial, but if you're just starting out in PHP, unless it's a core requirement of your client/employer, I would bypass it entirely and look into Node.js. There's a great deal of benefit that you get from using one language on both sides of the client/server isle, rather than dividing tasks into two similar looking but different languages, which constantly share screen real-estate as you work on them, owing to how much of a hassle it is to keep the server and display portions of the code truly separate. Of course PHP has become so entrenched that many people see it as a foregone conclusion. But (in my irrelevant opinion) all fandom aside, it has many shortcomings and is really ripe for retirement. A: Overall this is fine. We'd need to know more about specific goals and what the code is doing to get into more detail. In general, keeping the nuts and bolts in functions and calling them from a sort of main "command" center is a fine approach to procedural programming. However, some general high level rules that work for me: * *Don't repeat yourself. If you find you're doing the same things over and over again, make a function of that. If you load a value from a file, calculate something with it, and echo that, make a function for it. *Don't overspecialize too far. Lots of 2 line functions probably isn't a good thing. *If you can, be general. Don't make 5 different functions to connect to 5 different databases. Make one function and pass the name of the database to connect to it. See the rule about not repeating yourself. *If you have one function that calls another that calls another, and they are always used that way, consider making a single function of them. *Objects are great for dealing with a set of values and doing things with them. For a quick script, not so much, but if you're going to do some substantial work like validating data, storing it, reading it in, making it into a single string, that's a good opportunity to make a class. Classes will conveniently fit into a file which you can then use in other projects as well, and if you do maintenance to this class often, the scripts that use it may not need to be changed at all if your initial design was solid. A: You can use references to avoid repetitions. Add your functions name to an array and when you need a solution you have a main function that loops through that array and call the function with $this->$function_name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: django template for in for Any idea why this doesn't work? It gives me an error at {% if tab.title==foc %} {% for tab in menu %} {% for foc in focus %} <li>{{ tab.title }}</li> {% if tab.title==foc %} {% endif %} {% endfor %} {% endfor %} A: Try it with spaces around == Alternatively, use the ifqual tag instead of if A: The if statement was introduced on django 1.2 alpha and modified on django 1.2 The right way of using it: {% if somevar == "x" %} This appears if variable somevar equals the string "x" {% endif %} Check your django version at your django console with: django.version And if you using a lesser than 1.2 you should use the ifequal tag
{ "language": "en", "url": "https://stackoverflow.com/questions/7614300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript check multiple textbox for numeric I am checking numeric value for one textbox like this: function validateNumeric() { var old = document.getElementById("tbNum").value; var new = old_val.replace(/^\s+|\s+$/g,""); var validChars = '0123456789'; for(var i = 0; i < new.length; i++){ if(validChars.indexOf(new.charAt(i)) == -1){ alert('Please enter valid number'); return false; } } document.getElementById("tbNum").value = new; return true; } I want to use the same function and check numeric value for other text boxes that requires numeric value. How can I pass value of tbID, tbDiscID, as well as above and return true before submitting the form. A: I am not sure what you mean by tbId and tbDiscID, but to do this in plain JavaScript, you can generalize this solution by traversing JavaScript's arguments object, which lets you pass in any variable number of arguments to your function. This will help you take in the IDs you need. Your new solution would look something like the following: function validateNumeric() { for (var arg in arguments) { var id = arguments[arg]; var old = document.getElementById(id).value; var new = old_val.replace(/^\s+|\s+$/g,""); var validChars = '0123456789'; for(var i = 0; i < new.length; i++){ if(validChars.indexOf(new.charAt(i)) == -1){ alert('Please enter valid number'); return false; } } document.getElementById(id).value = new; return true; } } Then invoke it like: validateNumeric("myTextbox1", "myTextbox2", ..., "myTextboxN"); Where myTextBox1 ... myTextBoxN are the IDs of your textboxes. A: use parameter for the function, for using it on different elements validateNumeric(value) { use the onsubmit parameter on the form tag to call a validation <form name="myForm" action="dosomething.php" onsubmit="return validateForm()" write your validate function with calls for all elements function validateForm() { if (!validateNumeric(document.getElementById("tbNum"))) { return false; } ... return true; would be one way.. edit forgot the check within the validateForm method
{ "language": "en", "url": "https://stackoverflow.com/questions/7614312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++:error C2440: '' : cannot convert from 'A' to 'B' I have a base class A and it has a subclass B. A overrides the + operator and B overrides it as well,calls the parent's +operator, and casts the result to B. Then I am getting the error message: error C2440: '' : cannot convert from 'A' to 'B' I thought polymorphism worked in a way that should allow this to work? A: In polymorphism you cannot convert A to B, you can convert B to A. B is a kind of A, but A is NOT a kind of B. For example, in the classic Shape classes. If you have a class Shape and a class Rectangle that extends [inherit from] Shape, you cannot convert a Shape instance to Rectangle, but you CAN cast a Rectangle to Shape, because it is a 'kind of' Shape.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Failing to Target Children Any idea why this isn't working? The children of the unordered list are not sliding up like I expect.. http://jsfiddle.net/SparrwHawk/vqUgw/3/ A: here you go bro this looks like what you want: http://jsfiddle.net/2x2fE/ A: I was able to fix this by using mouseover and mouseleave with a selector on the children like so: $(document).ready (function(){ $('nav ul li').mouseover(function(){ $(this).children('ul').slideDown() }); $('nav ul li').mouseleave(function(){ $(this).children('ul').slideUp(); }); }); A: There is some error in you code. Check the fixed one. $(document).ready (function(){ $('nav ul li').hover(function(){ $(this).children("ul").slideDown(). addClass('shown'); }, function(){ $('.shown').slideUp().removeClass(".shown"); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7614315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between native objects and host objects? I don't understand the difference between native objects and host objects in JavaScript. Does the latter simply refer to non-primitive function objects that were created by a custom constructor (e.g., var bird1 = new Bird();)? A: In addition to the other answers regarding Host Objects. Host objects are specific to a environment. So next to the browsers' host objects, there are also specific objects in nodejs. For the sake of the example, first starting with the Standard objects as defined in Javascript. Then the common objects for the Browser/DOM. Node has it's own Objects. * *Standard Javascript built-in object examples: * *Object *Function *Boolean *Symbol *Number *Math *... (See full list on MDN web docs) *Host Objects Document Object Model Examples: * *Window *Document *History *... (See full list on DOM objects on MDN web docs) *XMLHttpRequest (part of Web API) *... (See full list Web API on MDN web docs) *Host Objects in Node.js: * *http *https *fs *url *os *... (See full list on nodejs.org) A: It is more clear if we distinguish between three kinds of objects: Built-in objects: String, Math, RegExp, Object, Function etc. - core predefined objects always available in JavaScript. Defined in the ECMAScript spec. Host objects: objects like window, XmlHttpRequest, DOM nodes and so on, which is provided by the browser environment. They are distinct from the built-in objects because not all environment will have the same host objects. If JavaScript runs outside of the browser, for example as server side scripting language like in Node.js, different host objects will be available. User objects: objects defined in JavaScript code. So 'Bird' in your example would be a user object. The JavaScript spec groups built-in objects and user objects together as native objects. This is an unorthodox use of the term "native", since user objects are obviously implemented in JavaScript while the built-ins is most likely implemented in a different language under the hood, just as the host objects would be. But from the perspective of the JavaScript spec, both builtins and user objects are native to JavaScript because they are defined in the JavaScript spec, while host objects are not. A: Could not see a convincing answer to the question whether var bird1 = new Bird(); is a native or host object. Assuming Bird is a user defined function, a native non-built-in object will be created according to http://es5.github.io/#x13.2 by the javascript implementation. In contrast, native built-in objects will be present since the start of a javascript program (such as Object and many others). A difference between a native object and a host object is that former is created by the javascript implementation and the latter is provided by the host environment. As a result host object internal [[class]] property can be different from those used by built-in objects (i.e. "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String"). Also, worthwhile noting that ECMA6 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf does not use the terminology native and host objects any more. Instead, it defines below object types, with more clear explanations of their intended behaviour. 4.3.6 ordinary object object that has the default behaviour for the essential internal methods that must be supported by all objects 4.3.7 exotic object object that does not have the default behaviour for one or more of the essential internal methods that must be supported by all objects NOTE Any object that is not an ordinary object is an exotic object. 4.3.8 standard object object whose semantics are defined by this specification 4.3.9 built-in object object specified and supplied by an ECMAScript implementation A: Here's my understanding of the spec. This: var bird = new Bird(); ...results in a native Object that simply happened to be created using the new operator. Native objects have an internal [[Class]] property of one of the following: "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String". For your bird1 it will be: "Object" Just like if you create a function: function my_func() { // ... } ...my_func isn't defined in ECMAScript, but it is still a native object with the internal [[Class]]: "Function" A host object is an object provided by the environment in order to serve a specific purpose to that environment not defined in by the specification. For example: var divs = document.getElementsByTagName('div') The object referenced by divs is a NodeList, which is integrated into the environment in such a manner that it feels like a regular JavaScript object, yet it isn't defined anywhere by the specification. Its internal [[Class]] property is: "NodeList" This provides implementation designers some flexibility in suiting the implementation to the specific need of the environment. There are requirements of host objects that are defined throughout the spec. A: Both terms are defined in the ECMAScript specification: native object object in an ECMAScript implementation whose semantics are fully defined by this specification rather than by the host environment. NOTE Standard native objects are defined in this specification. Some native objects are built-in; others may be constructed during the course of execution of an ECMAScript program. Source: http://es5.github.com/#x4.3.6 host object object supplied by the host environment to complete the execution environment of ECMAScript. NOTE Any object that is not native is a host object. Source: http://es5.github.com/#x4.3.8 A few examples: Native objects: Object (constructor), Date, Math, parseInt, eval, string methods like indexOf and replace, array methods, ... Host objects (assuming browser environment): window, document, location, history, XMLHttpRequest, setTimeout, getElementsByTagName, querySelectorAll, ... A: Considering three objects: Host, Native, Custom. Host Objects are created by the environment and are environment specific. Best known environment would be a web-browser but could be another platform. The host objects created in web-browser could be the window object or the document. Typically a browser uses an API to create Host Objects to reflect the Document Object Model into JavaScript. (Webbrowser have different JavaScript Engines that do this) A host object is created automatically the moment the page renders in a browser. A Native Object is created by the developer using predefined classes of JavaScript. Native Objects are in your written script. Than, a Custom Object is made by the developer from a custom (not predefined, or partially predefined) class. A: Native objects are objects that adhere to the specs, i.e. "standard objects". Host objects are objects that the browser (or other runtime environment like Node) provides. Most host objects are native objects, and whenever you instantiate something using new, you can be 99.99% sure that it is a native object, unless you mess around with weird host objects. This notion has been introduced due to the presence of very bizarre objects in IE(and other old browsers?). For example: typeof document.all == "undefined"; // true document.all.myElementId; // object When seeing this, everyone would agree that document.all is clearly "non-standard", and thus a non-native host object. So why not call native objects standard objects in the first place? Simple: after all, the Standard(!) document talks about non-native objects too, and calling them non-standard would lead to a paradox. Again: * *native == "standard" *host == provided by the browser or Node or … *most host objects are native, and all non-host objects are native too A: This may be overkill, but for simplicity a native object is one that exist and is usable in any environment that implements an ECMAScript compliant engine. This is usually (but not always) a browser. So, your Internet Explorer or your Google Chrome, doesn't make the String object available to you, for example. The reason you can use the String object is because it is "native" (built-in) to the JavaScript language itself. However, if you'd like to create a pop-up window, you'll need to use the window object. The window object is provided by the browser software itself, so it is not native to JavaScript, but it is part of the "Browser Object Model" or the BOM.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "106" }
Q: How to find Port number of IP address? We can find out IP address of a domain name or URL. But how to find out Port number on which a domain name is hosted? A: DNS server usually have a standard of ports used. But if it's different, you could try nmap and do a port scan like so: > nmap 127.0.0.1 A: Unfortunately the standard DNS A-record (domain name to IP address) used by web-browsers to locate web-servers does not include a port number. Web-browsers use the URL protocol prefix (http://) to determine the port number (http = 80, https = 443, ftp = 21, etc.) unless the port number is specifically typed in the URL (for example "http://www.simpledns.com:5000" = port 5000). Can I specify a TCP/IP port number for my web-server in DNS? (Other than the standard port 80) A: The port is usually fixed, for DNS it's 53. A: If it is a normal then the port number is always 80 and may be written as http://www.somewhere.com:80 Though you don't need to specify it as :80 is the default of every web browser. If the site chose to use something else then they are intending to hide from anything not sent by a "friendly" or linked to. Those ones usually show with https and their port number is unknown and decided by their admin. If you choose to runn a port scanner trying every number nn from say 10000 to 30000 in https://something.somewhere.com:nn Then your isp or their antivirus will probably notice and disconnect you. A: Quite an old question, but might be helpful to somebody in need. If you know the url, * *open the chrome browser, *open developer tools in chrome , *Put the url in search bar and hit enter *look in network tab, you will see the ip and port both A: Use of the netstat -a command will give you a list of connections to your system/server where you are executing the command. For example it will display as below, where 35070 is the port number TCP 10.144.0.159:**52121** sd-s-fgh:35070 ESTABLISHED A: Port numbers are defined by convention. HTTP servers generally listen on port 80, ssh servers listen on 22. But there are no requirements that they do. A: domain = self.env['ir.config_parameter'].get_param('web.base.url') I got the hostname and port number using this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Simulate right click I am wondering how to make my Java program simulate a right click. So imagine your mouse cannot right click anymore. How do I make Java simulate the right click? Im planning to have a button that u press on a JFrame that simulates the right click after x seconds. Thanks and please try to include some code and not just links A: Im planning to have a button that u press on a jframe that simulates the right click after x seconds button.doClick(); A: Windows? Control Panel | Ease of Access | Make the mouse easier to use | Control the mouse with the keyboard As an aside. A mouse is usually less that $10. If your time is worth $20 an hour, you'd have to finish the code within 30 minutes to make it cheaper than buying a new mouse. This project seems a 'false economy'. A: The java.awt.Robot api was designed for exactly this. It has lots of goodies in it! Specifically in this case, mousePress and mouseRelease. P.S. Yes I realize they're just links. But in all honesty, learning to read API docs and make code from them effectively is a skill every developer needs!
{ "language": "en", "url": "https://stackoverflow.com/questions/7614319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I set the footer of linear layout? I've got the following: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/imageView1" android:background="@drawable/header"></ImageView> <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_width="match_parent"> </LinearLayout> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/editText2" android:text="EditText"></EditText> <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/editText1" android:text="EditText"></EditText> <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_gravity="bottom"> <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/footer" android:id="@+id/imageView2" android:layout_gravity="bottom"></ImageView> </LinearLayout> I want put the image at the footer, not after the text boxes. Please help I am new to the android and I'm looking for help. A: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/imageView1" android:background="@drawable/header"></ImageView> <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_width="match_parent"> </LinearLayout> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/editText2" android:text="EditText"></EditText> <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/editText1" android:text="EditText"></EditText> <RelativeLayout android:id="@+id/relLayout" android:layout_height="fill_parent" android:layout_width="match_parent" > <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@drawable/footer" android:id="@+id/imageView2" android:layout_alignParentBottom="true"></ImageView> </RelativeLayout > ...... A: it is better to use a RelativeLayout instead of LinearLayout
{ "language": "en", "url": "https://stackoverflow.com/questions/7614321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Converting VS2005 Web Service Project to VS2010 I inherited a web service that was installed and forgotten about years ago. Now we need to change it, but it's built in VS2005, and all I have is vs2010. When I load the project, it automatically attempts to convert, but fails on these errors: The operation could not be completed. The system cannot find the path specified. (no information on what file it was looking for) Could not find the server 'http://localhost/<myproject>/<myproject>.csproj' on the local machine. Creating a virtual directory is only supported on the local IIS server. (I don't understand why a setting like that should prevent the project from loading/ connecting, this is clearly a config thing. Besides, I'm using IIS Express, which uses different ports, so that'll never work.) Unfortunately, there does not seem to be an opportunity to manually tweak these problems in VS2010. It simply won't load the project. How can I force this to load in VS so I can fix this in a reasonably sane manner? Maybe run VS2010 in some compatibility mode, or if there's an app I can use to convert this, or if someone has some experience in doing this sort of thing, I'd love to hear about it. A: Do you still have VS2005 around? Open the project in VS2005 and look at the project settings. See if the project is set up to use the local IIS server. If it is, then change it to use the Visual Studio Development Server and save the project. Convert it to VS2010 and you should be able to open it (still using the Development Server). Then, change the settings to use IIS Express.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: best practices, designing mac applications What is the ways/best practices when designing elements on the mac platform in objective-c? I looking on reading stuff for elements like * *NSButton *NSTextField *Gradient backgrounds *etc Should i really subclass all elements and draw it my self (corners, middle area, etc) or could i use some sort of nifty background-image trick. I have been searching on google on stuff but did not really find anything useful (i might be searching for the wrong thing?) Any help appreciated, thanks! A: They are different theories, but I personally think subclassing is a good way for that kind of stuff. Then you can build your application with custom components, which have additional properties, in regard to the built-in ones. In my point of view, you'll gain a lot by creating generic subclasses, and then subclassing those subclasses with specific code. You'll then have a kind of derivation. You can then manage backward compatibility more easily, and a change in the generic component class will reflect in all subclasses. So in my humble opinion, just don't be afraid of subclasses for that kind of stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Uninitialized Constant Mysql2 - Windows Here's my system specs: Windows 7 Ultimate 32bit Ruby 1.9.2 Rails 3.1 MySQL 5.5 I have created a new rails app using compass and when I do: rake db:create --trace I get the following results: ** Invoke db:create (first_time) ** Invoke db:load_config (first_time) ** Invoke rails_env (first_time) ** Execute rails_env ** Execute db:load_config ** Execute db:create rake aborted! uninitialized constant Mysql2 I can confirm that MySQL is running as I can access it from the command line. I also have the mysql2 0.3.7 gem installed. The bundle install also runs without a hitch. I've read that reverting back to MySQL 5.1 might fix the issue, but it took me so long just to get the gem installed I don't know if I want to go through that whole process again. Anyone have any thoughts?
{ "language": "en", "url": "https://stackoverflow.com/questions/7614327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you read git config values on a push remotely? I have a centralized repository with a few developers pushing to it. I've installed ReviewBoard and I'd like to set up a hook to post each commit to review board so the peers can comment on it. I'd like this to be done automatically from the centralized repository. The best way I can tell to do this would be to set a custom config value of reviewboard.username. I assume github does this, otherwise wouldn't it be pointless to have the user set github.user and github.token on your local copy? (http://help.github.com/set-your-user-name-email-and-github-token/) How would I go about getting config values from the pusher on the centralized server in say, post-receive? A: The github user and token are for identification purpose, when ssh isn't used. As for pushing automatically to a repo B when pushing to A, consider adding to your repo an extra layer like Gitolite, especially since the recent 2.1 edition, with mirrors feature. See the announce from today (Sep. 30th): [ANNOUNCE] Gitolite v2.1 and mirroring features: Almost as good as "active-active" mirroring: If the "master" server trusts the authentication performed by the "slave" server, you can have the slave internally redirect a "git push" to the correct master. With this, developers don't have to remember which repo is mastered where, use different 'pushurl's, etc. They just do everything with their local mirror and let the system deal with it. (You can even change which server is "master" and people don't even need to know it has changed!) A: You can't push custom or not config values to another repository with git. Github has you put the token and user in your config for 3rd party apps running on your computer. So I suppose if you needed to get the config variables for a hook to do something, your options are either mirroring as VonC recommends where the admin is dealing with repository mirrors and syncing them back to master, or just suck it up and write your hook to run on the 'local client' repositories and have (and trust?) each developer to have them installed. I've thought one option could be to have a separate repo with the hooks, maybe as a submodule, maybe not, and symlink them into .git/hooks/
{ "language": "en", "url": "https://stackoverflow.com/questions/7614329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Listen to multiple keydowns I'm trying to let a user move an element on the page using the arrow keys. So far, I have movement working for up/down/left/right, but not for diagonal (two arrow keys pressed simultaneously). My listener looks like this: addEventListener('keydown', function(e){ move = false; x = false; y = false; var keycode; if (window.event) keycode = window.event.keyCode; else if (e) keycode = e.which; switch(keycode){ case 37: move = true; x = 'negative'; //prevent page scroll e.preventDefault() break; case 38: move = true; y = 'negative' //prevent page scroll e.preventDefault() break; case 39: move = true; x = 'positive' //prevent page scroll e.preventDefault() break; case 40: move = true; y = 'positive' //prevent page scroll e.preventDefault() break; } if(move){ animation.move(x,y); } return false; }) The idea was that if the user presses an arrow key, it sets x and y to either negative or positive, and fires off the move() function, which will move the element a preset number of pixels in the desired direction, and that if two keys were pressed, a second event would fire... I also hope to be able to have the user seemlessly change directions by releasing and pressing keys rapidly Neither of these are happening, however, if the user presses another direction key, they seem to need to wait a momment for movement to happen, unless they completely release the key and then press another one, and it won't respond to the second key at all until the first is released. A: Fiddle: http://jsfiddle.net/ATUEx/ Create a temporary cache to remember your key strokes. An implementation of handling two keys would follow this pattern: * *<keydown> * *Clear previous time-out. *Check whether the a key code has been cached or not.If yes, and valid combination: - Delete all cached key codes - Execute function for this combination else - Delete all cached key codes - Store the new key code - Set a time out to clear the keycodes (see below), with a reasonable delay *Repeat 1 A reasonable delay: Experiment to know which timeout is sufficient for you. When the delay is too short, the next initiated event will not find a previously entered key code. When the delay is too long, the key strokes will stack when you don't want it. Code I have created an efficient function, keeping your code in mind. You should be able to implement it very easily. (function(){ //Anonymous function, no leaks /* Change the next variable if necessary */ var timeout = 200; /* Timeout in milliseconds*/ var lastKeyCode = -1; var timer = null; function keyCheck(ev){ var keyCode = typeof ev.which != "undefined" ? ev.which : event.keyCode; /* An alternative way to check keyCodes: * if(keyCode >= 37 && keyCode <= 40) ..*/ /*37=Left 38=Up 39=Right 40=Down */ if([37, 38, 39, 40].indexOf(keyCode) != -1){ /* lastKeyCode == -1 = no saved key Difference betwene keyCodes == opposite keys = no possible combi*/ if(lastKeyCode == -1 || Math.abs(lastKeyCode - keyCode) == 2){ refresh(); lastKeyCode = keyCode; } else if(lastKeyCode == keyCode){ clear([lastKeyCode]); } else { /* lastKeyCode != -1 && keyCode != lastKeyCode and no opposite key = possible combi*/ clear([lastKeyCode, keyCode]); lastKeyCode = -1 } ev.preventDefault(); //Stop default behaviour ev.stopPropagation(); //Other event listeners won't get the event } /* Functions used above, grouped together for code readability */ function reset(){ keyCombi([lastKeyCode]); lastKeyCode = -1; } function clear(array_keys){ clearTimeout(timer); keyCombi(array_keys); } function refresh(){ clearTimeout(timer); timer = setTimeout(reset, timeout); } } var lastX = false; var lastY = false; function keyCombi(/*Array*/ keys){ /* Are the following keyCodes in array "keys"?*/ var left = keys.indexOf(37) != -1; var up = keys.indexOf(38) != -1; var right = keys.indexOf(39) != -1; var down = keys.indexOf(40) != -1; /* What direction? */ var x = left ? "negative" : right ? "positive" : false; var y = up ? "negative" : down ? "positive" : false; /* Are we heading to a different direction?*/ if(lastX != x || lastY != y) animation.move(x, y); lastX = x; lastY = y; } //Add event listener var eventType = "keydown";window["on"+eventType] = keyCheck; })(); At the end of the anonymous function, the keydown event listener is added. This event is fired only once (when the key is pressed down). When a second key is pressed fast enough, the code recognises two key strokes after each other, and calls keyCombi(). I have designed keyCombi to be intelligent, and only call animation.move(x,y) when the values are changed. Also, I've implemented the possiblity to deal with two directions at a time. Note: I have contained the functions within an anonymous function wrapper, so that the variables are not defined in the global (window) scope. If you don't care about scoping, feel free to remove the first and last line. A: Here is your code for you, slightly revised ... http://jsfiddle.net/w8uNz/ It just WORKS. Moves element across the parent element. Rob W is right, you should have a dynamic cache of keys being pressed down at a period of time. But for what ? if you are making a dynamic game - there must be much higher abstraction for that. And overall, you need to improve your level of coding if you want to do stuff like that. (Or it will just generate headaches for you.) A: Logically this sounds rather simple: * *the first key triggers a key down event, store this event in a stack *then the second key triggers a key down event, store this event in a stack *now you have two key downs and no key up *if a key up fires you have three possibilities * *you have only one event => go in that direction *you have two events => go diagonally *you have more than two events, or an invalid option (e.g. right and left) => do nothing, or whatever you feel like *clear the stack
{ "language": "en", "url": "https://stackoverflow.com/questions/7614340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Wordpress query_posts posts_per_page not working Can't figure out why this is not limiting the posts_per_page. It is displaying a very long list of posts, but I only want to show 4 query_posts('posts_per_page=4&post_type=page&pagename=media'); if(have_posts() ) : while(have_posts()) : the_post(); A: Please try wp_reset_query(); before your code. // Reset Query wp_reset_query(); query_posts('posts_per_page=4&post_type=page&pagename=media'); if(have_posts() ) : while(have_posts()) : the_post(); A: You are resetting the query each time. You need to include the existing query string, otherwise when you paginate the pagination information will be lost. Try this instead. global $query_string; query_posts( $query_string . '&post_type=page&pagename=media' ); Also to note, if you are specifing a specific page with pagename=media then how can than paginate, it should only return one page?! A: I had this same problem on a wordpress site and I tried all the ways to find that site was using Posts per category plugin which was overriding the posts_per_page argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is this SQL SELECT statement not retrieving the row I just inserted? I am creating an in-memory SQLite database and inserting some a row into it. Unfortunately, I am unable to select the row I just inserted. <?php const CACHE_SCHEMA = <<<EOD CREATE TABLE test ( column1 TINYTEXT, column2 MEDIUMTEXT, column3 INT, column4 INT ) EOD; $db = new PDO('sqlite::memory:'); $statement = $db->query(CACHE_SCHEMA); $statement->execute(); $statement = $db->prepare('INSERT INTO test (column1, column2, column3, column4) VALUES (?,?,?,?)'); $statement->execute(array('a', 'b', 123, 2)); $statement = $db->prepare('SELECT column2 FROM test WHERE column1 = ? AND column3 + column4 >= ?'); $statement->execute(array('a', 124)); var_dump($statement->fetch(PDO::FETCH_ASSOC)); ?> Output: bool(false) As you can see, the 'SELECT' statement is not returning the row I inserted: * *Adding 'column3' and 'column4' of the row I inserted yields 125. *The 'WHERE' clause of the statement becomes: 'WHERE column1 = "a" AND column3 + column4 >= 124' once parameters are filled in. *Unless I'm mistaken, 125 >= 124. A: It took a bit of thinking to figure this one out, but according to the documentation for PDOStatement::execute(): "All values are treated as PDO::PARAM_STR." So I need to change: $statement->execute(array('a', 124)); to: $statement->bindValue(1, 'a'); $statement->bindValue(2, 124, PDO::PARAM_INT); $statement->execute(); ...and then instead of binding a string value to the last parameter, it will bind an integer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hide an element for three minutes of connectivity I have a chat application and I would like to display a "request supervisor" button to display after three minutes of the user being connected. This would include a user refreshing the page. Here is what I have, but it's really not sufficient at all; //shows the tooltip in 3 minutes window.setTimeout(function(){ $("#panic-tooltip").fadeTo(1000, 1); }, 180000); Obviously if the user refreshes the page it locks up. I was thinking about using a cookie somehow... I'd prefer not to have to have to do anything on the backend, but I might have to. Also, I am aware that push technology would be a good solution, but that's not an option here. I'm using HTML5/CSS3/jQuery/jQuery UI btw if any of that is helps. Thanks! A: This is what i ended up using... too bad davin or mellamokb didn't answer lol if($.cookie("showPanic") == 'yes'){ $("#panic-tooltip").fadeTo(1000, 1); } else { window.setTimeout(function(){ $("#panic-tooltip").fadeTo(1000, 1); $.cookie("showPanic", "yes"); }, 180000); } A: Given you have a function to set a cookie and one to retrieve a cookie, it is relatively simple. On first visit you set the cookie with the current time like this: if(!getCooke('first_visit')) setCookie('first_visit', new Date().toString()); But only if the cookie is not already present. Additionally you have an interval loop the checks for the difference in time: var timer = setInterval(function(){ var oldDate = new Date(getCookie('first_visit')), newDate = new Date(); if(newDate - oldDate > 180000){ //time is in miliseconds clearInterval(timer); //show your message here $("#panic-tooltip").fadeTo(1000, 1); } },1000);
{ "language": "en", "url": "https://stackoverflow.com/questions/7614353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Programmatically login to Facebook using username/password Ok, I've been looking for over an hour on this subject and can only find OAuth solutions, which I do not need or want. I need to authenticate as myself to Facebook from a location other than Facebook. I need my website (admin area) to authenticate to Facebook for me and post in my behalf, on my wall, or my friends wall. This is an administration tool, and I don't want to login into Facebook every time I post to my website. I need this admin extension to login for me, and add an automated post with a title and image: "New post on example.com". It feels like I've been looking everywhere and can only find solutions with creating a FB application, granting it certain rights, using oauth, etc-overly-complicated-process, which is (dare-i-say) rather stupid since I don't want to authenticate other people, like visitors. I simply want to emulate my(self|browser), as if I'm the one navigating through their pages and not an automated tool. Of course I could probably go the cURL way and emulate a real user-agent but I'm not about to start scraping FB pages. Is there a programmatic way of authenticating to FB using a simple user/pass (not even stored on the server) and get the same rights I normally get when authenticating through a browser? And of course, obtain needed data in a json or other machine parse-able encapsulation ? I would assume I need to send a cookie or some form of token on susequent requests, but that's not a problem, I just need a way of authenticating with a simple user/pass and bypass that whole app registration ache. I'd need something similar to twitter and google+ maybe (?) I did find a simple class for twitter but nothing on google+ (same problem, twitter is pushing hard for their way of creating an app and using oauth, but they do maintain a way of authenticating as yourself through simple REST requests). A: I don't believe there is a way to do what you're describing, other than a painful and non-supported method of emulating a user agent. It's also not a good practice to do what you're describing, as Facebook (and other websites for that matter) should not allow 3rd parties to collect usernames/passwords, even if it's only in transit. I understand that in your scenario, you will be the only user, but Facebook has to design their API for the masses. Why not set up a Facebook App and use oauth? You'll only need to authorize your App once, get an offline access token, and then use that access token from then on. I think this will be easier than the approach you're looking for because you won't need to authenticate with Facebook every time. You just need the access token. Note that the offline access token will expire if you change your Facebook password or you de-authorize your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: history table and 2nf Users table and Group users table are history tables (they cannot be moved to archived tables cause that would mess up foreign keys related to those tables. If a group user made a post and left the group, the post should still exist etc) Users Username Start Date key (Username, Start Date) Group Users Group Name Username Start Date Group Start Date Primary Key (Group Name, Username, Group Start Date) Foreign Key (Username, Start Date) According to 2NF, any nonkey field cannot be a fact about a subset of a key. In this case, Username is part of a composite key and Start Date is a fact about Username, therefore this table is not in 2NF. So would the fix be to include the start date as part of the key? A: Start Date is a fact about Username Not it isn't. Start date cannot be determined by Username in your model because (Username, Start Date) is a key - the Username and Start Date together are needed to identify a row in the users table. A: The PK of Group Users is arguably incorrect because combination of UserName and StartDate is required to uniquely identify a user. So, if 'John' (the first) joined on 2011-09-01 and 'John' (the second) joined on 2011-09-10, then your Group Users PK prevents them from both joining the same Group. Your Group Users PK should include both UserName and Start Date since this combination is what identifies a user uniquely. This is why people use 'ID' columns; if you had a Users.ID column, then you'd use that simple key in the FK in Groups Users. Compound primary keys that are themselves used as foreign keys in other tables tend to be problematic (for cases such as this) and a surrogate such as an ID column then makes the DB design simpler. You should presumably have a Group table too and Group Users.Group Name should be a FK to that table. It is a bit surprising that there is no 'unsubscribe date' in the Group Users table, nor in the Users table. Or you may prefer a 'currently subscribed' flag, but the date is also useful, in general.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Standards for Date/Time addition? I'm looking for standards for Date/Time addition. I haven't been able to find any. In particular I'm hoping to find a spec that defines what should happen when you add a month to a date like January 31st. Is the right answer February 28th(/29th)? March 1st? March 2nd? I've seen inconsistent implementations between different tools (PHP & MySQL in this case), and I'm trying to find some sort of standards to base my work on. Differing Results: PHP $end = strtotime("+1 month", 1314835200); //1317513600 Sat, 01 Oct 2011 20:00:00 -0400 MySQL SELECT UNIX_TIMESTAMP(DATE_ADD(FROM_UNIXTIME(1314835200), INTERVAL 1 MONTH)); #1317427200 Fri, 30 Sep 2011 20:00:00 -0400 Oracle SELECT ADD_MONTHS('31-Aug-11', 1) FROM dual; #30-SEP-11 (sorry for the format change, my oracle foo is weak) Java Calendar c = Calendar.getInstance(); c.clear(); c.set( 2011, Calendar.AUGUST, 31 ); c.add( Calendar.MONTH, 1 ); c.getTime() #Fri Sep 30 00:00:00 EDT 2011 A: I believe the defacto standard is ISO 8601. Unfortunately, there are many ambiguities, for example: Date arithmetic is not defined 2001-03-30 + P1M = 2001-04-29 (Add 30 days) 2001-03-30 + P1M = 2001-04-30 (Add 1 mon.) Addition is not commutative or associative 2001-03-30 + P1D + P1M = 2001-04-30 2001-03-30 + P1M + P1D = 2001-05-01 Subtraction is not the inverse of Addition. Precision of decimal fractions can vary. The full specification can be found at http://www.iso.org/iso/catalogue_detail.htm?csnumber=26780 I think each product is attempting to adhere to an impossible to implement standard. The ambiguous parts are open to interpretation and so everyone interprets. This is the same standard that opened us up to the Y2K bug!! Myself, I favor an implementation that converts a date/time to a 1970 based number (UNIX timestamp), performs the calculation and converts back. I believe this is the approach taken by Oracle/MySQL. I am surprised that more attention has not been paid this issue, as it is really important, sometimes critical, in so many applications. Thanks for the question! Edit: While doing some more reading, I found Joe Celko's thoughts on different date/time representations and standardization HERE. A: According to the POSIX.1-2001 standard, next month (as in incrementing tm_mon before calling mktime) is done by adjusting the values until they fit. So, for example, next month from January 31, 2001 is March 3, 2001. This is because the tm_mday of 31 isn't valid with tm_mon of 1 (February), so it is normalized to tm_mon of 2 (March) and tm_mday of 3. The next month from January 31, 2000 is March 2, 2000, because Feb. has 29 days that year. The next month from January, 1 2038 doesn't exist, depending. The great thing about standards is there are so many to chose from. Check the SQL standard, I bet you can find a different meaning of next month. I suspect ISO 8601 may give you yet another choice. Point is, there are many different behaviors, the meaning of 'next month' is very domain-specific. edit: I think I've found how SQL-92 handles it, apparently asking for next month from January 31 is an error. Links: * *SQL-92: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt *POSIX: http://pubs.opengroup.org/onlinepubs/9699919799/ (though apparently that version now defers to ISO C, which doesn't seem as clear. The mktime manpage on my machine is clear, though) *ISO C: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf *Java: http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html A: Query: SELECT ADDDATE(DATE('2010-12-31'), INTERVAL 1 MONTH) 'Dec + Month', ADDDATE(DATE('2011-01-31'), INTERVAL 1 MONTH) 'Jan + Month', ADDDATE(DATE('2011-02-28'), INTERVAL 1 MONTH) 'Feb + Month', ADDDATE(DATE('2011-03-31'), INTERVAL 1 MONTH) 'Mar + Month'; Output: Dec + Month Jan + Month Feb + Month Mar + Month 2011-01-31 2011-02-28 2011-03-28 2011-04-30 My conclusion: * *Calculate the number of days in the month of the input date. *Add that many days to the input date. *Check if the day in the resulting date exceeds the maximun number of days in the resulting month. *If yes, then change the resulting day to maximum day of the resulting month. If you add MONTH, YEAR_MONTH, or YEAR and the resulting date has a day that is larger than the maximum day for the new month, the day is adjusted to the maximum days in the new month source Problem here is that it doesn't mention that the month is actually the month from the input date. A: Joda-Time in Java chooses the previous valid date when an invalid one is created. For example, 2011-01-31 + P1M = 2011-02-28. I believe this is the most widely chosen default choice in date-time libraries, and thus a de facto standard. ThreeTen/JSR-310 provides a strategy pattern for this, with four choices, see the code. More amusing is the question of what the answer to 2011-01-31 + P1M-1D is. If you add the month, then resolve the invalid date, then subtract the day, you get 2011-02-27. But I think most users expect 2011-02-28 because the period is being added in a single lump. See how ThreeTen handles this here. I have considered trying to write a general purpose best practices in date/time calculations, or actual spec, but haven't really had the time! A: First day of the month + 1 month should equal the first of the next month. Trying this on SQL Server SELECT CAST ('01/01/2012' AS DateTime), DATEADD (m, 1, '01/01/2012') UNION ALL SELECT CAST ('02/01/2012' AS DateTime), DATEADD (m, 1, '02/01/2012') UNION ALL SELECT CAST ('03/01/2012' AS DateTime), DATEADD (m, 1, '03/01/2012') UNION ALL SELECT CAST ('04/01/2012' AS DateTime), DATEADD (m, 1, '04/01/2012') UNION ALL SELECT CAST ('05/01/2012' AS DateTime), DATEADD (m, 1, '05/01/2012') This results in ----------------------- ----------------------- 2012-01-01 2012-02-01 2012-02-01 2012-03-01 2012-03-01 2012-04-01 2012-04-01 2012-05-01 2012-05-01 2012-06-01 Last day of this month + 1 month should equal last day of next month. This should go for next month, current month, 10 months down, etc. SELECT CAST ('01/31/2012' AS DateTime), DATEADD (m, 1, '01/31/2012') UNION ALL SELECT CAST ('01/30/2012' AS DateTime), DATEADD (m, 1, '01/30/2012') UNION ALL SELECT CAST ('01/29/2012' AS DateTime), DATEADD (m, 1, '01/29/2012') UNION ALL SELECT CAST ('01/28/2012' AS DateTime), DATEADD (m, 1, '01/28/2012') UNION ALL SELECT CAST ('01/27/2012' AS DateTime), DATEADD (m, 1, '01/27/2012') UNION ALL SELECT CAST ('01/26/2012' AS DateTime), DATEADD (m, 1, '01/26/2012') This results in ----------------------- ----------------------- 2012-01-31 2012-02-29 2012-01-30 2012-02-29 2012-01-29 2012-02-29 2012-01-28 2012-02-28 2012-01-27 2012-02-27 2012-01-26 2012-02-26 See how 31, 30, 29 all become feb 29 (2012 is a leap year). p.s. I took off the time parts (all zeroes) to help make it more readable A: There is no widely accepted standard. The reason for the different implementations is that folks can't agree on what the standard should be. Many popular software systems give answers that no one would expect. Documentation is always necessary, therefore, to tell the user what your system will deliver. You choose a methodology, however, based on what you think most folks will expect. I think most people on the street would agree that: * *You can't define a 'month' by a certain number of days. So... *When it's Jan 31 and someone says "I'll meet you a month from today", they mean the last day of February. Basically, it's add to the month, then find the day number that is closest to today without exceeding it. The exception comes in accounting, where sometimes a month means 30 days. EDIT: I asked some folks around here, "If it's March 31 and someone says I'll meet you a month from today, what day are you going to meet them?" Most said, April 30, but a few said April 28 because it's four weeks away. The few were interpreting work schedules and thinking "if we met on this weekday, we'll meet again on the same weekday". Basically, if they met on the last Thursday of the month, and they're due to meet in one month, it'll be on the last Thursday of that month. So, there ya go. :\ A: Try the mysql date function : SELECT ADDDATE('2011-01-31', INTERVAL 1 MONTH) // 2011-02-28 Input date with leap year SELECT ADDDATE('2012-01-31', INTERVAL 1 MONTH) // 2012-02-29 A: In the .NET framework the behavior of System.DateTime.AddMonths is as follows: The AddMonths method calculates the resulting month and year, taking into account leap years and the number of days in a month, then adjusts the day part of the resulting DateTime object. If the resulting day is not a valid day in the resulting month, the last valid day of the resulting month is used. For example, March 31st + 1 month = April 30th [rather than April 31st]. I've tested how it works exactly: Console.WriteLine(new DateTime(2008,2,27).AddMonths(1)); Console.WriteLine(new DateTime(2008,2,28).AddMonths(1)); Console.WriteLine(new DateTime(2008,2,29).AddMonths(1)); Console.WriteLine(new DateTime(2011,2,27).AddMonths(1)); Console.WriteLine(new DateTime(2011,2,28).AddMonths(1)); Console.WriteLine(new DateTime(2008,1,30).AddMonths(1)); Console.WriteLine(new DateTime(2008,1,31).AddMonths(1)); Console.WriteLine(new DateTime(2011,1,30).AddMonths(1)); Console.WriteLine(new DateTime(2011,1,31).AddMonths(1)); /* output 3/27/2008 12:00:00 AM 3/28/2008 12:00:00 AM 3/29/2008 12:00:00 AM 3/27/2011 12:00:00 AM 3/28/2011 12:00:00 AM 2/29/2008 12:00:00 AM 2/29/2008 12:00:00 AM 2/28/2011 12:00:00 AM 2/28/2011 12:00:00 AM */
{ "language": "en", "url": "https://stackoverflow.com/questions/7614361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Can't find jsp on eclipse I am using the last version of Eclipse 3.7. I am working with the Google app engine and need to create some JSP, but on a new project. I can't find JSP. I don't have Tomcat. Can I just do new->file and then just end it with .jsp, like filename.jsp? Will it be okay? A: I'm not familiar with Google App Engine, but to have ability to run project with JSP files you should create a web project. I don't know which plugin in eclise you're using, but this tutorial looks easy, try it: * *Select the File menu > New > Web Application Project *The "Create a Web Application Project" wizard opens. For "Project name," enter a name for your project, *If you're not using Google Web Toolkit, uncheck "Use Google Web Toolkit." Verify that "Use Google App Engine" is checked. *If you installed the App Engine SDK using Software Update, the plugin is already configured to use the SDKs that were installed. If you would like to use a separate installation of the App Engine SDK, click Configure SDKs..., and follow the prompts to add a configuration with your SDK's appengine-java-sdk/ directory. *Click Finish to create the project. A: Create a file with a .jsp extension in your war directory (or a non-WEB-INF/ subdirectory). Works fine. (I'm using Eclipse 3.6 with SDK 1.5.4.) A: To use JSP, you need to download the J2EE SDK from Oracle and the Eclipse IDE For EE Developers in order to access JSP pages from Eclipse. See Eclipse Docs, Eclipse Web Tools, and this forum post. There's a wealth of information out there. To develop and test locally, you will need a web server, such as Apache's Tomcat or JBOSS, both of which are available for free. Otherwise, you'd have to upload the file to Google App Engine, look at it, debug it, take it down, and repeat the process until you're done development. A: I had to install Eclipse Web Developer Tools (3.15) and the jsp file type was visible. Just open the Eclipse Marketplace from Eclipse and find this extension.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript Code not working when on my site I recently installed a code on my website to insert text at the position of the cursor. It works perfectly when on its own: http://www.penpalparade.com/test.php It isn't however working with my site as a whole: http://www.penpalparade.com/jobs.php I've tried to fix it but have been unsuccessful, could someone please please help me at solving it because I've been at it for hours. A: Firebug is showing several errors. $(".tooltipbox a[title]").tooltip is not a function jQuery("textarea[class*=expand]").TextAreaExpander is not a function "NetworkError: 404 Not Found - http://www.penpalparade.com/css/images/img02.jpg" This code is referenced before jQuery: <a href="javascript:;" onclick='$("#message").insertAtCaret("*****");'>*****</a> To get it out the door move your jquery src reference to the top (in the head tag). Or to do it correctly. Just above your closing body tag: $(document).ready(function() { $("#whatever").click(function() { $("#message").insertAtCaret("*****"); }); }); Change your Html to: <a id="whatever" href="">*****</a> This allows you to separate the behavior from the content.
{ "language": "en", "url": "https://stackoverflow.com/questions/7614373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }