text
stringlengths
8
267k
meta
dict
Q: Do you need shebang in all bash scripts? Suppose you have a bash script B, that you are sourcing from another bash script A. B has a bunch of variable and function definitions. A is the main driver script. Do you need the #!/bin/bash line on top of both A and B? What happens if you do and if you don't? A: The shebang is only mandatory for those scripts which shall be executed by the operating system in the same way as binary executables. If you source in another script, then the shebang is ignored. On the other hand. IF a script is supposed to be sourced, then it is convention to NOT put any shebang at the start. A: You should use shebang in all scripts especially those using any non-sh compatible features. In Debian for example, default shell is dash (not bash). If you use bash-only feature and don't specify that this script should be interpreted by bash it may fail even on linux. It will fail on Solaris or HP-UX almost for sure. If your file is to be only sources by other script, then you can omit shebang line but do not set executable permission. Also for such files is good to keep /bin/sh compatibility. I strongly recommend to read DashAsBinSh. A: The shebang is used if you run the script directly as an executable file (for example with the command ./script.sh). In this case it tells the operating system which executable to run. It's not required and has no effect if you for example write bash ./script.sh or source the script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: getResource with parent directory reference I have a java app where I'm trying to load a text file that will be included in the jar. When I do getClass().getResource("/a/b/c/"), it's able to create the URL for that path and I can print it out and everything looks fine. However, if I try getClass().getResource(/a/b/../"), then I get a null URL back. It seems to not like the .. in the path. Anyone see what I'm doing wrong? I can post more code if it would be helpful. A: The normalize() methods (there are four of them) in the FilenameUtils class could help you. It's in the Apache Commons IO library. final String name = "/a/b/../"; final String normalizedName = FilenameUtils.normalize(name, true); // "/a/" getClass().getResource(normalizedName); A: The path you specify in getResource() is not a file system path and can not be resolved canonically in the same way as paths are resolved by File object (and its ilk). Can I take it that you are trying to read a resource relative to another path?
{ "language": "en", "url": "https://stackoverflow.com/questions/7615432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Create your own wurfl exception I am using php wurfl 1.3.1 with cakephp - The following user agent is being picked up as a mobile browser which is incorrect. It is on a windows 7 machine, the 64 bit version of IE has no problem but the 32 bit version redirects to mobile. (32 bit)[PROBLEM] Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GetMiroToolbar 1.2; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2) (64 bit) Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0) If you do have a fix for me, please also let me know the proper steps to making sure the server reads the new configs properly. Do I just clear the WURFL cache? Thank you. A: in web_browsers_patch.xml I added the following line : <device user_agent="Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GetMiroToolbar 1.2; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2)" fall_back="msie" id="msie_8"> <group id="product_info"> <capability name="model_name" value="8.0" /> </group> </device>
{ "language": "en", "url": "https://stackoverflow.com/questions/7615437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using boost::asio to find all reachable ips on a subnet I would like a way to use boost to find all reachable ips(responding to a ping) on a subnet. i.e. given subnet = 10.10.10.0 and ips 10.10.10.1-5 that are reachable, the result should be a list: 10.10.10.1 , ... , 10.10.10.5 Currently I have a script that pings the subnet and checks the arp cache for reachable ips. A: They have a ping example in the docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to apply styles to the value of a form field? I have a form input tag with some text assigned to its value attribute: <input type="text" name="firstName" value="First Name*" /> Since this is a required field, how do I style the asterisk at the end of the "First Name*" string to be the color red? Is this even possible?... How do you style the values of pre-populated form fields? Thank you. A: I think you're making this more complicated then it should. There may be a way using javascript or jquery but I think that's overkill. I would just put it on the outside of the box and style it within a <span> tag. A: I don't think you can style one character to be red but you could style the whole string to be red. What I would probably do is set the asterisk outside the input box and style it like this <input ...value="FirstName"><span style="color: #FF0000;">*</span> A: No, it's impossible. You'd have to fake it. However, that's what <label>s are for!! <label>First Name* <input name=firstName required></label> A: Even if it would be possible, it'd not be a good practice. Data should always be separated from the representation. You don't want anything else but the data that you really need to be posted. It'd be a good idea to go with the jQuery solution that simply assigns a class to the input field on post if there's an error, e.g. makes the text inside the input red, draws the red border around the input box etc. A: If you're using asp .net why not just use the required field validator control and let it do the work for you. A: Instead of adding * to the field, I would suggest signifying the required field by modifying the element's styling through CSS and jQuery/JavaScript. Working example: http://jsfiddle.net/wstGQ/ CSS: input { color: #ccc; } .required { color: #FF0000; border: 1px solid #FF0000; } jQuery: $('input').focus(function(){ var obj= $(this); var oldVal = obj.val(); obj.blur(function(){ if(obj.val() == oldVal){ obj.val('Please enter a valid option').addClass('required'); }else{ obj.removeClass('required'); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7615445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Runtime Error: failed to connect to camera service in android I wanted to make use of the zxing library to detect qrcodes in my app. But for the apps viewing purpose, i had to change the custom display orientation to portrait. Hence i had to integrate the whole zxing library into my app and addded camera.setDisplayOrientation(90) to the openDriver() method. After doing this, the program works, but I get "Runtime exceptions : Fail to connect to camera service" randomly. public void openDriver(SurfaceHolder holder) throws IOException { if (camera == null) { camera = Camera.open(); camera.setDisplayOrientation(90); if (camera == null) { throw new IOException(); } } camera.setPreviewDisplay(holder); if (!initialized) { initialized = true; configManager.initFromCameraParameters(camera); } configManager.setDesiredCameraParameters(camera); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); reverseImage = prefs.getBoolean(PreferencesActivity.KEY_REVERSE_IMAGE, false); if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) { FlashlightManager.enableFlashlight(); } } public void closeDriver() { if (camera != null) { FlashlightManager.disableFlashlight(); camera.release(); camera = null; framingRect = null; framingRectInPreview = null; } } /** * Asks the camera hardware to begin drawing preview frames to the screen. */ public void startPreview() { if (camera != null && !previewing) { camera.startPreview(); previewing = true; } } /** * Tells the camera to stop drawing preview frames. */ public void stopPreview() { if (camera != null && previewing) { if (!useOneShotPreviewCallback) { camera.setPreviewCallback(null); } camera.stopPreview(); previewCallback.setHandler(null, 0); autoFocusCallback.setHandler(null, 0); previewing = false; } } A: I doubt that the orientation change is causing that. I have found you will get that error whenever an activity stops but fails to call Camera.release in their onPause. The result is that the next time you try to do Camera.open you get that runtime error since the driver still considers it open regardless of the app/activity that opened it being gone. You can easily get this to happen while debugging/testing stuff when something throws an exception and brings the activity down. You need to be very diligent about catching all exceptions and being sure to release the camera before finishing the activity. BTW, are you finding you need to power cycle the device in order to be able to open the camera again?
{ "language": "en", "url": "https://stackoverflow.com/questions/7615446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting a row from a data frame as a vector in R I know that to get a row from a data frame in R, we can do this: data[row,] where row is an integer. But that spits out an ugly looking data structure where every column is labeled with the names of the column names. How can I just get it a row as a list of value? A: There is a problem with what you propose; namely that the components of data frames (what you call columns) can be of different data types. If you want a single row as a vector, that must contain only a single data type - they are atomic vectors! Here is an example: > set.seed(2) > dat <- data.frame(A = 1:10, B = sample(LETTERS[1:4], 10, replace = TRUE)) > dat A B 1 1 A 2 2 C 3 3 C 4 4 A 5 5 D 6 6 D 7 7 A 8 8 D 9 9 B 10 10 C > dat[1, ] A B 1 1 A If we force it to drop the empty (column), the only recourse for R is to convert the row to a list to maintain the disparate data types. > dat[1, , drop = TRUE] $A [1] 1 $B [1] A Levels: A B C D The only logical solution to this it to get the data frame into a common type by coercing it to a matrix. This is done via data.matrix() for example: > mat <- data.matrix(dat) > mat[1,] A B 1 1 data.matrix() converts factors to their internal numeric codes. The above allows the first row to be extracted as a vector. However, if you have character data in the data frame, the only recourse will be to create a character matrix, which may or may not be useful, and data.matrix() now can't be used, we need as.matrix() instead: > dat$String <- LETTERS[1:10] > str(dat) 'data.frame': 10 obs. of 3 variables: $ A : int 1 2 3 4 5 6 7 8 9 10 $ B : Factor w/ 4 levels "A","B","C","D": 1 3 3 1 4 4 1 4 2 3 $ String: chr "A" "B" "C" "D" ... > mat <- data.matrix(dat) Warning message: NAs introduced by coercion > mat A B String [1,] 1 1 NA [2,] 2 3 NA [3,] 3 3 NA [4,] 4 1 NA [5,] 5 4 NA [6,] 6 4 NA [7,] 7 1 NA [8,] 8 4 NA [9,] 9 2 NA [10,] 10 3 NA > mat <- as.matrix(dat) > mat A B String [1,] " 1" "A" "A" [2,] " 2" "C" "B" [3,] " 3" "C" "C" [4,] " 4" "A" "D" [5,] " 5" "D" "E" [6,] " 6" "D" "F" [7,] " 7" "A" "G" [8,] " 8" "D" "H" [9,] " 9" "B" "I" [10,] "10" "C" "J" > mat[1, ] A B String " 1" "A" "A" > class(mat[1, ]) [1] "character" A: Data.frames created by importing data from a external source will have their data transformed to factors by default. If you do not want this set stringsAsFactors=FALSE In this case to extract a row or a column as a vector you need to do something like this: as.numeric(as.vector(DF[1,])) or like this as.character(as.vector(DF[1,])) A: How about this? library(tidyverse) dat <- as_tibble(iris) pulled_row <- dat %>% slice(3) %>% flatten_chr() If you know all the values are same type, then use flatten_xxx. Otherwise, I think flatten_chr() is safer. A: You can't necessarily get it as a vector because each column might have a different mode. You might have numerics in one column and characters in the next. If you know the mode of the whole row, or can convert to the same type, you can use the mode's conversion function (for example, as.numeric()) to convert to a vector. For example: > state.x77[1,] Population Income Illiteracy Life Exp Murder HS Grad Frost 3615.00 3624.00 2.10 69.05 15.10 41.30 20.00 Area 50708.00 > as.numeric(state.x77[1,]) [1] 3615.00 3624.00 2.10 69.05 15.10 41.30 20.00 50708.00 This would work even if some of the columns were integers, although they would be converted to numeric floating-point numbers. A: As user "Reinstate Monica" notes, this problem has two parts: * *A data frame will often have different data types in each column that need to be coerced to character strings. *Even after coercing the columns to character format, the data.frame "shell" needs to stripped-off to create a vector via a command like unlist. With a combination of dplyr and base R this can be done in two lines. First, mutate_all converts all columns to character format. Second, the unlist commands extracts the vector out of the data.frame structure. My particular issue was that the second line of a csv included the actual column names. So, I wanted to extract the second row to a vector and use that to assign column names. The following worked to extract the row as a character vector: library(dplyr) data_col_names <- data[2, ] %>% mutate_all(as.character) %>% unlist(., use.names=FALSE) # example of using extracted row to rename cols names(data) <- data_col_names # only for this example, you'd want to remove row 2 # data <- data[-2, ] (Note: Using as.character() in place of unlist will work too but it's less intuitive to apply as.character twice.) A: I see that the most short variant is c(t(data[row,])) However if at least one column in data is a column of strings, so it will return string vector.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: get user name asp.net windows auth SO i made a simple web form, set in windows auth in iis. then i deployed it on my server and i try to log in. it prompts me a login box, i enter my infos, looks likes its working fine with active directory. if i enter something wrong it wont work etc. obviously i need to know who is the logged on user Response.Write(HttpContext.Current.User.Identity.Name.ToString()); i found this in other threads, but it wont work for me... how do i get the info filled in the login box ? A: If you using asp.net membership provider you can get the current logged user System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); User.Identity.IsAuthenticated can be used to identify whether user successfully logged in or not A: <identity impersonate="true" /> in web config , fixed my problem. http://msdn.microsoft.com/en-us/library/ff647076.aspx helped me. thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EXC BAD ACCESS POINT error HI I'm trying to create a list an app for favorites list that you save in a mutable array which then gets saved as a user defaults but I keep getting bad access point errors either when i click on a cell or if I go to another view and then go back to this view please help this is my code - (void)viewDidLoad { [super viewDidLoad]; listOfItems=[[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"favorites"]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation==UIInterfaceOrientationPortrait); } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc. that aren't in use. } -(void)viewWillAppear:(BOOL)animated { //Save mutable array and save to table set. listOfItems=[[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"favorites"]; [self.tableView reloadData]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [super dealloc]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [listOfItems count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... NSString *cellValue = [listOfItems objectAtIndex:indexPath.row]; cell.textLabel.text = cellValue; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self presentModalViewController:deffinitionviewController animated:YES]; } please help A: You should retain listOfItems: if(listOfItems) [listOfItems release]; // use this so it doesn't leak (also remember to release it in dealloc) listOfItems=[[[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:@"favorites"] retain];
{ "language": "en", "url": "https://stackoverflow.com/questions/7615459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a new workbook and copying worksheets over The problem in question centers around one workbook which contains all of my data and breakdowns spread across a ton of worksheets. I'm trying to get macros set up to copy select sheets to a new workbook. I think my biggest problem is getting the coding right for the destination workbook since the name includes a date string that changes each day. The code that I've got so far to just create the new workbook and close it is: Sub NewReport() Application.ScreenUpdating = False Application.DisplayAlerts = False MyDate = Date Dim dateStr As String dateStr = Format(MyDate, "MM-DD-YY") Set W = Application.Workbooks.Add W.SaveAs Filename:="N:\PAR\" & "New Report Name" & " " & dateStr, FileFormat:=51 Application.ScreenUpdating = True Application.DisplayAlerts = True ActiveWorkbook.Close True End Sub This works and does what I want in regards to creating the new document, naming it the way it should be named, and at the end closing it. What I need help with is that middle portion for copying specific sheets from the original workbook to this new one. What I was thinking was along the lines of: With Workbooks("Original Workbook.xlsm") .Sheets(Array("Sheet1", "Sheet2")).Copy_ Before:=Workbooks("destination.xls").Sheet1 Or at least some type of array to get exactly what I want to copy over. The biggest sticking point is getting the destination workbook path name correct. Any advice regarding individual pieces of this little project or on the whole is greatly appreciated. Thanks! EDIT: I also need to point out that the new workbook being generated needs to be just plain old excel format (.xlsx). No macros, no security warning for automatic updating links or enabling macros, zip. Just a plain book of the sheets I tell it to put there. A: Ok. I finally got it working now. Sheet names are carried over (otherwise I would have to go behind and rename them); it saves one copy to be sent and one copy to our archive folder; and the new workbooks don't get any popup about enabling macros or updating links. The code I finally settled on (which could probably be trimmed a little) is: Sub Report() Dim Wb1 As Workbook Dim dateStr As String Dim myDate As Date Dim Links As Variant Dim i As Integer With Application .ScreenUpdating = False .DisplayAlerts = False .EnableEvents = False End With Set Wb1 = ActiveWorkbook myDate = Date dateStr = Format(myDate, "MM-DD-YYYY") Wb1.Sheets(Array("Sheet1Name", "Sheet2Name", "etc."))Copy With ActiveWorkbook Links = .LinkSources(xlExcelLinks) If Not IsEmpty(Links) Then For i = 1 To UBound(Links) .BreakLink Links(i), xlLinkTypeExcelLinks Next i End If End With ActiveWorkbook.SaveAs Filename:="N:\" & "Report Name" & " " & dateStr, FileFormat:=51 ActiveWorkbook.SaveAs Filename:="N:\Report Archive\" & "Report Name" & " " & dateStr, FileFormat:=51 ActiveWorkbook.Close With Application .ScreenUpdating = True .DisplayAlerts = True .EnableEvents = True End With End Sub Hope that'll help someone else with the same issue! A: Your copy line should be Workbooks("Original Workbook.xlsm").Sheets(Array("Sheet1", "Sheet2")).Copy _ Before:=W.Sheets(1) A: You can make your code fully variable rather than harcoding "Orginal Workbook.xlsm" and the Sheet1 and Sheet2 names If you use two Workbook variables then you can set the ActiveWorbook (ie the one currently selected in Excel) as the workbook to be copied (alternatively you can set it to a closed workbook, existing open named workbook, or the workbook that contains the code). With a standard Application.Workbooks.Add you will get a new workbook with the number of sheets installed as per your default option (normnally 3 sheets) By specifying Application.Workbooks.Add(1) a new workbook is created with only one sheet And note I disabled macros by setting EnableEvents to False but it would be unusual to have application events running when creating workbooks Then when copying the sheet use Sheets(Array(Wb1.Sheets(1).Name, Wb1.Sheets(2).Name)).Copy 'rather than Sheets(Array("Sheet1", "Sheet2")).Copy to avoid hardcoding the sheet names to be copied. This code will copy the two leftmoast sheets irrespective of naming Lastly the initial single sheet is removed leaving you with a new file with only the two copied sheets inside Sub NewReport() Dim Wb1 As Workbook Dim Wb2 As Workbook Dim dateStr As String Dim myDate As Date With Application .ScreenUpdating = False .DisplayAlerts = False .EnableEvents = False End With Set Wb1 = ActiveWorkbook myDate = Date dateStr = Format(myDate, "MM-DD-YY") Set Wb2 = Application.Workbooks.Add(1) Wb1.Sheets(Array(Wb1.Sheets(1).Name, Wb1.Sheets(2).Name)).Copy Before:=Wb2.Sheets(1) Wb2.Sheets(Wb2.Sheets.Count).Delete Wb2.SaveAs Filename:="c:\test\" & "New Report Name" & " " & dateStr, FileFormat:=51 Wb2.Close With Application .ScreenUpdating = True .DisplayAlerts = True .EnableEvents = True End With End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7615466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: .htaccess file problems So I have a Joomla instance which is sitting in my ROOT directory. I have a Wordpress Multi-site installation sitting in the subdirectory /blog. It seems like the server is having a hard time finding or getting sites in the /blog directory. Seems like it gets to the main /blog page fine but if I want to go to /blog/{sitename}, sitename being an instance of the Wordpress Mulitsite, it has a hard time getting there. Probably complicating matters is that I have Fancy URLs on both the Joomla instance as well as the Wordpress Multisite instance. Both .htaccess files for Joomla and Wordpress Multisite are from stock installs of their respective applications (I'm 99% sure). I'm going to post them here and see if anyone can see possible conflicts in the .htaccess Joomla .htaccess with core SEF version $Id: htaccess.txt 21064 2011-04-03 22:12:19Z dextercowley $ RewriteEngine On RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR] RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR] RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR] RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR] RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) RewriteRule .* index.php [F] RewriteBase / RewriteCond %{REQUEST_URI} !^/index\.php RewriteCond %{REQUEST_URI} (/[^.]*|\.(php|html?|feed|pdf|raw))$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php [L] END Joomla .htaccess Now I have added this to the Joomla .htaccess file in hopes that it would not use SEF on the /blog folder but it doesn't seem to work. I am trying to exclude the blog directory from the top level .htaccess and just let the /blog .htaccess take over control of that subdirectory. #RewriteCond %{REQUEST_URI} ^/blog/.*$ #RewriteRule ^.*$ - [L] And here is my Wordpress .htaccess RewriteEngine On RewriteBase /blog/ RewriteRule ^index\.php$ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] Everything on the top level domain (Joomla) runs very fast when pages are requested. The server eventually finds the /blog directory but it takes more time than it should. The really big problem is that when i go to one of the blog sites (/blog/sitename) it can take upwards of 8-10 seconds. And then once the page loads and I go to another page on that /blog/sitename like "About" it can take about the same amount of time. Overall very frustrating. Any help is appreciated. I've been googling for awhile and have not found much help besides #RewriteCond %{REQUEST_URI} ^/blog/.*$ #RewriteRule ^.*$ - [L] And it has not helped the problem. It seems like all the sites in the /blog directory are very slow to get to. I have about 6 in there and they are all very slow loading. A: Well, I'm not sure if you're developing locally but one thing you could try would be to place all the Joomla files in their own directory and use .htaccess to resolve the site correctly - then you shouldn't have the Joomla .htaccess affecting your /blog directory. Just a consideration. I'm not sure that it would resolve the issue entirely but at least then you could separate out the issue of 'is the Joomla .htaccess conflicting with the Wordpress .htacceess and causing a slowdown'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: caputre OpenGL window in X11 with fast framerate - possible? I have an OpenGL application with the size of 800x600 running on my linux machine (X11). The content of this application (the rendered image) should be exported via network to another PC. First of all, i want to know if it is possible to take snapshots of the applications window with about 30 Hz, save them to jpeg and export them to the other machine via HTTP or whatever (like the IP Cameras are doing). Is it possbile to read the graphic's cards memory (Radeon HD 5800) in a fast way so that i can get a framerate of about 30 pictures per second? A: If you're willing to tolerate some latency Pixel Buffer Objects (PBOs) should get you some decent read-back throughput. libjpeg-turbo looks like a good solution for high-speed JPEG encoding. If you don't have the source to the app you're trying to monitor then LD_PRELOAD hacks combined with the above should work. A: You may want to take a look at VirtualGL which does exactly what you aim for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Data Structure - Inserting/Updating into ordered list I'm using the facebook api to retrieve a list of a user's photos. I'm using this to work out the user's close friends by seeing who has been tagged the most in the user's photos. So what I have the list of the tagged users (there will be duplicates). What I want to do is go through each tag and insert the user into a data structure. If the user is already there I want to increase that user's count by one. At the end I want the list ordered so I can 'rank' the friends. What data structure will be best for this? A: Step 1: Use an associative container. Map from UserId to user's count. Keep adding new users, and updating the user's count as you process more data. Step2: Copy all the users to another associative container, Now the key should be a pair(user's count, UserId). You can now iterate over the 2nd container and have your items in order. If you're using C++, you can use map for step 1, and set for step 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call action when select noSelectionLabel? I have this code above which works perfectly when i select some of the items on him... The a4j:support works fine and rerender my another field correctly... The problem is if i choose one item, and then i back to "noSelectionLabel"... When i do this for some reason my a4j:support dont work, i dont get into my method "setarFormulario" and i dont rerender my another field... <s:decorate template="layout/form.xhtml"> <ui:define name="label">Evento:</ui:define> <h:selectOneMenu value="#{home.instance.evento}" required="true"> <s:selectItems value="#{eventoService.obterTodos()}" var="evento" label="#{messages[evento.nome]}" noSelectionLabel="#{messages['br.com.message.NoSelection']}" /> <s:convertEntity /> <a4j:support event="onchange" action="#{home.setarFormulario}" reRender="camposFormulario" ajaxSingle="true" /> </h:selectOneMenu> </s:decorate> How can i get into my method even if i select the noSelectionLabel? Then my home.instance.evento must be null.. or something like this... A: Yor field h:selectOneMenu is required then selecting noSelectionLabel value will cause a validation error and if you had validation error, then the action="#{home.setarFormulario}" would never be called. As a workaround you can set to true the attribute hideNoSelectionLabel for your s:selectItems then the noSelectionLabel will be hidden when a value is selected A: <h:message for="id of the selectonemenu component " ></h:message> or remove the required =true from the selectonemenu tag
{ "language": "en", "url": "https://stackoverflow.com/questions/7615490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone 7 ScrollView? Is there a scrollView in phone7? I have this code private void button8_Click(object sender, RoutedEventArgs e) { for (int i=0; i<23; i++) { Button btn = new Button() { Content="newbutton "+i, HorizontalAlignment =HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(0, 20+(i*60), 0, 0), }; btn.Click += new RoutedEventHandler(btn_click); ContentPanel.Children.Add(btn); } } to add 23 buttons to my screen, what is the way to scrolling down the page to show all of the 23 buttons? A: I'm assuming ContentPanel is a StackPanel. In XAML: <ScrollViewer> <StackPanel x:Name="ContentPanel" /> </ScrollViewer> You can use the ScrollViewer.ScrollToVerticalOffset method to scroll to the end of the page. However, if you have other UIElements above the ScrollViewer those will still occupy the top of your screen with only the section occupied by the ScrollViewer being scrolled. To prevent that you'll have to have all the UIElements, including ContentPanel, be placed in the ScrollViewer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iTextSharp HTML to PDF preserving spaces I am using the FreeTextBox.dll to get user input, and storing that information in HTML format in the database. A samle of the user's input is the below:                                                                      133 Peachtree St NE                                                                     Atlanta,  GA 30303                                                                     404-652-7777                                                                      Cindy Cooley                                                                     www.somecompany.com                                                                     Product Stewardship Mgr                                                                     9/9/2011Deidre's Company123 Test StAtlanta, GA 30303Test test.   I want the HTMLWorker to perserve the white spaces the users enters, but it strips it out. Is there a way to perserve the user's white space? Below is an example of how I am creating my PDF document. Public Shared Sub CreatePreviewPDF(ByVal vsHTML As String, ByVal vsFileName As String) Dim output As New MemoryStream() Dim oDocument As New Document(PageSize.LETTER) Dim writer As PdfWriter = PdfWriter.GetInstance(oDocument, output) Dim oFont As New Font(Font.FontFamily.TIMES_ROMAN, 8, Font.NORMAL, BaseColor.BLACK) Using output Using writer Using oDocument oDocument.Open() Using sr As New StringReader(vsHTML) Using worker As New html.simpleparser.HTMLWorker(oDocument) worker.StartDocument() worker.SetInsidePRE(True) worker.Parse(sr) worker.EndDocument() worker.Close() oDocument.Close() End Using End Using HttpContext.Current.Response.ContentType = "application/pdf" HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}.pdf", vsFileName)) HttpContext.Current.Response.BinaryWrite(output.ToArray()) HttpContext.Current.Response.End() End Using End Using output.Close() End Using End Sub A: There's a glitch in iText and iTextSharp but you can fix it pretty easily if you don't mind downloading the source and recompiling it. You need to make a change to two files. Any changes I've made are commented inline in the code. Line numbers are based on the 5.1.2.0 code rev 240 The first is in iTextSharp.text.html.HtmlUtilities.cs. Look for the function EliminateWhiteSpace at line 249 and change it to: public static String EliminateWhiteSpace(String content) { // multiple spaces are reduced to one, // newlines are treated as spaces, // tabs, carriage returns are ignored. StringBuilder buf = new StringBuilder(); int len = content.Length; char character; bool newline = false; bool space = false;//Detect whether we have written at least one space already for (int i = 0; i < len; i++) { switch (character = content[i]) { case ' ': if (!newline && !space) {//If we are not at a new line AND ALSO did not just append a space buf.Append(character); space = true; //flag that we just wrote a space } break; case '\n': if (i > 0) { newline = true; buf.Append(' '); } break; case '\r': break; case '\t': break; default: newline = false; space = false; //reset flag buf.Append(character); break; } } return buf.ToString(); } The second change is in iTextSharp.text.xml.simpleparser.SimpleXMLParser.cs. In the function Go at line 185 change line 248 to: if (html /*&& nowhite*/) {//removed the nowhite check from here because that should be handled by the HTML parser later, not the XML parser A: Thanks for the help everyone. I was able to find a small work around by doing the following: vsHTML.Replace(" ", "&nbsp;&nbsp;").Replace(Chr(9), "&nbsp;&nbsp;&nbsp;&nbsp;").Replace(Chr(160), "&nbsp;").Replace(vbCrLf, "<br />") The actual code does not display properly but, the first replace is replacing white spaces with &nbsp;, Chr(9) with 5 &nbsp;, and Chr(160) with &nbsp;. A: I would recommend using wkhtmltopdf instead of iText. wkhtmltopdf will output the html exactly as rendered by webkit (Google Chrome, Safari) instead of iText's conversion. It is just a binary that you can call. That being said, I might check the html to ensure that there are paragraphs and/or line breaks in the user input. They might be stripped out before the conversion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Kohana config database - enabling I can't make to Config_Database work. I'm enabling new Config Source that way: Kohana::$config->attach(new Config_Database, FALSE); I'm loading that source after loading modules - in the bottom of bootstrap.php file. I get this error when I'm trying to enable this Config Source Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 261900 bytes) in /var/www/moje/modules/database/classes/kohana/config/database/writer.php on line 124 Line 124 in file (.../)database/writer.php doesnt exists - it has only 111 lines. What's going wrong? edit: Kohana 3.2 A: This sounds like a bug in 3.2 I have got it to work with 3.0 (haven't tried 3.1). Here's the thread in Kohana Forums: http://forum.kohanaframework.org/discussion/9637/config_database-and-the-out-of-memory-error/p1 A: It's going because Kohana trying to load database settings from database (and it's going to recursion) You should initialize your database instance before attaching Config_Database reader Try this (in bootstrap.php, after Kohana::modules()): Database::instance(); Kohana::$config->attach(new Config_Database, FALSE); A: Or you can simply load database config right before adding the Config_Database Kohana::$config->load('database'); Kohana::$config->attach(new Config_Database, FALSE);
{ "language": "en", "url": "https://stackoverflow.com/questions/7615498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Youtube views not registering through Facebook Youtube does not count views when videos are autoplayed, i.e. when they have the parameter autoplay=1 at the end of the url like this: http://www.youtube.com/watch?v=4r7wHMg5Yjg&autoplay=1 now when the videos are embedded inside facebook the code is: <embed width="398" height="224" flashvars="width=398&amp;height=224" wmode="opaque" salign="tl" allowscriptaccess="never" allowfullscreen="true" scale="scale" quality="high" bgcolor="#FFFFFF" name="swf_u285641_8" id="swf_u285641_8" style="" src="http://www.youtube.com/v/TxzVGR5U4Lc?version=3&amp;autohide=1&amp;autoplay=1" type="application/x-shockwave-flash"> because of this the views when a user shares on their facebook does not get counted properly. This has huge marketing ramifications, as youtube views are very important to grow organically, and facebook is definately the biggest medium of word of mouth. This problem has been confirmed by a Google Employee, so is facebook working on something to rectify this? A: Interesting. I guess the makeshift solution is to post a screen shot with a link to youtube or your page as long as autoplay=0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with color fillling in SSRS I have a calendar table with data based on some conditions. The color gets filled only in the boxes where there is data and the empty boxes are not colored. How do I get all the boxes colored irrespective of the data's presence? =IIf(DateDiff("d",Fields!EndofDate.Value, Fields!EndDate.Value) > 0 ,"White","Yellow") Please help!!! Thanks A: On the textbox properties of your date field, click on Fill, then click on the expression button next to Fill Color and enter the following expression: =IIF(IsNothing(Fields!EndofDate.Value),"White","Yellow") That will make all the fields with NULL values have a white background and all others have a yellow background. A: I have possibly another solution which you can try, instead of using a IsNothing you can use a Choose function E.g. =Choose(Fields!change.Value+1, "Gold", "Blue"....) So if there is no change instead of "Gold" you can just insert ""
{ "language": "en", "url": "https://stackoverflow.com/questions/7615503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing an object[] to parameter object[] is not working in Java I know this question is similar to passing a object[] to a params object[] not working however I am having a similar problem in Java. try { Object[] objSingleTableColumns = null; DatabaseActions db = new DatabaseActions(); db.dbConnect(sDatabase); for (int i=0 ; i < objTableList.length; i++) { objSingleTableColumns = db.dbShowColumns(objTableList[i].toString()); this.buildSingleModel(objTableList[i].toString(), sDatabase, objSingleTableColumns, false); } db.dbClose(); } catch (Exception e) { System.out.println("Error with Multiple Columns" + e); } I have a feeling the issue is being caused by passing a object which is inside an object but I am not sure how to fix this issue as I am still a bit new to Java.. I tried to do Object[] Casting but it did not seem to work. The error I get is java.lang.NullPointerException I have returned objSingleTableColumns using Arrays.toString(objSingleTableColumns) and it outputs the column lists as expected without an issue... To clarify what db.dbShowColumns() does it returns an object of database column names based on the table name provided. UPDATE: I tried initializing the array as @Mansuro suggested, but this did not work. I did a test run to get the output to maybe resolve this issue. Would it be possible that my code is creating a multidimensional array because I am passing an Object[] into another Object[]? If that's they case is there a way to merge the objects? Because I have ran this.buildSingleModel on its own and it works perfectly. This output is without running this.buildSingleModel objTableList = [glossary, messages, prodfeatures, renters, source, test_table] objTableList.length = 6 objSingleTableColumns = [gid, gname, gmeaning] objSingleTableColumns = [mid, msubject, mtype, mread, mcid, mmessage, mtimedate, mproduct, mstar] objSingleTableColumns = [fid, fpid, ftext, ftype, fsort, fonline] objSingleTableColumns = [rid, fname, lname, phone, email] objSingleTableColumns = [sid, sw] objSingleTableColumns = [tid, tname, tdesc] The code for the above output is: public void buildMultipleModels(String sDatabase, Object[] objTableList) { try { Object[] objSingleTableColumns = new Object[100]; DatabaseActions db = new DatabaseActions(); db.dbConnect(sDatabase); System.out.println("objTableList = " + Arrays.toString(objTableList)); System.out.println("objTableList.length = " + objTableList.length); for (int i=0 ; i < objTableList.length; i++) { objSingleTableColumns = db.dbShowColumns(objTableList[i].toString()); System.out.println("objSingleTableColumns = " + Arrays.deepToString(objSingleTableColumns)); // this.buildSingleModel(objTableList[i].toString(), sDatabase, objSingleTableColumns, false); } db.dbClose(); } catch (Exception e) { System.out.println("Error with Multiple Columns --> Exception =" + e); StringWriter sw = new StringWriter(); new Throwable("").printStackTrace(new PrintWriter(sw)); String stackTrace = sw.toString(); System.out.println("Stack trace = " + stackTrace); } } And this is the output when running this.buildSingleModel objTableList = [glossary, messages, prodfeatures, renters, source, test_table] objTableList.length = 6 objSingleTableColumns = [gid, gname, gmeaning] Error with Multiple Columns --> Exception =java.lang.NullPointerException Stack trace = java.lang.Throwable: at genModel.buildMultipleModels(genModel.java:170) at genModel.doBuildMultipleModels(genModel.java:67) at frmMain.btnGenerateMultipleModelsActionPerformed(frmMain.java:530) at frmMain.access$600(frmMain.java:44) at frmMain$7.actionPerformed(frmMain.java:322) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6267) at javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at java.awt.Component.processEvent(Component.java:6032) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4630) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2478) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) A: It seems that objSingleTableColumns may be null for one of the calls inside the for loop. Arrays.toString() accepts null so it may work fine. This is just guess as stack trace is not provided. A: You have to initialize the array objSingleTableColumns = new Object[ARRAY_SIZE];
{ "language": "en", "url": "https://stackoverflow.com/questions/7615506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to detect whether or not mobile device has location services enabled with JavaScript? I am currently using Modernizr to detect whether or not geolocation is supported for a particular device. However, I want to display a more specific error message if geolocation is supported, but the user has disabled location services for their device. I'm getting complaints that geolocation isn't working on supported browsers, when in fact it's just that the user hasn't enabled theirs. I know there are ways to detect this using native mobile code, but is there a way to do this with JavaScript? Does Modernizr support this? A: Does your error callback ever fire? If you don't have one, try adding one. If it never fires, you can set a timeout on your function that if it does not receive permission within a certain amount of time, to display a notification. Since the errorCallback never fires if geo is disabled, create a wrapper around the function that will create a settimeout on another function. If either of the callbacks to the api do fire, then remove the settimeout before it fires. var timeOutId; function disabledGeoHandler(){...} function show_map() { clearTimeout(timOutId); ... } function show_map_error() { clearTimeout(timOutId); ... } function lookup_location() { timeOutId = setTimeout(disabledGeoHandler, 1000); navigator.geolocation.getCurrentPosition(show_map, show_map_error); } In fact, you could just use geo.js
{ "language": "en", "url": "https://stackoverflow.com/questions/7615509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: INSERT statement will not let me use IF NOT EXISTS I have an insert statement that I can't get to work the way I want it to. It's on a vb.net page. This is on a VB.net page and I'm using SQL Server 2005 for my database. Dim strSQL As String = "IF NOT EXISTS (SELECT Title From Picklist) BEGIN INSERT INTO Picklist (Title, Data) VALUES (@Title, @Data); INSERT INTO Marketing (ProductID, MarketingTypeID, MarketingTitle, MarketingData) VALUES (@ProductID, 9, 'Video', scope_identity()) END" I don't get an error and nothing gets inserted into the database. If I try putting the END at the end of the first INSERT statement then I get an error saying that MarketingData is NULL and cannot be inserted. But if I take out the IF NOT EXISTS from the statement, everything gets inserted perfectly. What am I doing wrong here? UPDATE: Is it correct to write the statement like this? INSERT INTO Marketing SELECT (@ProductID, @MarketingTypeID, @MarketingTitle, @MarketingData) WHERE NOT EXISTS (SELECT * FROM Marketing) A: Your IF NOT EXISTS(SELECT * FROM Picklist) will skip the insert if any rows at all exist in Picklist. From your description of what happens when you change the position of the END it seems there are rows in the table. I assume in fact you are trying to do an UPSERT. What version of SQL Server are you on? If 2008 look into MERGE ;WITH Source(Title, Data) AS ( SELECT @Title, @Data ) MERGE Picklist AS T USING Source S ON (T.Title = S.Title) WHEN NOT MATCHED BY TARGET THEN INSERT (Title, Data) VALUES (@Title, @Data) ; IF (@@ROWCOUNT <> 0) INSERT INTO Marketing (ProductID, MarketingTypeID, MarketingTitle, MarketingData) VALUES (@ProductID, 9, 'Video', scope_identity())
{ "language": "en", "url": "https://stackoverflow.com/questions/7615510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Downloading a file into memory I am writing a python script and I just need the second line of a series of very small text files. I would like to extract this without saving the file to my harddrive as I currently do. I have found a few threads that reference the TempFile and StringIO modules but I was unable to make much sense of them. Currently I download all of the files and name them sequentially like 1.txt, 2.txt, etc, then go through all of them and extract the second line. I would like to open the file grab the line then move on to finding and opening and reading the next file. Here is what I do currently with writing it to my HDD: while (count4 <= num_files): file_p = [directory,str(count4),'.txt'] file_path = ''.join(file_p) cand_summary = string.strip(linecache.getline(file_path, 2)) linkFile = open('Summary.txt', 'a') linkFile.write(cand_summary) linkFile.write("\n") count4 = count4 + 1 linkFile.close() A: You open and close the output file in every iteration. Why not simply do with open("Summary.txt", "w") as linkfile: while (count4 <= num_files): file_p = [directory,str(count4),'.txt'] file_path = ''.join(file_p) cand_summary = linecache.getline(file_path, 2).strip() # string module is deprecated linkFile.write(cand_summary) linkFile.write("\n") count4 = count4 + 1 Also, linecache is probably not the right tool here since it's optimized for reading multiple lines from the same file, not the same line from multiple files. Instead, better do with open(file_path, "r") as infile: dummy = infile.readline() cand_summary = infile.readline.strip() Also, if you drop the strip() method, you don't have to re-add the \n, but who knows why you have that in there. Perhaps .lstrip() would be better? Finally, what's with the manual while loop? Why not use a for loop? Lastly, after your comment, I understand you want to put the result in a list instead of a file. OK. All in all: summary = [] for count in xrange(num_files): file_p = [directory,str(count),'.txt'] # or count+1, if you start at 1 file_path = ''.join(file_p) with open(file_path, "r") as infile: dummy = infile.readline() cand_summary = infile.readline().strip() summary.append(cand_summary) A: Just replace the file writing with a call to append() on a list. For example: summary = [] while (count4 <= num_files): file_p = [directory,str(count4),'.txt'] file_path = ''.join(file_p) cand_summary = string.strip(linecache.getline(file_path, 2)) summary.append(cand_summary) count4 = count4 + 1 As an aside you would normally write count += 1. Also it looks like count4 uses 1-based indexing. That seems pretty unusual for Python.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AJAX Function issues I use a function to post result via Ajax. When I test to see if the function was called I add an alert. Everything works fine, but as soon as I remove alert my results are not posted... What's causing it? function SendInvitesF(invType, invWho, projID) { $.ajax({ url: "ajax.php", type: POST", data: "op=sendInvites&inviteMsgType="+invType+"&invitees="+invWho+"&proj="+projID }); alert("test "+projID) // test alert <<< } $("#btnSend").click(function() { if($("#customMsg").attr("checked")) { var invType = "custom"; } else { var invType = "default"; } var invWho = $(".radioB:checked").val(); var projID = $("#testID").val(); SendInvitesF(invType, invWho, projID); }); A: I suspect that you are calling this function in the onclick or onsubmit event and you are not canceling the default action by returning false. Also you are not properly url encoding any of your parameters. To do this use the data hash: function SendInvitesF(invType, invWho, projID) { $.ajax({ url: 'ajax.php', type: 'POST', data: { op: 'sendInvites', inviteMsgType: invType, invitees: invWho, proj: projID }); return false; } and then if you are calling this inside the onclick of an anchor: // I guess btnSend is a submit button or an anchor so make sure // you cancel the default action by returning false from the click // callback $('#btnSend').click(function() { if ($('#customMsg').attr('checked')) { var invType = 'custom'; } else { var invType = 'default'; } var invWho = $('.radioB:checked').val(); var projID = $('#testID').val(); return SendInvitesF(invType, invWho, projID); }); Notice how we are returning false and thus canceling the default action which would be a redirect and of course not leaving the time for the AJAX request to execute. When you put an alert at the end of the function this stops any script execution and the AJAX call has the time to hit the server. A: Have you tried to add the alert on the success handler? to make sure that the ajax call actually went trough successfully? also, like Darin maybe you used on a onClick and forgot to cancel the default action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Playing fullscreen .mp4 video in MPMoviePlayerController? So I'm trying to play a movie in my tab-navigation bar app. Although its portrait mode, I'd like to play the movie in full screen landscape after pressing a button. Is there some way to present the movie in a modal view controller? Or is it unnecessary? Could someone please post some code or point me into the right direction? I already tried some code but I just couldn't get it working. I'm sure the video is the right format. Thanks a lot in advance!! A: The correct way is to use the MPMoviePlayerViewController in my case...
{ "language": "en", "url": "https://stackoverflow.com/questions/7615531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python screen scrape whole website I want to make a little program which will use every single something-meaning word from any website It's meant to be in python and I've heard about BeautifulSoup but I don't quite know how to use it for this purpose... little tutorial? :p Or is it just that easy as a regex? like: re.compile('<.*>(.*)<.*>') so everything between the brackets? Newlines and stuff is already done ;) thanx in advance guys and sorry for the minor english... A: Scrapy makes web-crawling easy. It also has great documentation and scrapy startproject command will build a skeleton project for you. A: Mechanize is a python library that allows you to perform http requests and even provides some ability to parse the html and extract the data you are looking for. It's major feature is that it can act like a browser and handle things like authentication and cookies. Regex is not ideal when working with XML/HTML(you'll see). You can use BeautifulSoup in combination with mechanize if you prefer that parsing library. Learning about things like XPath can make your life simpler as well. Both mechanize and BeautifulSoup have tutorials out there, so start reading some code!
{ "language": "en", "url": "https://stackoverflow.com/questions/7615532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Headless JavaScript testing in ree + cucumber Is there a way to do headless javascript testing in ree (Ruby Enterprise Edition)? I've seen celerity/culerity/capybara, which work with jruby + HTMLUnit, but I can't seem to get it working with ree. When I simply try to annotate my cucumber test with @culerity under ree, I get jruby: command not found, which of course makes sense, because I'm running under ree, not jruby. A: I have been looking at different libraries to do headless javascript testing. I have tried akephalos, based on HTMLUnit, which was really promising, but I was unable to get tests working that worked with selenium. I am now using capybara-webkit, and it works flawlessly. You will need to install Qt before installing the gem. But once that is done (and on ubuntu it is really easy to install), you just add the gem to your Gemfile gem "capybara-webkit" And set your Capybara Javascript driver to webkit: Capybara.javascript_driver = :webkit And you are good to go. Hope this helps. A: You can use capybara-webkit or run selenium with Xvfb - see this post with explanations on how to set it up. A: take a look also at poltergeist https://github.com/jonleighton/poltergeist Capybara.javascript_driver = :poltergeist
{ "language": "en", "url": "https://stackoverflow.com/questions/7615534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How you use fopen/fwrite on a js file? I am trying to do this $fp = fopen('all.js', 'w'); fwrite($fp, 'sddddddddddddddddddddd'); echo "<script src=\"/inc/all.js\" type=\"text/javascript\"></script>"; but the file is always empty...can you use fwrite on a js file and write to it...i checked permissions and all is good there...any ideas? A: fwrite couldn't care less if you're writing text, js, php, or raw binary garbage. It just outputs what you tell it to. The problem is that you're writing out to all.js, but are refering to /inc/all.js in your script tag. Unless your script's current-working-directory is set to whatever directory the URL /inc maps to on your server, you're writing in one place, but reading from another.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: MS Access Selecting Related Rows I have 2 tables with a many-to-any relationship. For the example we will call the tables "Guys" and Girls" There is a junction table that contains the related primary keys...who has dated who. If I want to find all the girls that Guy 1 has dated, I do a select on the junction table selecting all girls with guys.ID. This give me a RecordSet. Now to find the names of the girls, I need to select from the girls table a row using the key from each RecordSet row. Isn't there an easier way? Since I've defined the relationships in Access I would think that there must be a way to build a single query. How do I do that? A: SELECT girls.name FROM (guys INNER JOIN junct ON guys.guyID = junct.guyID) INNER JOIN girls ON junct.girlID = girls.girlID WHERE guys.guyID = [whatever id you're looking for]
{ "language": "en", "url": "https://stackoverflow.com/questions/7615536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Communicate with WCF Windows Service in VB6? I have a VB6 application that I want to communicate with a WCF Windows Service that I have written which imports Security Certificates. The only function in the service takes two string arguments. I have been having a lot of difficulty getting the two programs to communicate however. In VB.NET, it is easy, just make a reference to the service as you would a web service. In VB6, however, it is not so simple it seems. Searching only seems to pull up examples of how to WRITE a Windows service in VB6. Anyone know how this is done? A: The easyest way I have found to access a WCF service from VB6 is to create a .Net ComObject wrapper for the service client. Then in VB6 all your are doing is a create object and calling some methods on the object. All the WCF work takes place in the .Net com object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Rule of three with smart pointer? I'm a little confused by using "rule of three" with smart pointers. If I have a class whose only data member is a smart pointer, do I need to explicitly define destructor, copy constructor, and assignment operator? My understanding is that since smart pointer will handle the resource automatically, then I don't need to explicitly define destructor, and thus I shouldn't need to do so for the other two based on rule of three. However, I'm not sure if the default copy constructor is good enough for smart pointers such as shared_ptr. Thank you for your help! A: In short, "no". The whole point of factoring code into single-responsibility classes is that you can compose your classes from "smart" building blocks so that you don't have to write any code at all. Consider the following: class Foo { std::shared_ptr<Bar> m_pbar; std::string m_id; }; This class automatically has copy and move constructors and copy and move assignment operators that are as good as they can get, and everything is taken care of. If you want to be extreme, you could say that in most cases you should probably never be writing a destructor or copy constructor at all -- and if you do, then perhaps you should best factor that functionality into a separate class with one single responsibility. A: The default destructor is fine, because the destructor of shared_ptr will take care of the deallocation of the object. The default copy constructor may be acceptable depending on your purposes: when you copy the object that owns the shared_ptr, the copy will share ownership with the original. The same would naturally be true of the default assignment operator. If that’s not what you want, define a copy constructor that does otherwise—for instance, that clones the referenced object. A: The rule of three actually says: If you need to define a non-trivial version of any of the following: * *Destructor *Assignment Operator *Copy Constructor ...then you probably need the other two as well. You seem to be interpreting it as: If you need a non-trivial destructor then you also need the other two. But that's not quite the same thing, is it?
{ "language": "en", "url": "https://stackoverflow.com/questions/7615541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Best way to add voting to list items I have a list of items and I want to add ability to vote up or down. I am not sure how to architect this. * *Should I make the votes a table and put more info about the votes like the people who voted? *Regardless of #1, once a person votes, I can make an ajax and jquery call to update the database with the vote count, but how do I update the page on which the vote was made without refreshing the page? If the vote was in item n which isn't first or last, I can't use append or prepend functions in jQuery, so how can I update that exact item? A: Not sure why you got downvoted for this - seems like a good question to me... Anyway, I'd recommend storing who voted along with the total number of votes - it'll let you prevent people from voting as many times as they want, which you couldn't do with just vote totals. And assuming the link that gets clicked to cast a vote is within the LI it applies to, you can use jQuery's success callback, and the fact that $(this) will refer to the link that got clicked, to find the LI you want: $('a.vote').click(function() { //Save the value of $(this) - //I'm not positive it'll be the same in the callback: var clicked_link = $(this); jQuery.ajax({ // some options success: function(data, status, xhr) { var li = clicked_link.closest('li.votable'); //update the vote count from `data` }, //some other options }); }); Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7615543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to persist only a subset of Redis keys to disk Is it possible to persist only certain keys to disk using Redis? Is the best solution for this as of right now to run separate Redis servers where one server can have throw away caches and the other one has more important data that we need to flush to disk periodically (such as counters to visits on a web page) A: You can set expirations on a subset of your keys. They will be persisted to disk, but only until they expire. This may be sufficient for your use case. You can then use the redis maxmemory and maxmemory-policy configuration options to cap memory usage and tell redis what to do when it hits the max memory. If you use the volatile-lru or volatile-ttl options Redis will discard only those keys that have an expiration when it runs out of memory, throwing out either the Least Recently Used or the one with the nearest expiration (Time To Live), respectively. However, as stated, these values are still put to disk until expiration. If you really need to avoid this then your assumption is correct and another server looks to be the only option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Inserting values into multiple MySQL tables at once I've created mini content management system. Now got afew questions I'm filtering posts with following function function filter($data, $db) { $data = trim(htmlentities(strip_tags($data))); if (get_magic_quotes_gpc()) $data = stripslashes($data); $data = $db->escape_string($data); return $data; } And the PHP code looks like that $name=filter($_POST['name'], $db); $title=filter($_POST['title'], $db); $parent=filter($_POST['parent'],$db); $switch=filter($_POST['switch'], $db); if($switch=''){ echo "Return back and select an option"; die(); } $parentcheck=filter($_POST['parentcheck'],$db); if($parentcheck=='0') { $parent=$parentcheck; } $purifier = new HTMLPurifier(); $content = $db->real_escape_string( $purifier->purify( $_POST['content']) ); if(isset($_POST['submit'])&&$_POST['submit']=='Ok'){ $result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$switch'") or die($db->error); $result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('<what?>', '$title', '$content'") or die($db->error); } And that's how my tables look like Table named "pages" And "menu" My questions are followings: * *I'm trying to get autoincremented id value from menu table after ('$parent', '$name', '$switch'") insertion and set this id in pages table while inserting ($title, $content). How to do it? Is it possible with single query? *$content's value is the text with HTML tags. I'm using html purifier. May I filter it's value too before inserting into db table? Any suggestion/advice? A: Should be $result2=$db->query("INSERT INTO pages (id, title, content) VALUES (LAST_INSERT_ID(), '$title', '$content'") or die($db->error); Filtering using real_escape_string( ) should be safe. Is there something else that you want to filter? A: Looks like you're using mysqli as the DB library, so you can use $db->insert_id() to retrieve the LAST id created by an insert operation by that particular DB handle. So your queries would become: $result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$switch'") or die($db->error); $new_id = $db->insert_id(); $result2=$db->query("INSERT INTO pages (id, title, content) VALUES ($new_id, '$title', '$content'") or die($db->error); ^^^^^^^ You can't really do it in a single query, as mysql does not make the ID value available for the insert_id function until AFTER the query completes. So you do have to do this in a 3 step process: insert, get id, insert again. The rule for DB filtering (better known as escaping) is to escape ANYTHING that's user-provided. This even includes data you've retrieve in other db queries and are re-inserting. Escaping isn't really there as a security measure - it's there to make sure that whatever you're putting into the query string doesn't BREAK the query. Preventing SQL injection attacks is just a side effect of this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can not import spring 3.0.6 jars through Maven in IntelliJ Problem I am trying to get a barebones spring mvc project (similar to the template provided in STS) in IntelliJ but the spring 3.0.6 jars do not get imported. Not even after I have done: Right Click on Project Name->Maven->Force Reimport What I have tried * *Read the following post http://blog.springsource.com/2009/12/02/obtaining-spring-3-artifacts-with-maven/ *Added all the spring jar dependencies in my pom.xml *Put a properties block outside dependencies with 3.0.6 as the version *Added the following repository entries (sorry not sure how to enter xml here): http://maven.springframework.org/snapshot http://maven.springframework.org/milestone http://repo1.maven.org/maven2 *Right click on the project->Maven->Force Reimports *Nothing comes down. Anybody know why? <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>springplusjasper</groupId> <artifactId>springplusjasper</artifactId> <packaging>war</packaging> <version>1.0</version> <name>springplusjasper Maven Webapp</name> <url>http://maven.apache.org</url> <!-- Shared version number properties --> <properties> <org.springframework.version>3.0.6.RELEASE</org.springframework.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.core</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.expression</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.aop</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.context.support</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.transaction</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.orm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.oxm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.web.servlet</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.web.portlet</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>org.springframework.test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> </dependency> </dependencies> <repositories> <repository> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> <id>org.springframework.maven.snapshot</id> <name>Spring Maven Snapshot Repository</name> <url>http://maven.springframework.org/snapshot</url> </repository> <repository> <snapshots> <enabled>false</enabled> </snapshots> <id>org.springframework.maven.milestone</id> <name>Spring Maven Milestone Repository</name> <url>http://maven.springframework.org/milestone</url> </repository> <repository> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>Maven Repository Switchboard</name> <url>http://repo1.maven.org/maven2</url> </repository> </repositories> <build> <finalName>springplusjasper</finalName> </build> </project> A: Artifact ids for spring are spring-core, spring-beans etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add onclick to com.google.gwt.dom.client.ImageElement I add an onclic event in a com.google.gwt.dom.client.ImageElement using imageElement.setAttribute("onclick","var tabla=document.getElementById('tablaWidget');var length=tabla.rows.length; for(var i=0;i This works in firefox but not in IE. I read here: onclick setAttribute workaround for IE7 that I shouldn't use setAttribute to do this because is not crossbrowser, but I don`t know how to do it because this element doesn´t have the onclick or addEventListener method. Thanks for your help. A: You should use com.google.gwt.user.client.ui.Image instead of com.google.gwt.dom.client.ImageElement for any images that will be used in the UI. Then you can use Image#addClickHandler to handle clicks in a cross-browser compatible manner.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TimThumb use with pictures from non public folder or virtual folder I am using the TimThumb script (http://code.google.com/p/timthumb/). My images links are generated like this: http://website.com/pics/nature/animals/bear.png and this works great but I can't seem to use TimThumb like this: http://website.com/resize.php?src=http://website.com/pics/nature/animals/bear.png&h=150&w=150, it says Could not find the internal image you specified. I believe this is because my images are brought from a folder by slug names (bear.png). The folder's images are named by the ID of the image so there is no bear.png on the server, my application is using slugs to search the DB and bring up the real name of the picture but it loads the image upon this link: http://website.com/pics/nature/animals/bear.png. If I give my resize.php script a link from flickr it works great. BTW, resize.php is the actual TimThumb script. Any ideas ? Thanks ! A: Dont use a local path, enter the full URL for timthumb just like you did with flickr
{ "language": "en", "url": "https://stackoverflow.com/questions/7615558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gravity Cocos2D? In my game, I am using Cocos2D for the Game part. I am now trying to implement gravity but I am hearing that I have to use Box2D or Chipmunk. I could use those but is there any way to do this in Cocos2D, can anyone share any ideas/code just so I can add some simple gravity using Cocos2D if possible? Thanks! A: Its very easy using Box 2d and Chipmunk. Its inbuilt in cocos2d framework. Just when you start with the cocos2d application template(for iOS) select the Box2D/Chipmunk template. Its very easy. Inorder to start with some gravity you have to create a world and add gravity vectors to it. You have a very simple and detailed tutorial in http://www.raywenderlich.com/457/intro-to-box2d-with-cocos2d-tutorial-bouncing-balls Its a tutorial that teaches you to create a bouncing ball app in Cocos2d Box2d Framework. A: First create a CGPoint variable called gravity and set it's x value to 0 and it's y value to some negative number. CGPoint *grav = ccp(0.0f,-9.8f); Then, in your game loop, just use ccSub on each of your sprites positions. sprite.position = ccSub(sprite.position,grav);
{ "language": "en", "url": "https://stackoverflow.com/questions/7615565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I close a TabControlEx tab with the middle mouse button? I'm working with the WPF TabControlEx (close tabs). I'm looking a way to close the tab clicking the tab header with the mouse wheel click. Any suggestions? Thanks a lot for all your help A: Add this to your XAML on the tab header: <Grid.InputBindings> <MouseBinding MouseAction="MiddleClick" Command="{Binding CloseCommand}" /> </Grid.InputBindings> Have your CloseCommand on your ViewModel close the tab. You might also need to pass the specific tab in with the CommandParameter. A: The Project i was developing was for different purpose but it had the closable tabs if you want to use it you can find it in this forum
{ "language": "en", "url": "https://stackoverflow.com/questions/7615570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Link SVN commits to issues I know I can use #number to to link the commit to an issue. But I'm looking for a way to change the issue status through the svn commit. I'm looking for something similar to what Trac have http://trac.edgewall.org/wiki/TimeTracking . If your svn comment is "This task is almos done (refs 123)" then it add the message on the issue's log. Does anybody knows if there is a way to do it? A: Looks like this is in redmine OOTB: I'm looking for a way to change the issue status through the svn commit. You can update the issue status by using the proper Referencing keywords as defined in your settings. See the redmine wiki or the answer to this question on SO (screenshot below) If your svn comment is "This task is almos done (refs 123)" then it add the message on the issue's log. When using the proper Referencing keywords in your svn message (as above), the revision gets associated to the issue and is being displayed in a second column called Associated revisions to the right of the message History (see this issue as an example). In case you use Fixing keywords , an entry is also added to the issue's log, the status is modified and the % Done field is updated. A: Referencing issues in commit messages When fetched from the repositories, commit messages are scanned for referenced or fixed issue IDs. These options lets you define keywords that can be used in commit message to reference or fix issues automatically, and the status to apply to fixed issues. Default keywords are: for referencing issues: refs, references, IssueID for fixing issues: fixes, closes There's no default status defined for fixed issue. You'll have to specify it if you want to enable auto closure of issues. If you want to reference issues without using keywords, enter a single star: * in the Referencing keywords (Administration/Repository) setting. In this case, any issue ID found in the message will be linked to the changeset. Example of a working commit message using default keywords: This commit refs #1, #2 and fixes #3 This message would reference issues 1 and 2 and automatically fix issue 3. After a keyword issue IDs can be separated with a space, a comma or &. A: * *In case of TortoiseSVN you have to find, install, configure proper plugin for your issue-tracking tool *For command-line SVN (I suppose), most things can be done with post-commit hooks
{ "language": "en", "url": "https://stackoverflow.com/questions/7615571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android memory leak? Hi I have an application that once it recieves a sms, it has to start collecting the location of the user every 1 minute. Everything starts ok i.e. if I send a text, then the sms processing wakes up and calls the location service to start collecting the location every 1 minute. But after some 30 minutes or so, my application crashes because of memory. I used heap in DDMS and observed the memory which keeps on increasing as time goes i.e. the size of the data object keeps getting higher. I also used the allocation tracker to see if there is any leak in my code and observed all the objects are that being created in my code are getting cleared. I am not sure where I am leaking. Please help me understand is this a memory leak? If yes, how can I find where the memory leak is? IF this is not a memory leak, how can I make the application run infinitely until I stop it. A: Take a look at a post that I had recently. I was new to finding memory leaks and the info in this post helped me to find all of my memory leaks and squash them: Android - Many OutOfMemoryError exceptions only on single Activity with MapView
{ "language": "en", "url": "https://stackoverflow.com/questions/7615576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Outlook 2007 image alignment issue I have a table defined as <table width="600" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="600"> <table width="600" border="0" cellspacing="0" cellpadding="25"> <tr> <td width="210">Content 1 with grey background</td> <td width="390">COntent 2 with white background</td> </tr> </table> </td> </tr> <tr> <td width="600" colspan="2"><img src="image.jpg" width="600"></td> </tr> </table> Now this image.jpg has 210 px as grey background and 390px as white background in order to align with the above table cells. However, it shows up as non aligned in outlook 2007. It shows up fine in others. Any suggestions? A: You're lucky it shows at all. The background property is loosely if at all supported by most email clients. I would suggest against using it or using just an <img> tag instead. Here's more info on what outlook 2007 supports: http://www.email-standards.org/clients/microsoft-outlook-2007/
{ "language": "en", "url": "https://stackoverflow.com/questions/7615578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I merge two tables in Access while removing duplicates? I have read through about every possible solution online, and I get a different result every time. I have two tables: Clients and Patrons. They both have the same structure: LastName, FirstName, Address, City, State, and Zip. Clients has 108,000 entries while Patrons has only 42,000 entries. And some of those entries are duplicated between the two as I don't have 150,000 clients. I need one coherent list. The problem I am running into is that some of my clients reside at the same address, so I can't simply remove duplicate addresses as that will remove a legitimate client. And I have some clients with very common names, say Jane Doe, where there are a couple of them at different addresses, so I can't just filter out duplicate last or first names. I am using Microsoft Access 2010. Simply turning unique values to YES isn't helping. I have scoured the Microsoft help files, and I have gotten results of 2 to 168,000 and most everything in between. How can I get a single list without duplicates without having to alphabetize it and go line by line for 150,000 entries?? A: A UNION query returns only distinct rows. (There is also UNION ALL, but that would include duplicate rows, so you don't want it here.) Try this query. If it doesn't return what you want, please explain why if falls short. SELECT LastName, FirstName, Address, City, State, Zip FROM Clients UNION SELECT LastName, FirstName, Address, City, State, Zip FROM Patrons ORDER BY LastName, FirstName; You probably want another field or fields in the ORDER BY. I just offered something to start with. A: One way to do this is to do a FULL OUTER JOIN and COALESCE the values. This would allow you to know if its in the client table, the patron table or both Unfortunately AFAIK Access doesn't have FULL OUTER so you'll need to simulate it instead. SELECT a.LastName, a.FirstName, a.Address, a.City, a.State, a.Zip , "Both" as type FROM Clients a INNER JOIN Patrons b ON a.LastName = b.LastName AND a.Address = b.Address AND a.City = b.City AND a.State = b.State AND a.Zip = b.Zip UNION ALL SELECT a.LastName, a.FirstName, a.Address, a.City, a.State, a.Zip , "Client" as type FROM Clients a LEFT JOIN Patrons b ON a.LastName = b.LastName AND a.Address = b.Address AND a.City = b.City AND a.State = b.State AND a.Zip = b.Zip WHERE b.PatronID is null (Or whatever the PK is) UNION ALL SELECT b.LastName, b.FirstName, b.Address, b.City, b.State, b.Zip , "Patron" as type FROM Clients a RIGHT JOIN Patrons b ON a.LastName = b.LastName AND a.Address = b.Address AND a.City = b.City AND a.State = b.State AND a.Zip = b.Zip WHERE a.ClientID is null (Or whatever the PK is) If you just need a list though you should just use HansUp's answer A: I am not sure that building a fully automated solution is worth the job: you will never be able to build a code that will consider Doe, Jane, 1234 Sunset Boulevard and Doe, Jane, 1234 Sunset Bd as the same person, though these are really the same person! If I were you, I'd build a 4 steps semi-automated solution: * *Merge both tables in one unique table, add an 'isDuplicate' boolean field *Display, through a query, all similar names, and handpick duplicates to be deleted *Display, through a query, all similar (as similar as possible) addresses and handpick dupllicates to be deleted *Delete all records where 'isDuplicate' is set to True Of course, this method is interesting only if duplicate names\addresses are limited! I guess that your filterings will give you a few hundred records to consider. How long will it take? one hour or two? I think it's worth the job! By automating this process you will never be able to make sure all duplicates are eliminated, neither wil you be sure that no legitimate client was deleted. By doing the job this way, you will be sure of your result. A: I am looking for a better way to do this as well, but I was surprised that the answer here is kind of "difficult". Given no simple way to do that join automagically, there is an easy way using Access native functions. Use the Query wizard to create an "Unmatch" Query. This will create a list of participants who exist on one, but not both tables (you specify which during the wizard). Then you can append those records or create a new table as you please. I do not know a way of blending record data in this step as that is much more complicated. A: Try using their mobile phone or their email address as their unique id. That should avoid too many accidental merging or duplicates. And instead of 2 tables, keep them in 1 table but just add 2 columns Yes/No (one for Clients and another for Patrons).
{ "language": "en", "url": "https://stackoverflow.com/questions/7615587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I use jQuery live() after slice()? Why won't live() work after slice()? What am I doing wrong here? $('.object').slice(1).live('mouseenter', function() { alert(); }); ... <div class="object"> 1 <div class="object"> 2 <div class="object"> 3 </div> </div> </div> A: Why won't live() work after slice()? Straight from the API docs: DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector, as in the example above. Use a different selector. For example: $('div.object:gt(0)').live('mouseenter', function() { // super awesome life things }); A: DOM traversal methods are not supported for finding elements to send to .live(). Rather, the .live() method should always be called directly after a selector, as in the example above. @ http://api.jquery.com/live/
{ "language": "en", "url": "https://stackoverflow.com/questions/7615589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to access model in Backbone.js I'm currently learning Backbone.js and have run into a strange issue. I'm not sure if this is the proper way to implement this. I am trying to wrap a jQuery UI Slider in a backbone view and model. However, inside of the slider's slide method I can't access the model's values. Any help is appreciated. Here is my code: var SliderView = Backbone.View.extend({ initialize: function(){ console.log("Creating the slider view..."); _.bindAll(this, 'render'); this.render(); }, render : function(){ console.log("Rendering the slider..."); $( "#slider-vertical" ).slider({ orientation: "vertical", animate: true, range: "min", min: 0, max: 50, value: this.model.get('value'), disabled: this.model.get('disabled'), animate_if_programmed: true, slide: function( ui ) { console.log(model); this.model.set('value', ui.value); }, stop: function() { this.check_bounds(); } }); console.log("Finished rendering..."); } }) var SliderModel = Backbone.Model.extend({ initialize : function(args) { console.log("Creating the slider model..."); }, defaults : { disabled : false, value: 8, position: 0 } }); $(function(){ var sliderModel = new SliderModel(); var slider = new SliderView({ el: $( "#slider-vertical" ), model: sliderModel }); }) Thanks! A: This is a straightforward closure issue. slide and stop are callback functions, so you can't use this within them and assume it points to the view class (I think, with jQuery UI, it probably points to the DOM element you've attached the slider to - "#slider-vertical"). To fix this, you need to have a reference to the view (or the model, if you don't need the view itself) in scope when you define the slide and stop functions. In your case, that means you need a variable reference within render(): render : function(){ // create a reference to the view var view = this; console.log("Rendering the slider..."); $( "#slider-vertical" ).slider({ // ... slide: function( ui ) { // now use it in the slide callback console.log(view.model); view.model.set('value', ui.value); }, stop: function() { // and here, I assume view.check_bounds(); } }); console.log("Finished rendering..."); } A: this within the slider refers to the DOM element and not your view, define your view/model before hand. render : function(){ console.log("Rendering the slider..."); var v = this; var m = this.model; $( "#slider-vertical" ).slider({ orientation: "vertical", animate: true, range: "min", min: 0, max: 50, value: m.get('value'), disabled: m.get('disabled'), animate_if_programmed: true, slide: function( ui ) { console.log(model); m.set('value', ui.value); }, stop: function() { v.check_bounds(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7615590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: subscripted value is neither array nor pointer I am writing a C program in which I am using an array of pipe for IPC.I am getting error "subscripted value is neither array nor pointer".Can any one tell me where did I do mistake? here is the code where I get error: int p[100][2]; //in for loop pipe(p[i-1]); //in child process close(p[i-1][0]); write(p[i-1][1], out, sizeof(NODE)); //in parent process close(p[j][1]); ead(p[j][0], tmp, sizeof(NODE)); A: Pro tip: When resolving build errors in C don't pick any random error in the list and try to fix it. Start with the very first error generated as it is likely the root cause of many of the others that follow. A: You must have a syntax error somewhere else in your code that is throwing off the declaration of int p[100][2] so that the identifier p is not appropriately parsed as a 2-dimensional array of type int allocated on the stack (or statically allocated as a global variable ... you didn't mention where it was declared.). Since the identifier is not parsed correctly, it then also throws off every other use of p in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can you access the edit_XYZ_path for a model when you don't know what type of model it is? Suppose you have an application that has the following models: Book, Author, Publisher. In your routes.rb you have the standard: resources :books resources :authors resources :publishers At some point in your code you have a resource variable which is either a Book, Author, or Publisher, but you don't know which. I know I can access the class, by doing resource.class, but what's the simplest way to get the edit path (e.g. edit_book_path or edit_author_path)? A: I'm assuming you only want the path in order to use it with link_to so: link_to 'Edit', [:edit, resource]
{ "language": "en", "url": "https://stackoverflow.com/questions/7615593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Order MySQL query by multiple ids I have problems sorting results from MySQL. Here is the code: $my_query = " SELECT * FROM tbl1, tbl2, tbl3 WHERE tbl1.id = tbl2.id2 AND tbl1.sub_id = tbl3.sub_id AND tbl1.id IN(22, 55, 5, 10, 40, 2001, 187) "; This query works fine, but when I print it, it's ordered by tbl1.id ASC. I want to display the same order as I used in IN(22,55,5,10,40,2001,187). I think it is possible, but I tried my best and did not get it fixed. Is there any solution that works for me? A: Add this ORDER BY clause that uses the FIELD function to get the order you want: ORDER BY FIELD(tbl1.id, 22, 55, 5, 10, 40, 2001, 187)
{ "language": "en", "url": "https://stackoverflow.com/questions/7615596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I test XForms using submissions if I don't have the services available? I want to test XForms that performs submissions, but in my environment I don't have access to the services the submissions will ultimately call, either because they haven't be developed yet, or are behind a firewall. With some XForms implementations I can get around this by using a file:/// URLs to test that my form is sending the right data, but Orbeon Forms doesn't support writing to disk with a file:/// URL in submission. What other, more portable alternative could I use? A: If you need to test submission with replace instance, the similar echoinstance service will respond with the request entity, and the same Content-Type: <xforms:submission id="echo-submission" method="post" resource="http://xformstest.org/cgi-bin/echoinstance.sh" ref="instance('data')" replace="instance"/> Please note that bandwidth on xformstest.org is limited, so if you need to make the echo or echoinstance service part if your integration test infrastructure for continuous use, ask for help in setting up your own copy of the service. A: Using the XForms test suite echo service You can use the echo service also used by the XForms test suite. That echo service returns an HTML page with information about what you submitted, which is a good way for you to check that you are submitting the correct data. Your submission will look at follows, and also see this full example using the XForms test suite echo service. <xforms:submission id="echo-submission" method="post" resource="http://xformstest.org/cgi-bin/echo.sh" ref="instance('data')" replace="all"/> Using the jsFiddle echo service You can use the jsFiddle echo service for XML, which allows you to do a replace="instance". The jsFiddle echo service doesn't take the XML in the body of the POST, but as an xml form-encoded parameter in the POST. So you need to first encode the XML you want to post, as done in the submission below, and also in this full example using the jsFiddle echo service. <xforms:submission id="echo-submission" method="post" resource="http://jsfiddle.net/echo/xml/" serialization="application/x-www-form-urlencoded" ref="instance('jsfiddle-out')" replace="instance" instance="jsfiddle-in"> <xforms:setvalue ev:event="xforms-submit" ref="instance('jsfiddle-out')" value="saxon:serialize(instance('data'), 'xml')"/> </xforms:submission>
{ "language": "en", "url": "https://stackoverflow.com/questions/7615599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamically and incrementally add controls to a container I thought this was straight forward, but i have a link button, and I do this in the click event: myContainer.Controls.Add( new FileUpload()); I expect 1 new file control upload to be spawned in the container for each click, however, I always get 1. What do I need to do to have multiple file upload controls? A: Since the control was added dynamically, it does not survive the postback. This means that you have to add the file upload (or any other dynamically added control) again in the preinit event to be able to have its values populated and to use it later on in the page life cycle. Sounds like you are trying to be able to upload multiple files. You may want to add the file uploads with jQuery and use the Request.Files property to get them on the back-end. A: I agree with Becuzz's answer. Try this, there are better ways to do it, but this might help as well: Add this to the "Load" event of your page if (!IsPostBack) { Session["UploadControls"] = null; } if (Session["UploadControls"] != null) { if (((List<Control>)Session["UploadControls"]).Count > 0) { foreach ( ctrl in (List<Control>)Session["UploadControls"]) { files.Controls.Add(ctrl); } } } And also add this to the PreInit portion of your page: string ButtonID = Request.Form("__EVENTTARGET"); if (ButtonID == "Button1") { FileUpload NewlyAdded = new FileUpload(); List<Control> allControls = new List<Control>(); if (Session["UploadControls"] != null) { if (((List<Control>)Session["UploadControls"]).Count > 0) { foreach ( ctrl in (List<Control>)Session["UploadControls"]) { allControls.Add(ctrl); //Add existing controls } } } if (!allControls.Contains(NewlyAdded)) { allControls.Add(NewlyAdded); } Session["UploadControls"] = allControls; } And add this to your HTML. This can be anything of course: <div id="files" runat="server"> </div> I use the "__EVENTTARGET" value to know what caused the postback, so that you don't get unwanted Upload controls. Good luck, and hopefully this helps. Hanlet
{ "language": "en", "url": "https://stackoverflow.com/questions/7615605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Load class without knowing package? Is it possible to load a class by name if you don't know the whole package path? Something like: getClassLoader().loadClass("Foo"); The class named "Foo" might be around, might not be - I don't know the package. I'd like to get a listing of matching classes and their packages (but not sure that's possible!), Thanks A: Nope. The Java ClassLoader.loadClass(String) method requires that class names must be fully qualified by their package and class name (aka "Binary name" in the Java Language Specification). A: If you don't know the package, you don't know the name of a class (because it's part of the fully qualified class name) and therefore cannot find the class. The Java class loading mechanism basically only allows you to do one thing: ask for a class with its fully qualified name, and the classloader will either return the class or nothing. That's it. There#s no way to ask for partial matches, or to list packages. A: Contrary to the previous answers, and in addition to the answers in the question @reader_1000 linked to: This is possible, by essentially duplicating the logic by which Java searches for classes to load, and looking at all the classfiles. Libraries are available that handle this part, I remember using Reflections. Matching classes by unqualified name isn't their major use case, but the library seems general enough and this should be doable if you poke around. Do note that this will, very likely, be a fairly slow operation. A: Using java Reflections: Class.forName(new Reflections("com.xyz", new SubTypesScanner(false)).getAllTypes().stream() .filter(o -> o.endsWith(".Foo")) .findFirst() .orElse(null)); A: Even if you don't know the package name, sites like jarFinder might know it
{ "language": "en", "url": "https://stackoverflow.com/questions/7615611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Setting the szTip field of the NOTIFYICONDATA structure The szTip field is 128 characters long, and unicode. It is of type TCHAR, which is typedef'd as WCHAR. So i have no clue why the following code snippet will not compile. nid.szTip = _T("ToolTip"); The compile error is error C2440: '=' : cannot convert from 'const wchar_t [8]' to 'WCHAR [128]' Any advice? A: Your code would work if you were assigning to a TCHAR*. However, szTip is not a TCHAR*, it is declared as TCHAR szTip[64]. So you need to copy the contents of the string to the buffer. Like this: _tcscpy(nid.szTip, _T("ToolTip")); Do you really need to support both ANSI and Unicode builds? If not then stop using TCHAR and switch to Unicode. Then you could write a more readable version. wcscpy(nid.szTip, L"ToolTip");
{ "language": "en", "url": "https://stackoverflow.com/questions/7615615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting variable in a loop from outside while 'function' I have a while loop that assigns user ID's to a variable. The variable is an array. When I assign the variable to another in a link like this: it returns proper ID's on the click but only when the link is in a while loop as well. How ( is it possible ) to place the link outside the while loop and get the same ID data the variable holds ? This code works: while ( $row = mysqli_fetch_array($sql)) { $variable = $row['user_id']; echo "<a href='index.php?var=$variable'></a>"; } This one doesn't in this case: PHP: while ( $row = mysqli_fetch_array($sql)) { $variable[] .= $row['user_id']; } HTML: for ($i = 0 ; $i <100 ; $i++ ); <a href='index.php?var=$variable[$i]'></a> Thanks for comments.. A: You've got a syntax goof: for ($i = 0 ; $i <100 ; $i++ ); ^---- The semicolon terminates the for loop, so you're doing an empty loop. Change it to: for ($i = 0 ; $i <100 ; $i++ ) echo "<a href......etc...."; or better yet: for ($i = 0 ; $i <100 ; $i++ ) { echo "<a href......etc...."; } A: while ( $row = mysqli_fetch_array($sql)) { $variable[] .= $row['user_id']; //Wrong $variable[] = $row['user_id']; //Correct } foreach($variable as $value) { echo "<a href='index.php?var=$value'></a>"; // Be sure to use double quotes } A: Several issues are coming into play here: * *$variable is defined within the scope of the while loop, so it is inaccessible outside of said loop (though PHP may let you get away with this one). *You are assuming that there are precisely 100 rows (indexed 0-99) returned by performing the SQL query represented by $sql. While this may be true, it's not good practice to assume this, and you should handle however many rows are actually returned by performing that query. *Perhaps most importantly, if you are truly using <a href='index.php?var=$variable[$i]'></a> in an HTML context, it will not work, as $variable[$i] is PHP code. You will need to put this in a PHP document, somewhere between the <?php and ?> tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the observability of class methods in PHP The function get_classs_methods returns all methods of a class. But, is there a function or technique to get the observability of these methods? I want to list only the public methods. A: The return value from get_class_methods depends on the scope you're calling it from; if you're calling it from outside the class, you'll only get the methods that are visible from the current scope. Calling it from a method inside the class will give you all the available methods from the class. If you want more information or to query the class in a more detailed manner, you probably want to look at using reflection and the getMethods method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: connection to mysql server from clojure I'm trying to connect to a mysql database from clojure. I'm using the example code taken from: http://corfield.org/blog/post.cfm/connecting-clojure-and-mysql but I'm getting this error: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was 0 ms ago. The mysql server is bound to 127.0.0.1:3306. Changing localhost to 127.0.0.1 in :subname doesn't help. I have set the mysql server to log everything for debugging, and it doesn't even see a connection coming. What am I doing wrong here? A: I can connect to the db using mysql -h 127.0.0.1. But this fails to connect if I change 127.0.0.1 to localhost. my.cnf contains: bind-address = 127.0.0.1 and as I write above, changing to 127.0.0.1 in :subname doesn't help. The thing that did the trick was putting mysqld : ALL : ALLOW in /etc/hosts.allow. I have no idea why this is needed, especially when all the other services that contact the MySQL server work without it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Need the decimal to save and show three places I have this line of code in c# but i it always resets the textbox back to the format 0.00, how can i make it so that it keeps the format 0.000 ?. NewYorkTax = Convert.ToDecimal(txtNewYorkTax.Text); //converts it but with 0.00, I need 0.000 or 7.861 etc.. SIDE NOTE: NewYorkTax is of type Decimal, I need to keep this variable.. any ideas? Thank you A: You need to format the string in your textbox: decimal NewYorkTax = Convert.ToDecimal(txtNewYorkTax.Text); //... code that is doing stuff with the decimal value ... txtNewYorkTax.Text = String.Format("{0:0.000}", NewYorkTax); EDIT: Clarified the use of String.Format Second edit: Regarding exceptions Also bear in mind the risk of converting to decimal when taking in human input. Humans are error-prone creatures. :) It helps to use TryParse, which Decimal supports: decimal NewYorkTax; if (Decimal.TryParse(txtNewYorkTax.Text, out NewYorkTax)) // Returns true on valid input, on top of converting your string to decimal. { // ... code that is doing stuff with the decimal value ... txtNewYorkTax.Text = String.Format("{0:0.000}", NewYorkTax); } else { // do your error handling here. } A: i think you can use like this.. NewYorkTax = Convert.ToDecimal(String.Format("{0:0.000}", Convert.ToDecimal(txtNewYorkTax.Text)));
{ "language": "en", "url": "https://stackoverflow.com/questions/7615628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Excel vba - convert string to number So, I used the left function to take the first 4 characters of a string and I need to run a vlookup with it, but it won't find the match because it's looking through numbers. I want to do this in a macro, so I'm not sure about the syntax. Can someone help? A: If, for example, x = 5 and is stored as string, you can also just: x = x + 0 and the new x would be stored as a numeric value. A: use the val() function
{ "language": "en", "url": "https://stackoverflow.com/questions/7615629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How can I override a module's singleton method? Given a module with a singleton method like this: module Foo class << self def bar puts "method bar from Foo" end end end How can I override Foo.bar using another module? A: This code module Foo class << self def bar puts "method bar from Foo" end end end is equal to class << Foo def bar puts "method bar from Foo" end end that is also equal to def Foo.bar puts "method bar from Foo" end So, you can call it to redefine this method everywhere where Foo is defined (ever withing another module, without including Foo). A: Extend and alias My problem was that I forgot to think through the inheritance chain. I was looking for a way to override the method by modifying the inheritance chain, but that's not possible. The reason is that bar is defined on Foo itself, so it never looks up its inheritance chain for the method. Therefore, to change bar, I have to change it on Foo itself. While I could just re-open Foo, like this: module Foo def self.bar puts "new foo method" end end ... I prefer a way to be able to wrap the original bar method, as though I were subclassing and could call super. I can achieve that by setting up an alias for the old method. module Foo class << self def bar "method bar from Foo" end end end puts Foo.bar # => "method bar from Foo" module FooEnhancement # Add a hook - whenever a class or module calls `extend FooEnhancement`, # run this code def self.extended(base) # In the context of the extending module or class # (in this case, it will be Foo), do the following base.class_eval do # Define this new method def self.new_bar "#{old_bar} - now with more fiber!" end # Set up aliases. # We're already in the context of the class, but there's no # `self.alias`, so we need to call `alias` inside this block class << self # We can call the original `bar` method with `old_bar` alias :old_bar :bar # If we call `bar`, now we'll get our `new_bar` method alias :bar :new_bar end end end end # This will fire off the self.extended hook in FooEnhancement Foo.extend FooEnhancement # Calls the enhanced version of `bar` puts Foo.bar # => 'method bar from Foo - now with more fiber!' A: You can do the following: module Foo class << self def bar puts "method bar from Foo" end def baz puts "method baz from Foo" end end end module Foo2 def Foo.bar puts "new version of bar" end end include Foo Foo.baz #=> method baz from Foo Foo.bar #=> new version of bar Or instead of naming it Foo2 simply re-open Foo. module Foo class << self def bar puts "method bar from Foo" end def baz puts "method baz from Foo" end end end module Foo class << self def bar puts "new version of bar" end end end include Foo Foo.baz #=> method baz from Foo Foo.bar #=> new version of bar
{ "language": "en", "url": "https://stackoverflow.com/questions/7615632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: BlackBerry WebWorks 2.1.1, OS 6.0 / 7.0, blackberry.pim.Appointment.find is not working I have a simple sample app that returns number of appointments in calendar app, which works fine in OS 5.0, but failing find any appointments in OS 6.0 or 7.0, (I can create an Appointment though, just can't find it) var date = new Date(); var filter = new blackberry.find.FilterExpression("start", ">=", date); var appts = blackberry.pim.Appointment.find(filter); or just var appts = blackberry.pim.Appointment.find(); config file: <feature id="blackberry.system" /> <feature id="blackberry.utils" /> <feature id="blackberry.io.file" /> <feature id="blackberry.find"/> <feature id="blackberry.pim.Appointment"/> <feature id="blackberry.pim.Attendee" /> <feature id="blackberry.pim.Recurrence" /> <feature id="blackberry.pim.Reminder" /> I think this thread might be related to the problem I'm having, but it indicates that the problem has been fixed in WebWorks 2.0. Appointment API. Edit: Simulators: * *5.0.0.975 - 9630-Verizon - OK *6.0.0.141 - 9800 - ERR *7.0.0.318 - 9930 - ERR Device: * *6.0.0.600 - 9800 - ERR
{ "language": "en", "url": "https://stackoverflow.com/questions/7615635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: class design - validating user input I use the clas below to validate user input. Originally it was just a collection of static functions grouped together. However, I modifed it to an object style and added in a private memeber to hold the user input array. What is the next step to making this class adaptable, i.e. more generic so that it can be used by others as part of a library? $message is the text displayed to the user on a validation fail. Library Code: class validate { private $input; function __construct($input_arg) { $this->input=$input_arg; } function empty_user($message) { if((int)!in_array('',$this->input,TRUE)) return 1; echo $message;return 0; } function name($message) { if(preg_match('/^[a-zA-Z-\.]{1,40}$/',$this->input['name'])) return 1; echo $message;return 0; } function email($message) { if(preg_match('/^[a-zA-Z0-9._s-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/',$this->input['email'])) return 1; echo $message;return 0; } function pass($message) { if(preg_match('/^[a-zA-Z0-9!@#$%^&*]{6,20}$/',$this->input['pass'])) return 1; echo $message;return 0; } } Application Code: function __construct() { parent::__construct(); $obj=check_new($this->_protected_arr); $a='<si_f>Please enter both an email and a password!'; $b='<si_f>Please enter a valid email!'; $c='<si_f>Please enter a valid password!'; if($obj->empty_user($a) && $obj->email($b) && $obj->pass($c) && self::validate()) { self::activate_session(); echo "<si_p>"; } } A: Maybe it's worth having a look at Zend Validate? Or any other PHP frameworks validate classes. Just then extend them to add the functionality you want. In answer to your question, is it worth having another variable in the class so you can check the error? class validate { private $input; public $error = false; function __construct($input_arg) { $this->input=$input_arg; } function empty_user($message) { if((int)!in_array('',$this->input,TRUE)) return 1; echo $message;$this->error = "Empty message"; } ... else } $validate = new validate($empty_message); if( !$validate->empty_user('this input is empty') === false) { echo "Was not empty"; } A: I'd not write all these function in a generic class. I'd rather have separate functions that perform specific checks, and maybe a specific class that calls these checks on my specific input. This class now echo's, which is never a good solution for a class like this. Just let it perform the check and raise an exception if something's wrong. If exceptions are too hard, or don't fit in your achitecture, let your function return false, and set a property that can be read afterwards. About your specific checks: * *Your e-mail check is very strict and doesn't allow all e-mail addresses. The domain, for instance, can be an IP address too, and the username (the part before the @) can include many obscure characters, including an @. Yes, really! *Why must a password be 6 characters at least? And why on earth would you limit the password to 20 characters? I use passwords of over 20 characters, and I know many other people that do too. Just let everybody type everything they want. Anything. Let them post 3MB of text if they like. Let them include unicode characters if they want. What is a better protection that having a bunch of chinese characters as a password? And if they want to enter just a, that's their responsibility too. You should never ever store the password itself anyway, so just hash whatever they input and store the 32 characters that gives you (if you use MD5 hashing). The only password that you may refuse is an empty password. Anything else should go. *Same goes for name. 40 characters? Really. I can imagine people having names that long. Add a little more space. Bytes aren't that expensive, and it's not that you're gonna have 2 billion users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what is a good structure to save this data C# WinForms: The things I want to save: name: string previous value: double new value: double so each entity has those three fields, the number of them will not be too much at all, maybe 10 max. All I want to do with them is just to be able to add some members to it and then loop through them and read them later. so one easy way would be having three arrays, one for each. It is not really thay big of a deal to create a Class for it, etc..so I am looking for some good strudcutres that I can use, Arrays like what I said above? any better choice? A: There's nothing wrong with creating classes to hold custom data. You can even create a private inner class if its not going to be used by anything else. There is something wrong with using arrays for a need that doesn't require an indexed set of data. A: Class or struct is clearly the way to go. If you want to avoid a class you could use a Dictionary<string, KeyValuePair<double, double>> where the key is the name and the KeyValuePair represents the previous and new values A: class Foo { public string Name { get; set; } public double PreviousValue { get; set; } public double NewValue { get; set; } } A: Create an object for them: public class Foo { public string Name { get; set; } public double Value { get; set; } public double OldValue { get; set; } } Then you can add them to a List and loop through them and access them: foreach(var foo in myListOfFoos) { // Do something with foo.Name, foo.Value, etc... } A: If you're into OOP (and you should) then everything is a class. What's the problem with the classes? They're not selected based on how big they are. If they model something real then they should exist. I won't create anything different that what others have said. A: What do you mean with "not really that big of a deal to create a class"? Classes are not evil. They help structure your data. That's one of the main reasons why they have been invented. Make it a class. It won't kill your code's performance, but will definitely increase readability, maintainability and whatnot compared to using primitives and collections thereof. If not for yourself, then for the poor chap that will eventually inherit your codebase. Use a class. I can point you to some good reading material on object orientation if needed. A: I think that a class really is the most simple way to store this data. I know that you keep saying it's not a big enough deal to use a class, but if you need to save this data set easily for use later you really need to be using a class. You even said yourself that: each entity has those three fields The "entity" you're talking about is an object, which is an instance of a class. You can have a List<T> of the objects and iterate through them easily with a foreach. A: If you don't want to create a class or struct then you could store your data in a list of tuples. List<Tuple<string, double, double>> MyData = new List<Tuple<string, double, double>>(); MyData.Add(new Tuple<string, double, double>("test1", 1, 2)); MyData.Add(new Tuple<string, double, double>("test2", 3, 4)); If it were me though I would just go ahead and create a class, it will make it easier for future developers to figure out your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access variable in added movie clip I'm in class file right now and made a new movie clip using the linkage name var mc = new ExampleLinkageName(); addChild(mc); all good, I can see mc on the stage. In the ExampleLinkageName movieclip, I have a variable defined in it (on the physical timeline) called test. In my class, I try trace(mc.test) and I get null. Any idea how I can read that variable? A: You are doing it right, but the variable has not been created (the first frame actions has not executed) when you try to access it. If you (for debug purpose) try to access mc.test in the next frame of your timeline you will get the correct variable value. Or add an ENTER_FRAME EventListener to the created Movieclip like this: var mc : Symbol1 = new Symbol1(); mc.addEventListener(Event.ENTER_FRAME, initHandler); addChild(mc); function initHandler(event : Event) : void { trace(mc.test); mc.removeEventListener(Event.ENTER_FRAME, initHandler); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7615643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GCD - executing methods on order after finishing others I have a class that I call several times with different data. That class, calls a web-service, parse it's response to NSDictionary, and save the data on Core Data. The call of the web service and the saving in core data are done in different threads, using core data queues, so that the UI keeps responsive. Class: - (void)refreshDataFromWebService:(NSString *)webserviceWSDL { dispatch_queue_t receiveActivities = dispatch_queue_create("com.myApp.ws.wsdlMethod", NULL); dispatch_async(receiveData, ^(void) { //call web service //... //parse received data to NSDictionary //... }); dispatch_release(receiveData); } //some work //the class that works with the WS, calls a method on it's delegate, and the saveData is called. - (void)saveData { dispatch_queue_t request_queue = dispatch_queue_create("com.myApp.insertDataOnCoreData", NULL); dispatch_async(request_queue, ^{ //save data to CoreData with new Manage Object Context //... //... }); dispatch_release(request_queue); } The issue is that I need to call this Class about 15 times, and in some order. What is the best way to do it? Should I call: [SomeClass refreshDataFromWebService:method_1]; [SomeClass refreshDataFromWebService:method_2]; [SomeClass refreshDataFromWebService:method_3]; [SomeClass refreshDataFromWebService:method_4]; or should I do a different way? The goal is that method_2 is only called after method_1 is finish saving on CoreData, due to relationships. Thanks for you precious help, Rui Lopes A: Your first call to receive data and then save data the will not work in any scenario where it takes longer to receive data than it does to call save the data, which would likely almost always be the case. The save operation needs to be called inside of the receive block at the end. Now for the services to be called one at a time in order you should create an ivar for a serial dispatch queue for the class and use that and only release it in the dealloc method. Another option is to use NSOperations with a queue that has max concurrent operations set to 1. A: Why don't you simply create a single serial queue for each instance of your class and then serialize the operations against the internal queue? This will ensure that method_2 happens after method_1 (assuming that method_1 was enqueue first, by design) while still allowing all instances of the class to run in parallel with respect to one another. This assumes, of course, that this is your goal - it's hard to tell from the code fragment in question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0 I upgraded from Java 1.6 to Java 1.7 today. Since then an error occur when I try to establish a connection to my webserver over SSL: javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name at sun.security.ssl.ClientHandshaker.handshakeAlert(ClientHandshaker.java:1288) at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1904) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1027) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1262) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1289) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1273) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:523) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1296) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) at java.net.URL.openStream(URL.java:1035) Here is the code: SAXBuilder builder = new SAXBuilder(); Document document = null; try { url = new URL(https://some url); document = (Document) builder.build(url.openStream()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(DownloadLoadiciousComputer.class.getName()).log(Level.SEVERE, null, ex); } Its only a test project thats why I allow and use untrusted certificates with the code: TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { Logger.getLogger(DownloadManager.class.getName()).log(Level.SEVERE, null, e); } I sucessfully tried to connect to https://google.com. where is my fault? Thanks. A: I had what I believe the same issue is. I found that I needed to adjust the Apache configuration to include a ServerName or ServerAlias for the host. This code failed: public class a { public static void main(String [] a) throws Exception { java.net.URLConnection c = new java.net.URL("https://mydomain.com/").openConnection(); c.setDoOutput(true); c.getOutputStream(); } } And this code worked: public class a { public static void main(String [] a) throws Exception { java.net.URLConnection c = new java.net.URL("https://google.com/").openConnection(); c.setDoOutput(true); c.getOutputStream(); } } Wireshark revealed that during the TSL/SSL Hello the warning Alert (Level: Warning, Description: Unrecognized Name), Server Hello Was being sent from the server to the client. It was only a warning, however, Java 7.1 then responded immediately back with a "Fatal, Description: Unexpected Message", which I assume means the Java SSL libraries don't like to see the warning of unrecognized name. From the Wiki on Transport Layer Security (TLS): 112 Unrecognized name warning TLS only; client's Server Name Indicator specified a hostname not supported by the server This led me to look at my Apache config files and I found that if I added a ServerName or ServerAlias for the name sent from the client/java side, it worked correctly without any errors. <VirtualHost mydomain.com:443> ServerName mydomain.com ServerAlias www.mydomain.com A: Ran into this issue with spring boot and jvm 1.7 and 1.8. On AWS, we did not have the option to change the ServerName and ServerAlias to match (they are different) so we did the following: In build.gradle we added the following: System.setProperty("jsse.enableSNIExtension", "false") bootRun.systemProperties = System.properties That allowed us to bypass the issue with the "Unrecognized Name". A: You cannot supply system properties to the jarsigner.exe tool, unfortunately. I have submitted defect 7177232, referencing @eckes' defect 7127374 and explaining why it was closed in error. My defect is specifically about the impact on the jarsigner tool, but perhaps it will lead them to reopening the other defect and addressing the issue properly. UPDATE: Actually, it turns out that you CAN supply system properties to the Jarsigner tool, it's just not in the help message. Use jarsigner -J-Djsse.enableSNIExtension=false A: You can disable sending SNI records with the System property jsse.enableSNIExtension=false. If you can change the code it helps to use SSLCocketFactory#createSocket() (with no host parameter or with a connected socket). In this case it will not send a server_name indication. A: Java 7 introduced SNI support which is enabled by default. I have found out that certain misconfigured servers send an "Unrecognized Name" warning in the SSL handshake which is ignored by most clients... except for Java. As @Bob Kerns mentioned, the Oracle engineers refuse to "fix" this bug/feature. As workaround, they suggest to set the jsse.enableSNIExtension property. To allow your programs to work without re-compiling, run your app as: java -Djsse.enableSNIExtension=false yourClass The property can also be set in the Java code, but it must be set before any SSL actions. Once the SSL library has loaded, you can change the property, but it won't have any effect on the SNI status. To disable SNI on runtime (with the aforementioned limitations), use: System.setProperty("jsse.enableSNIExtension", "false"); The disadvantage of setting this flag is that SNI is disabled everywhere in the application. In order to make use of SNI and still support misconfigured servers: * *Create a SSLSocket with the host name you want to connect to. Let's name this sslsock. *Try to run sslsock.startHandshake(). This will block until it is done or throw an exception on error. Whenever an error occurred in startHandshake(), get the exception message. If it equals to handshake alert: unrecognized_name, then you have found a misconfigured server. *When you have received the unrecognized_name warning (fatal in Java), retry opening a SSLSocket, but this time without a host name. This effectively disables SNI (after all, the SNI extension is about adding a host name to the ClientHello message). For the Webscarab SSL proxy, this commit implements the fall-back setup. A: I hit the same problem and it turned out that reverse dns was not setup correct, it pointed to wrong hostname for the IP. After I correct reverse dns and restart httpd, the warning is gone. (if I don't correct reverse dns, adding ServerName did the trick for me as well) A: My VirtualHost's ServerName was commented out by default. It worked after uncommenting. A: If you are building a client with Resttemplate, you can only set the endpoint like this: https://IP/path_to_service and set the requestFactory. With this solution you don't need to RESTART your TOMCAT or Apache: public static HttpComponentsClientHttpRequestFactory requestFactory(CloseableHttpClient httpClient) { TrustStrategy acceptingTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContext sslContext = null; try { sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); } catch (Exception e) { logger.error(e.getMessage(), e); } HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", new PlainConnectionSocketFactory()) .register("https", csf) .build(); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(100); httpClient = HttpClients.custom() .setSSLSocketFactory(csf) .setConnectionManager(cm) .build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); return requestFactory; } A: We also ran into this error on a new Apache server build. The fix in our case was to define a ServerAlias in the httpd.conf that corresponded to the host name that Java was trying to connect to. Our ServerName was set to the internal host name. Our SSL cert was using the external host name, but that was not sufficient to avoid the warning. To help debug, you can use this ssl command: openssl s_client -servername <hostname> -connect <hostname>:443 -state If there is a problem with that hostname, then it will print this message near the top of the output: SSL3 alert read: warning:unrecognized name I should also note that we did not get that error when using that command to connect to the internal host name, even though it did not match the SSL cert. A: Instead of relying on the default virtual host mechanism in apache, you can define one last catchall virtualhost that uses an arbitrary ServerName and a wildcard ServerAlias, e.g. ServerName catchall.mydomain.com ServerAlias *.mydomain.com In that way you can use SNI and apache will not send back the SSL warning. Of course, this only works if you can describe all of your domains easily using a wildcard syntax. A: It should be useful. To retry on a SNI error in Apache HttpClient 4.4 - the easiest way we came up with (see HTTPCLIENT-1522): public class SniHttpClientConnectionOperator extends DefaultHttpClientConnectionOperator { public SniHttpClientConnectionOperator(Lookup<ConnectionSocketFactory> socketFactoryRegistry) { super(socketFactoryRegistry, null, null); } @Override public void connect( final ManagedHttpClientConnection conn, final HttpHost host, final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig, final HttpContext context) throws IOException { try { super.connect(conn, host, localAddress, connectTimeout, socketConfig, context); } catch (SSLProtocolException e) { Boolean enableSniValue = (Boolean) context.getAttribute(SniSSLSocketFactory.ENABLE_SNI); boolean enableSni = enableSniValue == null || enableSniValue; if (enableSni && e.getMessage() != null && e.getMessage().equals("handshake alert: unrecognized_name")) { TimesLoggers.httpworker.warn("Server received saw wrong SNI host, retrying without SNI"); context.setAttribute(SniSSLSocketFactory.ENABLE_SNI, false); super.connect(conn, host, localAddress, connectTimeout, socketConfig, context); } else { throw e; } } } } and public class SniSSLSocketFactory extends SSLConnectionSocketFactory { public static final String ENABLE_SNI = "__enable_sni__"; /* * Implement any constructor you need for your particular application - * SSLConnectionSocketFactory has many variants */ public SniSSLSocketFactory(final SSLContext sslContext, final HostnameVerifier verifier) { super(sslContext, verifier); } @Override public Socket createLayeredSocket( final Socket socket, final String target, final int port, final HttpContext context) throws IOException { Boolean enableSniValue = (Boolean) context.getAttribute(ENABLE_SNI); boolean enableSni = enableSniValue == null || enableSniValue; return super.createLayeredSocket(socket, enableSni ? target : "", port, context); } } and cm = new PoolingHttpClientConnectionManager(new SniHttpClientConnectionOperator(socketFactoryRegistry), null, -1, TimeUnit.MILLISECONDS); A: Use: * *System.setProperty("jsse.enableSNIExtension", "false"); *Restart your Tomcat (important) A: I have also come across this issue whilst upgrading from Java 1.6_29 to 1.7. Alarmingly, my customer has discovered a setting in the Java control panel which resolves this. In the Advanced Tab you can check 'Use SSL 2.0 compatible ClientHello format'. This seems to resolve the issue. We are using Java applets in an Internet Explorer browser. Hope this helps. A: Here is solution for Appache httpclient 4.5.11. I had problem with cert which has subject wildcarded *.hostname.com. It returned me same exception, but I musn't use disabling by property System.setProperty("jsse.enableSNIExtension", "false"); because it made error in Google location client. I found simple solution (only modifying socket): import io.micronaut.context.annotation.Bean; import io.micronaut.context.annotation.Factory; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import javax.inject.Named; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import java.io.IOException; import java.util.List; @Factory public class BeanFactory { @Bean @Named("without_verify") public HttpClient provideHttpClient() { SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), NoopHostnameVerifier.INSTANCE) { @Override protected void prepareSocket(SSLSocket socket) throws IOException { SSLParameters parameters = socket.getSSLParameters(); parameters.setServerNames(List.of()); socket.setSSLParameters(parameters); super.prepareSocket(socket); } }; return HttpClients.custom() .setSSLSocketFactory(connectionSocketFactory) .build(); } } A: I had the same problem with an Ubuntu Linux server running subversion when accessed via Eclipse. It has shown that the problem had to do with a warning when Apache (re)started: [Mon Jun 30 22:27:10 2014] [warn] NameVirtualHost *:80 has no VirtualHosts ... waiting [Mon Jun 30 22:27:11 2014] [warn] NameVirtualHost *:80 has no VirtualHosts This has been due to a new entry in ports.conf, where another NameVirtualHost directive was entered alongside the directive in sites-enabled/000-default. After removing the directive in ports.conf, the problem had vanished (after restarting Apache, naturally) A: Just to add a solution here. This might help for LAMP users Options +FollowSymLinks -SymLinksIfOwnerMatch The above mentioned line in the virtual host configuration was the culprit. Virtual Host Configuration when error <VirtualHost *:80> DocumentRoot /var/www/html/load/web ServerName dev.load.com <Directory "/var/www/html/load/web"> Options +FollowSymLinks -SymLinksIfOwnerMatch AllowOverride All Require all granted Order Allow,Deny Allow from All </Directory> RewriteEngine on RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L] </VirtualHost> Working Configuration <VirtualHost *:80> DocumentRoot /var/www/html/load/web ServerName dev.load.com <Directory "/var/www/html/load/web"> AllowOverride All Options All Order Allow,Deny Allow from All </Directory> # To allow authorization header RewriteEngine On RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] # RewriteCond %{SERVER_PORT} !^443$ # RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L] </VirtualHost> A: There is an easier way where you can just use your own HostnameVerifier to implicitly trust certain connections. The issue comes with Java 1.7 where SNI extensions have been added and your error is due to a server misconfiguration. You can either use "-Djsse.enableSNIExtension=false" to disable SNI across the whole JVM or read my blog where I explain how to implement a custom verifier on top of a URL connection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "233" }
Q: Android layout_weight when creating components programatically I've read plenty of questions saying that the problem was the layout_width = 0dip but I've tried that and can't make this work. I have this holder: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/linearLayout1" android:orientation="horizontal" android:weightSum="3" android:padding="10dip" android:fadingEdge="none" android:background="@drawable/bg_filters"> </LinearLayout> And this partials: <Button xmlns:android="http://schemas.android.com/apk/res/android" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_width="0dip" android:layout_height="40dip" android:padding="4dip" android:gravity="center" android:layout_gravity="center" android:layout_weight="1" android:layout_marginRight="15dip" android:background="@drawable/bg_filter_bt_active" android:textColor="@color/app_color_all"> </Button> but my views' buttons show still show up grouped to the left... Is there a method I should call the holder to recalculate the weights of its children? Remember, I'm creating them programmatically. Thanks ! EDIT: I already HAVE a screen with this composition: ################################## # # # Button | Button | Button # # # with that exact XML, but instead of being created programmatically, it is already there in the XML. It works perfectly. When I create the same setup but programmatically, I get this: ################################## # # # Button | Button | Button # # # The buttons align themselves to the left, even tho the weight should evenly distribute them. Is there a method or something I need to call to the LinearLayout to calculate the weight and correct the view? EDIT 2: I just tried taking this same LinearLayout and inserting the same Button 3 times inside it on a regular XML. It shows just like it should. This is definitely something to do with creating the holder and the 3 buttons programmatically. A: Check your imports! I had the same exact problem and it turns out I was importing the wrong LayoutParams. I was importing android.widget.AbsListView, instead of android.widget.LinearLayout.LayoutParams and that what was causing the problem. A: Have you tried forcing the view to redraw itself through invalidate() or refreshDrawableState()? Can you post the code where you create those buttons programmatically?
{ "language": "en", "url": "https://stackoverflow.com/questions/7615648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Grab firsts distinct entities ordered by datetime using Core Data What I have Message Entity user | text | date ---------------------------------------------- user1 | This is first message user 1 | 10:50 ** user2 | This is first message user 2 | 10:50 ** user3 | This is first message user 3 | 10:50 ** user1 | This is second message user 1 | 10:00 user4 | This is first message user 4 | 10:00 ** user2 | This is second message user 2 | 10:00 user3 | This is second message user 3 | 10:00 user1 | This is third message user 1 | 9:00 ... With that data I want to grab the first message of each distinct user using CoreData in a single fetch request. That is user1|This is the first message user 1|10:50 user2|This is the first message user 2|10:50 user3|This is the first message user 3|10:50 user4|This is the first message user 4|10:00 You can achieve that by grabbing first the distinct users, and then, perform a fetch request for each user using a predicate, but it will end with a lot of "queries" (5 in this case). It would be nice if it can be done in a single request. Thanks! A: I would add a relationship to your user entity called something like 'lastMessage' which you will always keep up-to-date whenever you insert a new message. Then the problem becomes trivial. In my experience it's easier to de-normalize your schema slightly to improve performance rather than trying to create really complex queries. EDIT to show entities: ------------- 1 R1 * ------------ |User Entity|<----------->| Message | ------------- ------------ | name |------------>| text | ------------- R2 1 | date | ------------ You have two entities - User and Message. Set up 2 relationships between the entities: R1 - 'messages' bidirectional one-to-many (one user has many messages and one message belongs to one user) R2 - 'lastMessage' unidirectional one-to-one (one user has one last message) Keep R2 up-to-date whenever you add a new message. To get last messages for all users perform a fetch request for all users and then just look at the R2 relationship. Use setPropertiesToFetch: on the NSFetchRequest to populate the R2 relationship in a single trip to the database. A: There's an easier way. Do a fetch request of the user fields. This will produce a set containing each distinct user. Next, enumerate through the set: for (NSManagedObject *obj in fetchController.fetchedObjects){ } Inside this loop, you can do another fetch using the obj object for the predicate. Sort by date wiht a maximum return of 1. The resulting set will be one object which is the first message for that user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loading a Big Plist File I have a big plist file, I have a problem, when I do: [NSMutableDictionary dictionaryWithContentsOfFile:docDirPath]; I must waiting for some seconds before I can use the application. Is there some solution? Thanks A: Load the plist in another thread, GCD is perfect for this. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ [self.theDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:docDirPath]; }); If the class of the method that does this will not live until the plist read is complete you will need to wrap the block in a copy to Heap. dispatch_async(queue, [[^{ [self.theDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:docDirPath]; } copy] autorelease]); A: If the plist is stored as a text plist, convert it to a binary plist instead. They load much faster. The easiest way to do that is with plutil: plutil -convert binary1 file.plist (This assumes that it's a static plist file rather than one created on-the-fly. Within your app you can store a dictionary as binary using NSPropertyListSerialization)
{ "language": "en", "url": "https://stackoverflow.com/questions/7615654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: sql fulltext returning null I'm using the joomla CMS to write to my db and have written a custom front end. I'm trying to obtain the contents of the 'fulltext' row. I've tried mysql_fetch_assoc['fulltext'] and mysql_result($sql, 0, 'fulltext'). Both return fulltext. Here's the query string: SELECT created, modified, title, introtext, 'fulltext', state, urls, created_by FROM table_content WHERE id='$id' It's probably something really obvious I've missed because fulltext seems to conflict with sql without the quotation marks around it. Any assistance would as always be appreciated! A: You can use SQL keywords as field names, with appropriate escaping with backticks. You're using single quotes, which turns the word into a string that contains the word "fulltext". Try SELECT .... introtext, `fulltext`, state, ... ^--------^--- backticks instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mathematica remote kernel on macs I am trying to run a remote mathematica kernel between two macs. Under Kernel Configuration Options For kernel program I have: /Applications/Mathematica.app/Contents/MacOS/MathKernel The arguments of MLOpen: -LinkMode Listen -LinkProtocol TCPIP -LinkOptions MLDontInteract The launch command is: java -jar mathssh [email protected] /usr/local/bin/math -mathlink -LinkMode Connect -LinkProtocol TCPIP -LinkName "linkname" -LinkHost ipaddress When i use this remote kernel (for instance 2+2 does not give a result) I get the error message: "The kernel Thomas Machine failed to connect to the front end. (Error = MLECONNECT). You should try running the kernel connection outside the front end." It seems that Mathematica is not even opening on the remote machine since I used "top" and do not see it running after I start the remote kernel. Any help would be greatly appreciated. A: I just tried this with 8.0.1 -- here's my config (with bogus machine/user names): In particular the /usr/local/bin/math looks suspicious. You generally shouldn't need to use the advanced settings. Drop to a command line and try: ssh [email protected] /usr/local/bin/math and see if you get a Mathematica prompt and can evaluate 1+1 there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ASP.NET MVC3 Combination of Views + Partial Views Conflicting I have the following structure: Views: Home Articles Partial Views: Book Classes Intro Faq On the top of the page, in my header, is a navigation menu - containing multiple Ajax.ActionLinks that call into different methods in my HomeController class to fetch a particular partial view and then place that content in my center DIV. So I can click on the Faq link, and the content in the center DIV of my page will now contain the partial view for my Faq. Now, I have an Articles view that will look completely different and therefore needs to be separated as it's own view as opposed to a partial view, and, the problem that I am running into is if I click on my Html.ActionLink for "Articles", I am navigated to my Articles view, which is what I want, but then if I click on one of the other links that are Ajax.ActionLinks, I need (somehow) the view to change back to my Home view so that I can then retrieve the requested partial view and place that into my center DIV. Any idea how I can do this? Right now the AJAX.ActionLink, when being called while on my Articles View, is calling into my HomeController, but then trying to replace the content in my center DIV (which doesn't exist in my Articles view), and additionally, it's not loading the HomeView. Any thoughts on how to best achieve this? Also, I am not using the Razor engine. So, the navigational menu, which is a set of links, resides in my Site.Master file. Here is one of the links that I have: <%= Ajax.ActionLink("Book", "LoadBook", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "content", InsertionMode = InsertionMode.Replace })%> When clicking on this link, the method LoadBook in my HomeController is called. Refer to the code below: public ActionResult LoadBook() { return PartialView("Book"); } In my Home.aspx view, I have the following code: <div id="content"> <% Html.RenderPartial("Intro"); %> </div> This code will automatically load the partial view for my "intro" (introduction) by default whenever initially loading the Home view. So basically, since the link for "Articles" is Html.ActionLink (as opposed to Ajax.ActionLink), when it is clicked I am taken to the Articles view. When I click on, for example, the "Book" Ajax.ActionLink in my Site.Master header while on the Articles view, the code will try to update a "content" DIV with the "Book" partial view. This behavior is only wanted when on the Home view, for obvious reasons. So, how can I have different behavior for my Ajax.ActionLinks when viewing a view that is different than my Home view? Thanks! Chris A: This sort of architecture is going to give you lots of problems. For stanrtes, you can't link to any pages. All your content happens in your main page. This works ok for an app like GMail, but most people will be confused as to why they can't save a shortcut to a page, or send a link to a friend. HTML is designed to have a unique URL for each page. You're fighting upstream trying to do something different. Suppose you want to use fragments to jump to other sections of your page. you can't do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Objective-C, counting zombies via instruments, clarification needed As i was working on my program, i noticed that, upon profiling, instruments was nice enough to point me to a Zombie object when it saw one. Does the fact that this message does not show up indicative of the fact that app contains no zombie processes? Is there a way i can confirm that app contains no references to Zombie processes? In my question, i am explicitly mentioning Xcode4, as i have not seen automatic Zombie behavior in 3 and suspect it may be a new feature. A: No zombie messages showing up is a good sign. It means you weren't accessing any freed objects while Instruments was tracing. There's no way for Instruments to confirm that your application never accesses a freed object. All Instruments can do is tell you when you access a freed object. Regarding automatic zombie behavior, detecting zombies is not new behavior in Xcode 4. Instruments has a Zombies template in both Xcode 3.2 and 4 that detects zombies. You can also configure the Allocations instrument to detect zombies by clicking the Info button next to the instrument, which the zombie message is blocking in your screenshot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading new content into and keeping input fields value from previous state? I'm trying to make my own tumblr search (tags only) since their own search function doesn't actually work. So I'm nearly there. It works, but I need the search field to keep the value of what the user searched for. So if I search for "foobar", it loads the tumblr.com/tagged/foobar directly into my tumblr.com, but the search field still contains the term "foobar" Here is my working code except for the code where I'm trying to insert the previous search term into the newly loaded Thanks in advance. <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> jQuery(function($) { $('#syndex').keydown(function(event) { if (event.keyCode == '13') { var syndex = $('input:text').val(); $('body').load("http://syndex.me/tagged/"+ syndex); $(this).val(syndex); //this is what's not working } }); }); </script> </head> <body> <div id="logo"> <input id="syndex" type="text"/> </div> </body> </html> A: You need to put this into the complete function which can be passed as a parameter to load. http://api.jquery.com/load/ Load makes an AJAX call which is asynchronous. You are trying to set the value prior to the content being loaded. $('body').load("http://syndex.me/tagged/"+ syndex,function(){ $('input:text').val(syndex); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7615671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A dynamic resize of this HTML from AJAX is making text unreadable. How do I "refresh" it? I am filling a pull-down list with data from an ajax call. When the page first loads, the area looks like this: After the pull-down list is filled via an Async call it looks like this mess: If I click anywhere in the area it looks correct: So - is there a way that I can tell the enclosing div or p to refresh so it does essentially the same thing after the select box is filled? Thank you! A: Just give it a min-width in your css and set it to the width of the widest drop down item. A: You have a mix of block and inline elements so they are overlapping. You should make each piece of the form its own block element and then you can set properties like width or min-width. CSS: label { display: block; width: auto; float: left; } input, select { display: block; min-width: 100px; float: left; } HTML: <label>Give</label> <input type="text" id="pts" /> <label>point to</label> <select id="person"> // dynamically loaded </select> <input type="submit" value="Give Now">
{ "language": "en", "url": "https://stackoverflow.com/questions/7615674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSDocument - memory leak & app crash I have a memory leak in my document based app. It launches fine, I can open or make a new document, but only one or two times, and then the app crashes. I used analyzed tool in Xcode and there are no issues. However, Instruments reveals the memory leak, but I can't find where it lies in my code. Using Objects Allocations, I can see my NSDocument subclass isn't released when I close the document... I don't really know if this is the intended behaviour. Here is how I read and write the document : -(NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError { NSMutableData *d = [NSMutableData data]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:d]; [archiver encodeObject:[self machine] forKey:IVPCodingKeyMachine]; [archiver finishEncoding]; [archiver release]; if(outError) { *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL]; } return d; } -(BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outErro { NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; machine = [[unarchiver decodeObjectForKey:IVPCodingKeyMachine] retain]; [machine setDelegate:self]; [unarchiver finishDecoding]; [unarchiver release]; if(outError) { *outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL]; } return YES; } The machine property is declared like so : @property(readonly) IVPMachine *machine; on the machine ivar and IVPMachine class conforms to NSCoding protocol. In case of new documents I have overridden -(id)initWithType:(NSString *)typeName error:(NSError **)outError; method, here the code I use : -(id)initWithType:(NSString *)typeName error:(NSError **)outError { self = [super initWithType:typeName error:outError]; if (self) { machine = [[IVPMachine alloc] initWithCreditAmount:2000]; [machine setDelegate:self]; [machine setGame:[[IVPGamesLibrary sharedInstance] objectInGamesAtIndex:0]]; } return self; } Finally in -(void)dealloc; method I release the machine ivar. I can't figure out where the bug lies.. Isn't my document subclass instance supposed to be released when I close a document in my app ? Any help is welcome. Thank you. A: As a wild guess, did you implement -[IVPMachine setDelegate:] to retain the delegate? If so, don't do that. Delegates should be weak references, i.e., non-retaining. You own the IVPMachine, so if it owns you back, that's a circular ownership, and is what is keeping both the document and the IVPMachine alive. More practically, dig some more in Instruments. It can tell you not only that you have leaked something, but every retention and release that has happened to it. Look through that list to find the retention that is not balanced out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trace context switches on Linux Possible Duplicate: Monitoring pthread context switching I have a program where under certain scheduling layout some strange things happen (a number of threads which do sched_yield seem to throttle each other in a strange manner). I would like to take an exact trace of what is going on in terms of the OS scheduler slices on each CPU. Is there a way to capture such trace? I'm running SLES 11.1, with root privileges. A: This might be what you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Warning: set_time_limit() [function.set-time-limit]: Cannot set time limit in safe mode in I have a large script that has a set_time_limit(0) directive to insure it processes fully. However, I'm getting a few reports of this error on a small percentage of installations: Warning: set_time_limit() [function.set-time-limit]: Cannot set time limit in safe mode... Is there a method call to check for safe mode before committing the function? A: Is there a method call to check for safe mode before committing the function? Yes, there is ini_get('safe_mode') Whether to enable PHP's safe mode. If PHP is compiled with --enable-safe-mode then defaults to On, otherwise Off. Source * *ini_get()
{ "language": "en", "url": "https://stackoverflow.com/questions/7615679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Grey Font Color Printing Is there any way to ensure that my grey font colors do not turn black? Firefox and Chrome seem to do this in order to prevent white text on black background from turning into white on white. I do not have a background color (except white), so this browser-level conversion is not useful, it only helps in preventing grey colors for no reason. Is there a way to turn this off? Or should I just stick with techniques like opacity, browser detection, and coloring my grays... A: I found had to : * *Add !important to the css rule... and... *In the Firefox print dialog, tick the option for "Appearance: Print background colors" I couldn't get it to work in Chrome. A: Solution: @media print { h1 { color: rgba(0, 0, 0, 0); text-shadow: 0 0 0 #ccc; } @media print and (-webkit-min-device-pixel-ratio:0) { h1 { color: #ccc; -webkit-print-color-adjust: exact; } } } A: Some browsers add more respect to your gray if you add color: Replace #777 with #778. Be wary of opacity. Sometimes, even if the print preview will show great results, it only actually works on select printers. Printers with unlucky firmware will fail to print your text at all if it is gray using opacity. A: You just need to output your grey font in svg. Browsers don't change color in svg. Here's an example: <svg height="40" width="200"> <text font-size="28px" y="25" x="30" fill="#ffffff" > Some text </text> </svg> A: I thought that is the only div on that page. Make the following change, it should work fine. <style> @media print { div.red { color: #cccccc !important; } </style> And change the html of the div tag like below A: I found that TEXT color is not inherited by "general purpose" stylesheet, but must be forced again in print css file. In other words, even if text color is set in the general css file (one with media='all' attribute), it is ignored when printed, at least in Firefox and Chrome. I found that writing again (redundant but..... necessary) text color in print css file (one with media='print' attribute), color now will be considered. A: This solution working in all browsers: .text{ color: transparent; text-shadow: 2px 0 #red; } A: Give importance to color: .bgcol{ background-color:skyblue !important; } .subject_content,h2,p{ color:rgba(255, 255, 255) !important; margin: 25px auto; } <body class="bgcol"> <div class="subject_content"> <h2 class='text-center'>fhddfhnt area</h2> <p>sdgdfghdfhdfh.</p> </div> A: Nothing above was working for me so I finally figured it out. Always give colors to direct elements. Ex. Suppose your html is <div class='div'><br/> < h1>Text< /h1><br/> </div> and your CSS .div { color: #ccc; } This was my case. In this case no matter what you do the color won't show. You have to do .div h1 { color: #ccc; } @media print { .div h1 { -webkit-print-color-adjust: exact; } } Hope this helps you!! Please reply if you find a better solution as this is what I could find after 2 hrs and it works for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: How to match "escape" non-printable character in a regex? I've found a howto, http://answers.oreilly.com/topic/214-how-to-match-nonprintable-characters-with-a-regular-expression/ , but non of the codes, \e, \x1b, \x1B, work for me in Java. EDIT I am trying to replace the ANSI escape sequences (specifically, color sequences) of a Linux terminal command's output. In Python the replace pattern would look like "\x1b[34;01m", which means blue bold text. This same pattern does not work in Java. I tried to replace "[34;01m" separately, and it worked, so the problem is \x1b. And I am doing the "[" escaping using Pattern.quote(). EDIT Map<String,String> escapeMap = new HashMap<String,String>(); escapeMap.put("\\x1b[01;34m", "</span><span style=\"color:blue;font-weight:bold\">"); FileInputStream stream = new FileInputStream(new File("/home/ch00k/gun.output")); FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); String message = Charset.defaultCharset().decode(bb).toString(); stream.close(); String patternString = Pattern.quote(StringUtils.join(escapeMap.keySet(), "|")); System.out.println(patternString); Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(message); StringBuffer sb = new StringBuffer(); while(matcher.find()) { matcher.appendReplacement(sb, escapeMap.get(matcher.group())); } matcher.appendTail(sb); String formattedMessage = sb.toString(); System.out.println(formattedMessage); EDIT Here is the code I've ended up with: import java.io.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; import java.util.*; import java.util.regex.*; import org.apache.commons.lang3.*; class CreateMessage { public static void message() throws IOException { FileInputStream stream = new FileInputStream(new File("./gun.output")); FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); String message = Charset.defaultCharset().decode(bb).toString(); stream.close(); Map<String,String> tokens = new HashMap<String,String>(); tokens.put("root", "nobody"); tokens.put(Pattern.quote("[01;34m"), "qwe"); String patternString = "(" + StringUtils.join(tokens.keySet(), "|") + ")"; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(message); StringBuffer sb = new StringBuffer(); while(matcher.find()) { System.out.println(tokens.get(matcher.group())); matcher.appendReplacement(sb, tokens.get(matcher.group())); } matcher.appendTail(sb); System.out.println(sb.toString()); } } The file gun.output contains the output of ls -la --color=always / Now, the problem is that I'm getting a NullPointerException if I'm trying to match Pattern.quote("[01;34m"). Everything matches fine except of the strings, that contain [, even though I quote them. The exception is the following: Exception in thread "main" java.lang.NullPointerException at java.util.regex.Matcher.appendReplacement(Matcher.java:699) at org.minuteware.jgun.CreateMessage.message(CreateMessage.java:32) at org.minuteware.jgun.Main.main(Main.java:23) EDIT So, according to http://java.sun.com/developer/technicalArticles/releases/1.4regex/, the escape character should be matched with "\u001B", which indeed works in my case. The problem is, if I use tokens.put("\u001B" + Pattern.quote("[01;34m"), "qwe");, I still get the above mentioned NPE. A: quote() is to make a pattern that will match the input string verbatim. Your string has pattern language in it. Look at the output from quote() - you'll see that it's trying to literally find the four characters \x1b. A: The ansi escape sequences are of the following form [\033[34;01m] where \033 is ANSI character 033 (oct) or 1b in Hex or 27 in decimal. You need to use the following regexp: Pattern p = Pattern.compile("\033\\[34;01m"); You can use an octal (\033) or hex (\x1b) representation when you're using a non-printable character in a java string. A: The proper value for "escape" character in a regexp is \u001B A: FWIW, I've been working on stripping ANSI color codes from colorized log4j files and this little pattern seems to do the trick for all of the cases I've come across: Pattern.compile("(\\u001B\\[\\d+;\\d+m)+")
{ "language": "en", "url": "https://stackoverflow.com/questions/7615683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Automatically call method after part has been composed in MEF Is there a way to specify that a method gets called automatically after a part has been composed? The method could be called on the composed part or in the class doing the composition. A: Yes. If your class implements the IPartImportsSatisfiedNotification interface, then the MEF container will call OnImportsSatisfied at the right time. A: Taking this approach will introduce a temporal coupling into your class - it will be dependent on some outsider calling methods in just the right order before it works properly. Temporal Coupling is a major code smell - it makes reuse and understanding of the class much more difficult. (And keep in mind that one developer who will need to read and understand the code from scratch is yourself in six months.) Instead, your class should take responsibility for it's own initialization - it shouldn't rely on an outside party. One way to do this, if certain steps need to be deferred from the constructor, is to move those steps into a private method and then add a guard step to each appropriate public method ensuring the initialization is complete. public class Example { public Example() { // Constructor } public void Open() { EnsureInitialized(); ... } private void EnsureInitialized() { if (!mInitialized) { Initialize(); } } private void Initialize() { // Deferred code goes here } } A: Based on your comments the specific problem is there is code you want to execute only when the type is created via MEF composition. In other scenarios you'd like to avoid the code execution. I'm not sure if there is a particular MEF event you could hook into. However you could use the following pattern to work around the problem class MyPart { public MyPart() : this(true) { } private MyPart(bool doMefInit) { if (doMefInit) { MefInitialize(); } } public static MyPart CreateLight() { return new MyPart(false); } } Although i would question the validity of this pattern. If your type has code which is only valid in a specific hosting scenario it screams that the code should likely be factored out into 2 independent objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Custom Maven Archetype or alternatives to project generation We would like to generate projects from a Maven Archetype but we are finding it a bit simplistic. We would like to do the following: * *Have a simple starting point. Not ask too many questions. *Allow updating the project later (or during the original generate) with additional features. *Allow adding / deleting / updating the project features. *Updating pom.xml, spring xml files, possibly other XML files and property files. *generation of stubbed web services from contracts, including unit tests. *generation of Eclipse / Intellij projects would be nice. *Some reasonably complex generation of things like populating namespaces / classes into spring Interceptors would be nice. Especially if it could generate said values. Maven Archetypes do not appear to support anything more than making choices during the initial generation, and adding files later. I don't see any support for modifying existing files? We can generate stubbed web services via a normal maven build, but do not appear to be able to run arbitrary maven plugins during the archetype:generate? If anyone knows the answers to any of the above, we like to hear it. Also if anyone has alternatives for the feature set that we are looking for we would like to know about them. A: We did something like that for our project. We defined a dedicated plugin that will itself call the Archetype:generate plugin. This way we can rely on a the Archetype:generate capabilities (automatic parsing and replacement of part of the generated classes...). You can have a look at this project on our SVN here: http://websvn.ow2.org/listing.php?repname=weblab&path=%2Ftrunk%2FWebLabTools%2FMavenPlugins%2F&#. Note: That the code has been done by a trainee, please be kind ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7615690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Callback after __doPostBack()? I am refreshing an UpdatePanel with Javscript by calling a method like so: reloadDropDown = function (newValue) { __doPostBack("DropDown1", ""); selectNewValueInDropDown(newValue); } Inside my UpdatePanel is a <select> box that I need to select an <option> with a newValue. My problem is that my selectNewValueInDropDown method is being called prior to the __doPostBack from completing. Is there a way I can "wait" for the postback before calling my selectNewValueInDropDown method? A: Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function BeginRequestHandler(sender, args) { // } function EndRequestHandler(sender, args) { //request is done } A: To make my comment more concrete, here's the idea: reloadDropDown = function (newValue) { var requestManager = Sys.WebForms.PageRequestManager.getInstance(); function EndRequestHandler(sender, args) { // Here's where you get to run your code! selectNewValueInDropDown(newValue); requestManager.remove_endRequest(EndRequestHandler); } requestManager.add_endRequest(EndRequestHandler); __doPostBack("DropDown1", ""); } Of course, you probably want to handle race conditions where two requests overlap. To handle that, you would need to keep track of which handler is for which request. You could use something like ScriptManager.RegisterDataItem on the server side, or call args.get_panelsUpdated() and check to see if the panel you're interested it was updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Implementing reCaptcha into a Rails 2.3.12 app I need to implement reCaptcha into a Rails app form for my internship. Unfortunately I am still taking my Web Programming classes and haven't gotten into any server side lessons yet, so I am still a complete noob when it comes to submitting forms and sending requests to servers, let alone not using RoR before I started the internship. I have been trying to find a tutorial to follow, but all that I've found assume more experience with web development. I have the public/private keys from the site and have installed the plugin, but am completely lost now. Obviously I don't want someone to just tell me what I should code, but if someone could tell me where I need to go after this that would be fantastic. I know that I need to add <%= recaptcha_tags %> where I want reCaptcha to appear, but I haven't been able to find anything pertaining to what I need to code for the helpers or what kind of JavaScript I need to implement. I know I need to do some AJAX calls, but again, NO idea what to do or where to start. Any tips, pointers or references to tutorials would be fantastical and I would love you forever and a day. Thanks! A: look here https://developers.google.com/recaptcha/docs/customization http://hwork.org/2009/03/08/recaptcha-on-rails/ http://blog.ncodedevlabs.com/2010/01/26/implementing-recaptcha-in-your-rails-app/ or the best place : http://google.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7615700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create a Region or GraphicsPath from the non-transparent areas of a bitmap I want to hit-test a drawn bitmap to see if a given Point is visible in the non-transparent pixels of the image. For example, to do this test for the whole bitmap rectangle, you would do something like this: Bitmap bitmap = new Bitmap("filename.jpg"); GraphicsPath path = new GraphicsPath(); Rectangle bitmapRect = new Rectangle(x, y, bitmap.Width, bitmap.Height); path.AddRectangle(bitmapRect); if (path.IsVisible(mouseLocation)) OnBitmapClicked(); However, if I have a bitmap of a non-rectangular item and I want to be able to check if they are clicking on the non-transparent area, is there any supported way in the .NET framework to do this? The only way I could think to do this is to lock the bitmap bytes into an array, and iterate through it, adding each x,y coordinate that is non-transparent to an array of Point structures. Then use those point structures to assemble a GraphicsPath. Since these points would be zero-based I would need to offset my mouse location with the distance between the x,y coordinate that the image is being drawn at and 0,0. But this way I could essentially use the same GraphicsPath for each image if I draw it multiple times, as long as the image is not skewed or scaled differently. If this is the only good route, how would I add the points to the GraphicsPath? Draw lines from point to point? Draw a closed curve? A: IMHO a simpler technique would be to look at the alpha component of the hit pixel: Color pixel = bitmap.GetPixel(mouseLocation.X, mouseLocation.Y); bool hit = pixel.A > 0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7615708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Testing Modified Session Variables Right now I'm trying to test Session variables. For example I set: Session["test"] = "test"; Then: if (blah) { Session["test"] = "foo"; } else if (testing) { Session["test"] = "foo2"; } I'd like to be able to run tests so that depending on the conditions I set forth I can see that the Session variable has changed appropriately. I've tried using Moq and I'm able to create a Mock Session and then define a variable to return something specific: controllerContext.Setup(x => x.HttpContext.Session["test"]).Returns("test"); This doesn't change though when running through the test. It seems even further complicated if I'm strongly typing the variables by using a Session wrapper since I try to pass the mock session and context between controllers. I've a read a little about FakeContext and Fake Sessions as opposed to Mock. I've also heard a little about using delegates. Really I'm just trying to emulate what happens when the code is actually running and make sure the end result is what I expect and it happens to often depend on my Session variables. What would be the best approach towards testing their modification is properly being done? A: It's good to see that you have used Moq, in which case instead of asserting the value of the session you can assert if the code has attempted to set the session.. Asserting on behaviour basically.. Here are a couple of useful links: ASP.NET MVC Unit Testing - Sessions ASP.NET MVC Tip #12 – Faking the Controller Context
{ "language": "en", "url": "https://stackoverflow.com/questions/7615709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In PHP, can you access a parent object from an object from which it is composed? I have a base class of FileCopier that is composed with two "has-a" associations to Resource Source and Resource Destination. After construction, three properties exist in FileCopier: - Source (instance of Resource) - Destination (instance of Resource) - Config (array of configuration stuff for this FileCopier) All of the examples I find on this issue are regarding children by extension rather than children by composition. My question is: is there any way for the Resource instance to access it's parent's "Config"? Or, must I pass a reference to the parent to it's associated children, say, via the constructor? A: The answer depends on the responsibilities of your objects. If both Resources are created by the FileCopier object, you could supply the config from the FileCopier through the constructor of the Resource class (if all resources should have a configuration - otherwise through a property/getter&setter). If the FileCopier is the thing that is configured, and Resources will know about the FileCopier it is currently being used in (either through the constructor or a property), then the FileCopier should just have a getConfig() or use ->config if the property is public. From your naming I'm having a bit of trouble of seeing the actual use case where a resource must know the configuration of the object performing any work on the resource itself. It might be more better to move that part of configuration (i.e. if it's a "save" or "move" command on the resource) to the actual method call (and call ->save() where the FileCopier object uses the path from its configuration. A: If I have understood the question correctly, "parent" is the wrong term, though I know what you mean. If an object F is an instanceof FileCopier, and has two properties that are both instanceof Resource, then the object F is not the parent of the resource instances. Not quite sure what one does call that relationship, tbh :-o You can permit the resource instances access to your config though. Do something like this in your FileCopier class: public function setSource(Resource $r) { $this->Source = $r; $r->setConfig($this->Config); } That way the resource can be 'notified' of the config transparently. A: If I understand well you have: class FileCopier{ /* @var Source */ private $source; /* @var Destination */ private $destination; /* @var Config */ private $conf; ... } And you want to access $conf from $source and $destination? There is no parent or other magic word to access this $conf from the two other variables. Your best bet would be to add a function to Resource which will set a local reference to Config: class Resource { /* @var Config */ protected $config; ... function setConfig(Config $config) { $this->config = $config; } ... } Or if config is set at some other point r could change or if for whatever other reason you want to access the latest $conf from your resources you can pass a ref to FileCopier instead: class Resource { /* @var FileCopier */ protected $copier; ... function setFileCopier(FileCopier $copier) { $this->copier = $copier; // and access to $this->copier->conf through a getter // or make $conf public in FileCopier } ... } Then all you have to do is to call your setter before using $source and $destination. Probably in the FileCopier: class FileCopier{ ... //first case : function setConfig($config) { $this->config = $config; $this->source->setConfig($config); $this->destination->setConfig($config); } // Or for the second case: function setup() { $this->source = new Source(); $this->source->setFileCopier($this); $this->destination = new Destination(); $this->destination->setFileCopier($this); } ... } Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how: Partial Rage Rendering with jsp2/facelets/templating with menu driving main content refresh only? I found some posts by BalusC (big fan of urs) and others here on stack overflow and haven't found the solution, which would seem like something many would want to be able to do. If I have a facelets/templating structure like this, a left navigation with links that drive what gets shown in main content area, but without doing a complete page refresh, I just want the main area to update, how do I do this? ------------------------------------- | link1 | show content for link1 | | link2 | when link1 is clicked | | link2 | in left navigation area | | | | ------------------------------------- I see the primefaces showcase does a whole page refresh when clicking menu items on left, and oddly enough, the richfaces4 showcase does not, although I am looking at the code can't understand just yet. is there a example out there that can show me how to do this? here is my code uiTemplate.xhtml (main template) <div> <div id="left"> <ui:include src="navigationMenu.xhtml"/> </div> <div id="center_content" class="center_content"> <ui:insert name="center_content" /> </div> </div> then my navigationMenu.xhtml looks like <ui:composition> <rich:collapsiblePanel header="ClickMe" switchType="client"> <h:link outcome="page1" value="goto page1" /><br /> <h:link outcome="page2" value="goto page2" /><br /> <h:link outcome="page3" value="goto page3" /><br /> </rich:collapsiblePanel> </ui:composition> and one of the pages which will appear in center content area, hopefully loaded without a complete refresh of all sections. I would think I am going to need some f:ajax tag or use h:commandLink for these links above but just haven't found a good example. I see a bunch posts about Mojarra 2.1.x fixing dynamic includes but not sure that is related to this, unless that's is the only way to accomplish this. page1.xhtml <ui:composition template="./uiTemplate.xhtml"> <ui:define name="center_content"> page 1 content </ui:define> </ui:composition> A: I figured out how to get something working, however, I have not done much testing, like adding more components into the navigation form other than a4j:commandLink elements. my current navigation section merely updates the center content with new content in a ajx request thereby not doing a complete page refresh, nothing elaborate, here is my navigationMenu.xhtml file <ui:composition> <h:form> <rich:collapsiblePanel header="Carriers" switchType="client"> <a4j:commandLink action="page1" value="goto page1.xhtml" render=":centerContentDiv"/><br /> <a4j:commandLink action="page2" value="goto page2.xhtml" render=":centerContentDiv"/><br /> </rich:collapsiblePanel> </h:form> and then my uiTemplate.xhtml which is my master template has a snippet in it like this <div> <div id="left"> <ui:include src="navigationMenu.xhtml"/> </div> <h:panelGroup id="centerContentDiv" layout="block"> <ui:insert name="center_content" /> </h:panelGroup> </div> I do notice there seems to be a bit of a oddity, even in my really small test app. I have to be real deliberate when clicking the links or it seems to ignore me I guess i need to add facestraces from primefaces to see if it tells me anything about whats happening I hope this helps someone out there *** followup ***** As a followup, after some testing, if the included center content subsequently contains form(s), submitting those form(s) seems to only happen on second click of a commandLink or commandButton. The forms are not nested which is a common reason a form don't submit correctly BalusC comments here. I added facestraces and it does hit the server but jumps from restore view to render response, 2nd click it goes through all phases. The fact that the navigation uiComposition has a h:form and the center content uiComposition has a h:form is causing issues. I know this because if I remove the navigation uiComposition, and just load the center content directly via typed in URL, then it's form submits correctly on first click. I think BalusC was referring to something about this in post on partial page rendering but without a complete example in that post, it was a bit hard for me to follow. This would be a common task I would assume many would want to implement, so I'll keep digging.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework also Linq advice needed i have got on my DB 3 tables movies, workers, workermovies ( this is the Relationship table ) public class Movie { public Movie() { Genres = new List<Genre>(); Formats = new List<Format>(); ProductionCompanies = new List<ProductionCompany>(); Workers = new List<Worker>(); } public int Id { get; set; } public string Title { get; set; } public DateTime ReleaseDate { get; set; } public string StoryLine { get; set; } public int RunTime { get; set; } [ForeignKey("MPAARateId")] public MPAARate MPAARate { get; set; } public int MPAARateId { get; set; } public byte[] ImageData { get; set; } public string ImageMimeType { get; set; } public DateTime CreatedDate { get; set; } public string OfficialSite { get; set; } public int Budget { get; set; } public int StatusId { get; set; } public virtual ICollection<Genre> Genres { get; set; } public virtual ICollection<Format> Formats { get; set; } public virtual ICollection<ProductionCompany> ProductionCompanies { get; set; } public virtual ICollection<Worker> Workers { get; set; } } public class Worker { public int Id { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public DateTime Birthday { get; set; } public string Biography { get; set; } public string BornName { get; set; } public double Height { get; set; } public DateTime? Died { get; set; } public byte[] ImageData { get; set; } public string ImageMimeType { get; set; } public bool IsActor { get; set; } public bool IsDirector { get; set; } public bool IsWriter { get; set; } public bool IsProducer { get; set; } public bool IsStar { get; set; } public virtual ICollection<Movie> Movies { get; set; } } in this Relation i got the movieId and the workerId but i also got some more fields if the person acted or writen or producer etc. how do i define the relation entity class if needed and when i want to get just the ppl that acted in the movie how do i wrote such a linq query A: You need to introduce an additional entity in your model WorkerMovie and convert the many-to-many relationship between Worker and Movie into two one-to-many relationships - one between Worker and WorkerMovie and the other between Movie and WorkerMovie. A sketch: public class WorkerMovie { [Key, Column(Order = 0)] public int WorkerId { get; set; } [Key, Column(Order = 1)] public int MovieId { get; set; } public Worker Worker { get; set; } public Movie Movie { get; set; } public bool WorkedAsActor { get; set; } public bool WorkedAsWriter { get; set; } public bool WorkedAsProducer { get; set; } // etc. } public class Movie { // ... public virtual ICollection<WorkerMovie> WorkerMovies { get; set; } // remove ICollection<Worker> Workers } public class Worker { // ... public virtual ICollection<WorkerMovie> WorkerMovies { get; set; } // remove ICollection<Movie> Movies } If you want only to find the workers who were actors in a particular movie with a movieId you can write: var workersAsActors = context.WorkerMovies .Where(wm => wm.MovieId == movieId && wm.WorkedAsActor) .Select(wm => wm.Worker) .ToList(); Here is another answer to a very similar question with many more examples of possible queries: Create code first, many to many, with additional fields in association table
{ "language": "en", "url": "https://stackoverflow.com/questions/7615715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery val() indexOf not working Trying to do something if the input value contains a certain word but this doesn't work: var formMain = $('#MainForm :input[name="Search"]'); if ((formMain).value.indexOf('word') >= 0) { alert('HAS THIS WORD IN IT!'); Example Form: <form onsubmit="return OnSubmitSearchForm(event, this);" action="/searchresults.asp" id="MainForm" name="MainForm" method="post" class="search_results_section"> <input type="hidden" value="word" name="Search"> <input type="hidden" value="" name="Cat"> </form> A: Your title mentions val() but you're not actually using it. formMain is a jquery object and has no value, you should use val(). var formMain = $('#MainForm :input[name="Search"]'); if (formMain.val().indexOf('word') >= 0) { alert('HAS THIS WORD IN IT!'); } Also note that formMain is a misleading variable name as it is not the main form but rather a jquery object which contains the search input. A: $(function(){ var formMain = $('#MainForm input[name="Search"]').val(); if (formMain.indexOf('word') >= 0) { alert('HAS THIS WORD IN IT!'); } }); A: possibly you are doing mistake with selector and should use .val with selector only .... here is something for you check this http://jsfiddle.net/sahil20grover1988/V2dsn/3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7615719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I exit out from an infinitely runnng loop in JavaScript? Is it possible to stop an infinite loop from running at all? Right now I am doing something like this: var run = true; loop ({ if(run) { whatever } }, 30), Then when I want to stop it I change run to false, and to true when I want to start it again. But the loop is always running whatever I do. It just not executing the code inside. Is there a way to stop it completely? and make it start again when I want? A: If I am understanding your question correctly, what you need is the break keyword. Here's an example. A: SetInterval will give you a loop you can cancel. setInterval ( "doSomething()", 5000 ); function doSomething ( ) { // (do something here) } Set the interval to a small value and use clearinterval to cancel it A: function infiniteLoop() { run=true; while(run==true) { //Do stuff if(change_happened) { run=false; } } } infiniteLoop(); A: It may not be exactly what you are looking for, but you could try setInterval. var intervalId = setInterval(myFunc, 0); function myFun() { if(condition) { clearInverval(intervalId); } ... } setInterval will also not block the page. You clear the interval as shown with clearInterval. A: Use a while loop while(run){ //loop guts } When run is false the loop exits. Put it in a function and call it when you want to begin the loop again. A: The problem is that javascript only has a single thread to run on. This means that while you are infinitely looping nothing else can happen. As a result, it's impossible for your variable to ever change. One solution to this is to use setTimeout to loop with a very small time passed to it. For example: function doStuff(){ if(someFlag){ // do something } setTimeout(doStuff,1); } doStuff(); This will give the possibility for other actions to make use of the thread and potentially change the flag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get a consistent date format from NSDate? I'm using NSDates as keys for an NSDictionary, but for key value coding, I need a string. Importantly, I need it to not change representation across OSes or locales. When I show it to users, I'll use NSDateFormatter, of course, but internally it must always be the same. What's the best way get a consistent format as a string? A: Use NSDateFormatter and specify the time zone as GMT and the local as "en_US_POSIX". From Apple's: Data Formatting Guide If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences. Another option is to convert a NSDate to a NSTimeInterval with a method such as timeIntervalSince1970 and then to a hexascii value to use as a key. NSDate returns a time value relative to an absolute reference date—the first instant of 1 January 2001, GMT.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: when modification of the assigned variable will affect the value of original variable? >>> x = 10 >>> y = x >>> y = 100 >>> y # Changes on y will not be transferred to x 100 >>> x 10 >>> x2 = 'hello' >>> y2 = x2 >>> y2 = 'world' # Changes on y2 will not be transferred to x2 >>> y2 'world' >>> x2 'hello' >>> a = [1, 2] >>> b = a >>> b.append(3) # Changes on b will be transferred to a >>> b [1, 2, 3] >>> a [1, 2, 3] >>> x1 = {} >>> y1 = x1 >>> y1['h'] = 'hhh' # Changes on y1 will be transferred to x1 >>> y1 {'h': 'hhh'} >>> x1 {'h': 'hhh'} Question> In which cases, the value of the assigned variables will affect the value of original variables? Python version: Python 3.1.2 A: * *In some cases you are then rebinding one of the names, but not the other, so they now are bound to different objects. y = 100 # Rebind y. Doesn't change x. y2 = 'world' # Rebind y2. Doesn't change x2. *In other cases you are mutating the object. Then both names see the changes to the object. b.append(3) # Mutates the list that both a and b are bound to. y1['h'] = 'hhh' # Mutates the dictionary that both x1 and y1 are bound to. A: You are not changing values of a variable when you write y = x. You are binding an object to a name. In your example >>> a = [1, 2] >>> b = a You have one object (a list) with two names bound to that object. Naturally, mutating changes on that object are reflected when the same object is accessed by each different name. In your example >>> x = 10 >>> y = x >>> y = 100 You have 2 objects in play, integers with values 10 and 100. When you write y = 100 you are simply re-binding the name y to the other object. The name x is still bound to 10. A: You should consider that all variables in python are indeed pointers to objects. Case 1 When you write x = 10 the variable x is a pointer to a number object with value 10. y = x the variable y is a pointer to the same object currently pointed by x. y = 100 now the variable y is instead pointing to another number object with value 100. This clearly has no effect on the object that x is pointing to. Case 2 When you write x = [1, 2] x is pointing to an array object that contains two pointers to number objects with value 1 and 2. y = x y is now pointing to the same array as x y.append(3) this doesn't affect the variable y (this is the key point!), but alter the object it is pointing to (the array) by adding another element. Because x is also pointing to the same object the change will be visible from x too. A: Here's the thing: you can't actually really modify a variable in Python. Variables are just names for values. You can modify certain types of value, and you can "assign to" variables, which actually just causes them to refer to (i.e. name) some different value from what it did before. Integer and string values cannot be modified. Lists and dictionaries can. Writing code like b.append(3) (where a and b initially refer to some list value) causes the name b to be used to look up the list value, which is then modified (its .append method is called, which causes the change). Since a and b both refer to the same value, the change is "seen by" a. Writing code like b = a + [3] creates a new value with the concatenated list, and causes b to refer to this new value instead of the old one. The value referred to by a is unaffected, in the same way that if you calculate 2 + 3 = 5, 2 is still the same 2 that it was before you did the calculation. A: I don't know python much but I would assume if the value is a primitve type the original variable it not affected. Otherwise the value is only a reference which will change the original variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Too many arguments used by python scipy.optimize.curve_fit I'm attempting to do some curve fitting within a class instance method, and the curve_fit function is giving my class instance method too many arguments. The code is class HeatData(hx.HX): """Class for handling data from heat exchanger experiments.""" then several lines of methods that work fine, then my function is: def get_flow(pressure_drop, coeff): """Sets flow based on coefficient and pressure drop.""" flow = coeff * pressure_drop**0.5 return flow and the curve_fit function call def set_flow_array(self): """Sets experimental flow rate through heat exchanger""" flow = self.flow_data.flow pressure_drop = self.flow_data.pressure_drop popt, pcov = spopt.curve_fit(self.get_flow, pressure_drop, flow) self.exh.flow_coeff = popt self.exh.flow_array = ( self.exh.flow_coeff * self.exh.pressure_drop**0.5 ) gives the error get_flow() takes exactly 2 arguments (3 given) I can make it work by defining get_flow outside of the class and calling it like this: spopt.curve_fit(get_flow, pressure_drop, flow) but that's no good because it really needs to be a method within the class to be as versatile as I want. How can I get this work as a class instance method? I'd also like to be able to pass self to get_flow to give it more parameters that are not fit parameters used by curve_fit. Is this possible? A: Unlucky case, and maybe a bug in curve_fit. curve_fit uses inspect to determine the number of starting values, which gets confused or misled if there is an extra self. So giving a starting value should avoid the problem, I thought. However, there is also an isscalar(p0) in the condition, I have no idea why, and I think it would be good to report it as a problem or bug: if p0 is None or isscalar(p0): # determine number of parameters by inspecting the function import inspect args, varargs, varkw, defaults = inspect.getargspec(f) edit: avoiding the scalar as starting value >>> np.isscalar([2]) False means that the example with only 1 parameter works if the starting value is defined as [...], e.g.similar to example below: mc.optimize([2]) An example with two arguments and a given starting value avoids the inspect call, and everything is fine: import numpy as np from scipy.optimize import curve_fit class MyClass(object): def get_flow(self, pressure_drop, coeff, coeff2): """Sets flow based on coefficient and pressure drop.""" flow = coeff * pressure_drop**0.5 + coeff2 return flow def optimize(self, start_value=None): coeff = 1 pressure_drop = np.arange(20.) flow = coeff * pressure_drop**0.5 + np.random.randn(20) return curve_fit(self.get_flow, pressure_drop, flow, p0=start_value) mc = MyClass() print mc.optimize([2,1]) import inspect args, varargs, varkw, defaults = inspect.getargspec(mc.get_flow) print args, len(args) EDIT: This bug has been fixed so bound methods can now be passed as the first argument for curve_fit, if you have a sufficiently new version of scipy. Commit of bug fix submission on github A: If you define get_flow inside your HeatData class you'll have to have self as first parameter : def get_flow(self, pressure_drop, coeff): EDIT: after seeking for the definition of curve_fit, i found that the prototype is curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw) so the first arg must be a callable that will be called with first argument as the independent variable : Try with a closure : def set_flow_array(self): """Sets experimental flow rate through heat exchanger""" flow = self.flow_data.flow pressure_drop = self.flow_data.pressure_drop def get_flow((pressure_drop, coeff): """Sets flow based on coefficient and pressure drop.""" #here you can use self.what_you_need # you can even call a self.get_flow(pressure_drop, coeff) method :) flow = coeff * pressure_drop**0.5 return flow popt, pcov = spopt.curve_fit(get_flow, pressure_drop, flow) self.exh.flow_coeff = popt self.exh.flow_array = ( self.exh.flow_coeff * self.exh.pressure_drop**0.5 ) A: Trying dropping the "self" and making the call: spopt.curve_fit(get_flow, pressure_drop, flow) A: The first argument of a class method definition should always be self. That gets passed automatically and refers to the calling class, so the method always receives one more argument than you pass when calling it. A: The only pythonic way to deal with this is to let Python know get_flow is a staticmethod: a function that you put in the class because conceptually it belongs there but it doesn't need to be, and therefore doesn't need self. @staticmethod def get_flow(pressure_drop, coeff): """Sets flow based on coefficient and pressure drop.""" flow = coeff * pressure_drop**0.5 return flow staticmethod's can be recognized by the fact that self is not used in the function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TypeLoadException in COM Library I have a class library that has a class, MessageGroupInfo, that contains some string and bool properties. No methods. I use this class to pass info to a constructor of another class, MessageGrouper. These are used by a COM visible class library that is an Add-in to another app. Both the add-in assembly and the class library use .NET 4 client targets. When I call a method that uses MessageGrouper (and thus MessageGroupInfo), I get a TypeLoadException. It can't find MessageGroupInfo. I know it has resolved and loaded the class library because other code in that assembly is working just fine. I setup a quick WinForm app to see if it had an issue, but it worked fine. This problem originally occurred on a 64bit win7 box. It works fine on a XP 32bit box. So, could this be a 64 bit thing or a COM-64bit thing? Is there some setting I'm missing? Not that otherwise the add-in works well, calling many other methods in the class library. Thanks! A: Thanks to Hans, I figured out that the issue was .NET referencing an old DLL of the class library. The debugger was looking at the correct one (I.e. Intellisense could find the method), but that method wasn't actually in the DLL being referenced. I haven't figured out why this occurred, but the fix was to find all instanced of the DLL, delete them and rebuild. BAM. It worked. :D Thanks Hans for pointing me in the correct direction! A: It's likely to be a 64-bit thing. By default, .Net applications are built architecture-independent, which means they will be launched as 64-bit processes when on a 64-bit machine. A 64-bit process cannot load a 32-bit DLL, or vice versa. I had this problem myself with an app containing a WebBrowser control that couldn't instantiate Flash player for this reason. Just to complicate things further, there are two separate registry key trees for 32-bit and 64-bit COM classes; if your library is built architecture-independent it will likely get registered in the 64-bit tree when your native app is looking in the 32-bit tree. Change the project's platform target setting to x86 to ensure that your code is always treated as 32-bit. (In Visual Studio, you'll find this on the project properties, Build tab.) Even with that setting, though, I'm not sure of what madness you'll run into trying to build an installer that deals with the details of 32 vs 64 bit registration. Visual Studio's installer projects may or may not do the right thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java AES without padding What are some of the simplest ways to AES encrypt and decrypt a 16 byte array without the automatic padding? I have found solutions that use external libraries, but I want to avoid that if possible. My current code is SecretKeySpec skeySpec = new SecretKeySpec(getCryptoKeyByteArray(length=16)); // 128 bits Cipher encryptor = Cipher.getInstance("AES"); encryptor.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = encryptor.doFinal(plain); How can I prevent the padding? The plain data is always fixed length and includes its own padding. How can I allow plain to be 16 bytes without causing encrypted to become 32 bytes? A: Agree with @rossum, but there's more to it: CTR mode needs an initialisation vector (IV). This is a "counter" (which is what "CTR" refers to). If you can store the IV separately (it doesn't need to be protected) that would work. You'll need the same IV value when you decrypt the data. If you don't want to store the IV and you can guarantee that no two values will be encrypted with the same key, it's fine to use a fixed IV (even an array of 0s). The above is very important because encrypting more than one message with the same key/IV combination destroys security. See the Initialization vector (IV) section in this Wikipedia article: http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation An AES CTR implementation of your code might be: SecretKeySpec skeySpec = new SecretKeySpec(getCryptoKeyByteArray(length=16)); Cipher encryptor = Cipher.getInstance("AES/CTR/NoPadding"); // Initialisation vector: byte[] iv = new byte[encryptor.getBlockSize()]; SecureRandom.getInstance("SHA1PRNG").nextBytes(iv); // If storing separately IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); encryptor.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec); byte[] encrypted = encryptor.doFinal(plain); A: CTR mode does not require padding: "AES/CTR/NoPadding". A: See my comment. Sorry I probably should have taken a closer look the first time. * *Change "AES" to "AES/CBC/NoPadding" *Change decryptor.init(Cipher.DECRYPT_MODE, skeySpec); to decryptor.init(Cipher.DECRYPT_MODE, skeySpec, encryptor.gerParameters()); To encrypt only 16 bytes of data, fixed length, using a method that requires no initialization vector to be saved, Change "AES" to "AES/ECB/NoPadding" I pick ECB because that is the default. If you need to encrypt more than 16 bytes, consider using something other than ECB, which suffers a certain repetition detection flaw In this bitmap example, this image has repeated white blocks, so you can deduce the outline of the image simply by looking for where the blocks become different. If you are only encrypting one block, it doesn't really matter though, only if you are encrypting multiple blocks that are combined does ECB become revealing. Related: https://security.stackexchange.com/questions/15740/what-are-the-variables-of-aes
{ "language": "en", "url": "https://stackoverflow.com/questions/7615743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to access a custom config from my class library application? I have a custom config in my Infrastructure Project, but when my app start only my web.config is recognized. I don't want to place the configuration of this custom config file in my web.config because this configuration is responsability for Infrastructure Layer. How I use this custom config from another project in my web project? A: The previous answers to this question are failing to inform you of a critical point. .NET is designed to have a single configuration process for each AppDomain. All class libraries will use the configuration file of the application which calls them. In your case, your class library will use the web.config. If your class library were being used from a console application, then it would use the application.exe.config file. When you think about it, this is the only thing that makes sense. If your class library is used from two separate applications, then it will have two separate configurations. These configurations must be managed on behalf of the calling application. A: Something like this: var exeMap = new ExeConfigurationFileMap {ExeConfigFilename = @"C:\Path\To\Your\File"}; Configuration myConfig = ConfigurationManager.OpenMappedExeConfiguration( exeMap, ConfigurationUserLevel.None ); A: Assuming that the infrastructure project is a class library, have you considered creating properties to expose the app.config (?) settings to the front-end? Here is an example of what I mean. Keep in mind that this is just an example. It's a property that demonstrates how to expose a config value through a property. In your case, the property would retrieve a value from your custom config file. public string GetConfigurationValue(string Key) { return GetValueFromConfiguration(Key); } One thing I'm wondering is why you're creating a custom configuration file rather than just creating a configuration section that you can integrate into the app.config file. It seems like you're making things much more difficult than they need to be.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Showing the searchbar only when user pull down the table I have a table view with a search bar on top of it. My requirement is to do not show the search bar when someone open the page but when someone slides the table down then the search bar should be visible. A: Related to murat's answer, here's a more portable and correct version that will do away with animated offsetting on view load (it assumes the search bar has an outlet property called searchBar): - (void)viewWillAppear:(BOOL)animated { self.tableView.contentOffset = CGPointMake(0, self.searchBar.frame.size.height); } UPDATE: To accommodate tapping on the search icon in the section index, the following method needs to be implemented, which restores the content offset: - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { index--; if (index < 0) { [tableView setContentOffset:CGPointMake(0.0, -tableView.contentInset.top)]; return NSNotFound; } return index; } A: In your controller's viewDidAppear: method, set the contentOffset property (in UIScrollView) of your table view to hide the search bar. - (void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; self.tableView.contentOffset = CGPointMake(0, SEARCH_BAR_HEIGHT); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7615747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Rails 2.3.x & Koala & Facebook: certificate verify failed I'm trying to get Facebook Graph API to work in Rails 2.3.5 using Koala. All works fine in my dev environment (Mac) but fails in production (Ubuntu 8.04.1). Test code: cookies = {"__utma"=>"158657023.1470934917.1315425280.1317394623.1317406089.55", "28aac256bbbe09dcae1eb7086ae1c326"=>"c14d42fcd1a6700aa6198a2ecd7587fa", "fbsetting_28aac256bbbe09dcae1eb7086ae1c326"=>"{\"connectState\":1,\"oneLineStorySetting\":3,\"shortStorySetting\":3,\"inFacebook\":false}", "__utmb"=>"158657023.23.10.1317406089", "28aac256bbbe09dcae1eb7086ae1c326_session_key"=>"c76e09e8124a194e26a9c1e9.1-635077092", "28aac256bbbe09dcae1eb7086ae1c326_user"=>"635077092", "__utmc"=>"158657023", "28aac256bbbe09dcae1eb7086ae1c326_expires"=>"0", "__utmz"=>"158657023.1317406089.55.52.utmcsr=angel.co|utmccn=(referral)|utmcmd=referral|utmcct=/thingspotter", "fbs_265881436784759"=>"\"access_token=AAADx0ViXiHcBAFMuyXsGRdZB4GmmHyZBQl9h7Ymqi6z0kk3ko5jRJGmdWZCdJQm7dWg2nCyraaZCJuJ6iurPxDHL6bZCMzosZD&expires=0&secret=815a69d93434d26034ada92bb2e80ae9&session_key=858594415a361e318af23dd1.1-635077092&sig=55f7e932f8e68a7dad6ae35af1877b45&uid=635077092\"", "_DefaultAppFacebook_session"=>"BAh7CToPc2Vzc2lvbl9pZCIlYzZjZGU5ZmJlNGU0NTM2ZjExNmQ1ZGQ5ZTc3ZjhiZDUiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA6EF9jc3JmX3Rva2VuIjFnZllGbGFVK0hMdVdZcDZaZjhJY3VJWVlZY2dEakc4VCtpM0dWTktSbFFRPSILbGF5b3V0IgxkZXNrdG9w--195b2d14ce7593502ec6d161906ceb0c38ed4219", "28aac256bbbe09dcae1eb7086ae1c326_ss"=>"0854c086618a5e075e2d9a866ce03f82"} @facebook_cookies = Koala::Facebook::OAuth.new.get_user_info_from_cookie(cookies) oauth_access_token = @facebook_cookies["access_token"] graph = Koala::Facebook::GraphAPI.new(oauth_access_token) fb_user = graph.get_object('me') Produces the error message: OpenSSL::SSL::SSLError: certificate verify failed from /usr/lib/ruby/1.8/net/http.rb:586:in `connect' from /usr/lib/ruby/1.8/net/http.rb:586:in `connect' from /usr/lib/ruby/1.8/net/http.rb:553:in `do_start' from /usr/lib/ruby/1.8/net/http.rb:542:in `start' from /usr/lib/ruby/1.8/net/http.rb:1035:in `request' from /usr/lib/ruby/1.8/net/http.rb:772:in `get' from /usr/lib/ruby/gems/1.8/gems/faraday-0.7.4/lib/faraday/adapter/net_http.rb:49:in `call' from /usr/lib/ruby/gems/1.8/gems/faraday-0.7.4/lib/faraday/request/url_encoded.rb:14:in `call' from /usr/lib/ruby/gems/1.8/gems/faraday-0.7.4/lib/faraday/request/multipart.rb:13:in `call' from /usr/lib/ruby/gems/1.8/gems/faraday-0.7.4/lib/faraday/connection.rb:203:in `run_request' from /usr/lib/ruby/gems/1.8/gems/faraday-0.7.4/lib/faraday/connection.rb:85:in `get' from /usr/lib/ruby/gems/1.8/gems/koala-1.2.0/lib/koala/http_service.rb:49:in `send' from /usr/lib/ruby/gems/1.8/gems/koala-1.2.0/lib/koala/http_service.rb:49:in `make_request' from /usr/lib/ruby/gems/1.8/gems/koala-1.2.0/lib/koala.rb:131:in `make_request' from /usr/lib/ruby/gems/1.8/gems/koala-1.2.0/lib/koala.rb:57:in `api' from /usr/lib/ruby/gems/1.8/gems/koala-1.2.0/lib/koala/graph_api.rb:215:in `graph_call' from /usr/lib/ruby/gems/1.8/gems/koala-1.2.0/lib/koala/graph_api.rb:36:in `get_object' It's obviously something related to SSL certificates, so I've tried to configure Koala: Koala.http_service.http_options = { :ssl => { :ca_file => '/etc/ssl/certs', :verify_mode => OpenSSL::SSL::VERIFY_PEER, :verify => true } } ...and also download http://curl.haxx.se/ca/cacert.pem to the /etc/ssl/certs folder. Does not make any visible difference though. Relevant gems are: faraday (0.7.4) koala (1.2.0) rails (2.3.5) ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux] I've found related SO posts but no perfect match. A: I had the same problem with Rails 3.2, Ruby 1.9.3, Ubuntu 11.10 TenJack's answer worked except the cert file is now ca-certificates.crt , so: Koala::HTTPService.http_options[:ssl] = {:ca_file => '/etc/ssl/certs/ca-certificates.crt'} A: I found the solution while browsing (taken verbatim): Tweek for ssl error (when connecting to facebook using koala gem) in Ubuntu: Open the file ".rvm/gems/ruby-1.9.2-p136/gems/koala-1.0.0/lib/koala/http_services.rb" Add the following lines around line 60: http = create_http(server(options), private_request, options) http.use_ssl = true if private_request http.verify_mode = OpenSSL ::SSL::VERIFY_PEER http.ca_path = '/etc/ssl/certs' if File.exists?('/etc/ssl/certs') # Ubuntu http.ca_file = '/opt/local/share/curl/curl-ca-bundle.crt' if File.exists? ('/opt/local/share/curl/curl-ca-bundle.crt') # Mac OS X (Reference article : http://martinottenwaelter.fr/2010/12/ruby19-and-the-ssl-error/) If the certificate still seems missing (error doesnt go away) add this certificate : http://curl.haxx.se/ca/cacert.pem to the /etc/ssl/certs folder with the file name as cacert.pem. A: I had the exact same problem (Rails 2.3.8, Ruby 1.8.7, Ubuntu 8.04), the only way I could get it to work was to specify the exact path of the ca-bundle.crt file (http://certifie.com/ca-bundle/ca-bundle.crt.txt): Koala::HTTPService.http_options[:ssl] = {:ca_file => '/etc/ssl/certs/ca-bundle.crt'}
{ "language": "en", "url": "https://stackoverflow.com/questions/7615750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DataMapper filter records by association count With the following model, I'm looking for an efficient and straightforward way to return all of the Tasks that have 0 parent tasks (the top-level tasks, essentially). I'll eventually want to return things like 0 child tasks as well, so a general solution would be great. Is this possible using existing DataMapper functionality, or will I need to define a method to filter the results manually? class Task include DataMapper::Resource property :id, Serial property :name , String, :required => true #Any link of type parent where this task is the target, represents a parent of this task has n, :links_to_parents, 'Task::Link', :child_key => [ :target_id ], :type => 'Parent' #Any link of type parent where this task is the source, represents a child of this task has n, :links_to_children, 'Task::Link', :child_key => [ :source_id ], :type => 'Parent' has n, :parents, self, :through => :links_to_parents, :via => :source has n, :children, self, :through => :links_to_children, :via => :target def add_parent(parent) parents.concat(Array(parent)) save self end def add_child(child) children.concat(Array(child)) save self end class Link include DataMapper::Resource storage_names[:default] = 'task_links' belongs_to :source, 'Task', :key => true belongs_to :target, 'Task', :key => true property :type, String end end I would like to be able to define a shared method on the Task class like: def self.without_parents #Code to return collection here end Thanks! A: DataMapper falls down in these scenarios, since effectively what you're looking for is the LEFT JOIN query where everything on the right is NULL. SELECT tasks.* FROM tasks LEFT JOIN parents_tasks ON parents_tasks.task_id = task.id WHERE parents_tasks.task_id IS NULL You parents/children situation makes no different here, since they are both n:n mappings. The most efficient you'll get with DataMapper alone (at least in version 1.x) is: Task.all(:parents => nil) Which will execute two queries. The first being a relatively simple SELECT from the n:n pivot table (WHERE task_id NOT NULL), and the second being a gigantic NOT IN for all of the id's returned in the first query... which is ultimately not what you're looking for. I think you're going to have to write the SQL yourself unfortunately ;) EDIT | https://github.com/datamapper/dm-ar-finders and it's find_by_sql method may be of interest. If field name abstraction is important to you, you can reference things like Model.storage_name and Model.some_property.field in your SQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does my JOIN still trigger n+1 selects in active record? PortfolioEngine::Portfolio Load (0.3ms) SELECT "portfolio_engine_portfolios".* FROM "portfolio_engine_portfolios" INNER JOIN "portfolio_engine_items" ON "portfolio_engine_items"."portfolio_id" = "portfolio_engine_portfolios"."id" ORDER BY portfolio_engine_portfolios.sort_index ASC, portfolio_engine_portfolios.sort_index ASC, portfolio_engine_items.sort_index ASC PortfolioEngine::Item Load (0.2ms) SELECT "portfolio_engine_items".* FROM "portfolio_engine_items" WHERE "portfolio_engine_items"."portfolio_id" = 2 ORDER BY portfolio_engine_items.sort_index ASC, sort_index asc PortfolioEngine::Item Load (0.3ms) SELECT "portfolio_engine_items".* FROM "portfolio_engine_items" WHERE "portfolio_engine_items"."portfolio_id" = 3 ORDER BY portfolio_engine_items.sort_index ASC, sort_index asc PortfolioEngine::Item Load (0.2ms) SELECT "portfolio_engine_items".* FROM "portfolio_engine_items" WHERE "portfolio_engine_items"."portfolio_id" = 1 ORDER BY portfolio_engine_items.sort_index ASC, sort_index asc The n+1 is triggered by looping through each portfolio's items. class Portfolio < ActiveRecord::Base has_many :items, order: "portfolio_engine_items.sort_index asc", autosave: true, inverse_of: :portfolio default_scope :order => 'portfolio_engine_portfolios.sort_index ASC' end class Item < ActiveRecord::Base belongs_to :portfolio belongs_to :client has_many :images, order: "sort_index ASC", autosave: true, inverse_of: :item end I have no idea, why this happens.... @portfolios = PortfolioEngine::Portfolio. joins(:items). order("portfolio_engine_portfolios.sort_index ASC, portfolio_engine_items.sort_index ASC"). all A: Have you tried includes instead of joins?
{ "language": "en", "url": "https://stackoverflow.com/questions/7615754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a version of Youtube Chromeless player that works on iPad/iPhone I'm building a site which requires being able to have advanced control over a video embed. I'd like to use the Chromeless player. The example from Google is flash based. Is there an alternative version that can be used without flash? A: The closest thing to the Chromeless Youtube palyer that would work for the iPhone/iPad, seems to be using HTML5 iframe with Youtube API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }