text
stringlengths
8
267k
meta
dict
Q: Constant array of constant objects How do you define constant array of constant objects in C (not C++)? I can define int const Array [] = { /* init data here */ }; but that is a non-constant array of constant objects. I could use int const * const Array = { /* init data here */ }; and it would probably work. But is it possible do this with array syntax? (Which looks more clean) A: The "double constness" thing applies only to pointers because they can be changed to point to something else1, since the characteristics of arrays are statical by themselves (arrays cannot be changed in size/type/to point to something else) the only const you can apply is to their elements. * *so you have the variations "pointer to an int", "pointer to a constant int", "constant pointer to an int", "constant pointer to a constant int". A: If you want the elements of array do not modify, just use this: const int Array[]; A: An array cannot be "constant" -- what is that even supposed to mean? The array size is already a compile-time constant in any case, and if all the members are constants, then what else do you want? What sort of mutation are you trying to rule out that is possible for a const int[]?
{ "language": "en", "url": "https://stackoverflow.com/questions/7633776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: geocoding database provider(sql, nosql) and schema Companies like Yahoo, Google, MS provide geocoding services. I'd like to know what is the best way to organize the backend for such services - what is the optimal solution in terms of database provider(SQL vs NOSQL) and database schema. Some providers use Extensible Address Language (xAL) to describe an entity in the geocoding response. xAL has more than 30 data elements. Google geocoding API has about 20 data elements. So in case of SQL database there will be 20-30 tables with mostly one-to-many relationships via foreign keys? What about NOSQL databases, like MongoDB. How would one organize such a database? lots of collections for each data element, similar to SQL? One collection where each document completely describes given entity in the address space? A: It's hard to say... It depends on what you need to do with the data in term of analysis and caching. I had to deal with geo coordinates. But our app is very simple and we don't need to manipulate the geolocations in DB, simply store and retrieve. So I simply store start and end points in 2 columns of each route and a polyline in a binary column, with a few milestones being saved in a dedicated SQL table. But for an advanced use of our APP we considered using this: https://simplegeo.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7633784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: How can I let the user choose a contact? In my app I need the user to choose a contact (or type a phone number) I want to do it (almost) exactly like in the existing UI for sending SMS (I hope it's the same in all android devices, but if not than spesificly like in the smasung galaxy s (1)) : that is have a single textBox that if the user clicks he can type a phne number, and also clicking the textBox opens two tabs below "recent" and "contacts". The problem I have in implementing this is only in how to let the user choose from his contacts/recent (if the user clicks the recent/contacts I don't know what to do so it will be like in the existing UI for sending SMS).
{ "language": "en", "url": "https://stackoverflow.com/questions/7633785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableView crashes when scroll down I know there's a lot of questions about this topic but I have not be able to solve my problem... Well, I have detected the problem, it's the contactsArray that's global. If I comment that lines, the table works fine. The code is this: @interface ContactsView : UIViewController <UITableViewDelegate, UITableViewDataSource>{ IBOutlet UITableView *table; NSMutableArray * contactsArray; } @property (nonatomic, retain) NSMutableArray *contactsArray; @property (nonatomic, retain) IBOutlet UITableView *table; In viewDidLoad I do: contactsArray = [[NSMutableArray alloc] init]; And here the implementation of each cell: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"ContactsCell"; ContactsCell *cell = (ContactsCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell==nil){ NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ContactsCell" owner:self options:nil]; for(id currentObject in topLevelObjects){ if([currentObject isKindOfClass:[UITableViewCell class]]){ cell = (ContactsCell *) currentObject; break; } } } // Configure the cell... Person *persona = [[Person alloc] init]; persona=[contactsArray objectAtIndex:indexPath.row]; [cell setCellNames:[persona name]]; [cell setCellStates:@"En Donosti"]; [persona release]; return cell; } If I comment the persona=[contactsArray objectAtIndex:indexPath.row]; and [cell setCellNames:[persona name]]; So, I'm pretty sure that the problem is with contactsArray Any idea why is it crashing? Thanks! A: You must not release persona object as you just get it from array. Also the Person *persona = [[Person alloc] init]; has no effect as you immediately overwrite object you create with object from array. Fixed code should look like: Person *persona = [contactsArray objectAtIndex:indexPath.row]; [cell setCellNames:[persona name]]; [cell setCellStates:@"En Donosti"]; return cell;
{ "language": "en", "url": "https://stackoverflow.com/questions/7633790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: set visibility on textBox from form1 to form2 From other Form i want to set visibility for textBoxes on this form but i down't know how to call TextBoxes and set property Visible = false. I try with Enums but i still can't solve problem. I can not cast or do anything. So how can i call textBox From form1 to form2... i am using C# and CF 3.5 public enum VnosTextBoxType { Ean, PredmetObravnave, Tse, Kolicina, EnotaMere, Lokacija, Zapora, Sarza, SarzaDobavitelja, Datumod, DatumDo } this are names for all my TextBoxes. I have TextBoxes with names like txtEan, txtPredmetObravnave,.. A: What about writing on Form2 a method like this: public void SetTBVisible(string name, bool visible) { this.Controls[name].Visible = visible; } and call this form your Form1? EDITED: public void SetTBVisible(string name, bool visible) { string cName = name.ToLower(); foreach(Control c in this.Controls) if (c.Name.ToLower() == cName) { c.Visible = visible; break; } } A: Make a new class called Globals.cs write: public static Form1 MainForm; public static Form2 ChildForm; go to Form1 and make the event: form load put: Globals.MainWindow = this; and: CheckForIllegalCrossThreadCalls = false; and do the same in Form2 with ChildForm now you can call form2 with: Globals.ChildForm.TextBox1.Visible = false; Edit: don't forget to make your textBox public. A: let say you want to set Visible = false for textbox1 of form1 when you create instance of form2 then you have pass the instance of form1 into its constructor like this Class Form1 : Form { public void setTextbox(bool val) { this.Textbox1.visible=val; } Public void showForm2() { Form2 f2= new Form2(this); f2.show(); } } Class Form2 : Form { Form1 f1; public Form2(Form form1) { f1=form1; } public void setTb() { f1.setTextbox(false); } } I Hope this will help you
{ "language": "en", "url": "https://stackoverflow.com/questions/7633791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Start activity from widget & ignore back stack Let's consider simple DB access application with two activities: * *A - list of entries from DB *B - input form to enter new data to DB, with two buttons: Save / Cancel Application starts with A (list) and from A user may go to B (input form). To make entering new data more efficient I created a widget to jump directly to B (PendingIntent). The observed behaviour of the application is like that: * *If the first action of the user is widget (empty back stack) => the application opens B and when user click Save or Cancel activity is finished and focus goes back to Android desktop. *If main application was started before (A is on back stack) => B is still properly opened from widget however when user click Save or Cancel focus goes back to A The behaviour described in 2 is OK when user starts B from A. However I would like to avoid it when B is started from widget. Any hints ? A: I have a situation where I need to do something similar. My quick fix was to add a "EXTRA_LAUNCHED_BY_WIDGET" Extra to the Intent launched by the widget. Then, in my Activity I treat that as a special case. I needed to override the Back button behaviour, but you could just as easily use this case elsewhere, e.g. in other overridden Activity methods. @Override public void onBackPressed() { Bundle extras = getIntent().getExtras(); boolean launchedFromWidget = false; if (extras.containsKey("EXTRA_LAUNCHED_BY_WIDGET")) { launchedFromWidget = extras.getBoolean("EXTRA_LAUNCHED_BY_WIDGET"); } if (launchedFromWidget) { // Launched from widget, handle as special case } else { // Not launched from widget, handle as normal } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert native C++ memory into C# structure? I have the following native function interface in C++: int func1(void* param, int sizeOfParam). In documentation the following example of call is provided: typedef struct { int x; int y; int width; int height; } Rect; Rect rect; int func1((void*)&rect, sizeof(rect)); I need to call this function from C# code. I have the following header in C# from developers of native library: [DllImport(NATIVE_DLL_NAME, CallingConvention = CallingConvention.Cdecl, EntryPoint = "func1")] private static extern int func1(IntPtr param, int sizeOfParam); I also have the following C# structure Rect: public struct Rect { int x; int y; int width; int height; }; I need to call func1 in C# code and pass Rect: I do the following: Rect rect = new Rect(); int rectSize = System.Runtime.InteropServices.Marshal.SizeOf(rect); func1(???, rectSize); What to place in position of ??? where rect should be passed (but it is not possible because of incompatible types)? It seems that IntPtr should be passed and then converted to struct rect. How to achieve this? (rect is output parameter here) UPDATE: It is desired not to change signatures of C++ code and C# wrappers - it is third part code. Moreover it is not always variable of Rect is passed as first param of func1 A: You changed the rules of the game to disallow modifications to the C# code. And so the P/invoke must be of this form: private static extern int func1(IntPtr param, int sizeOfParam); In that case you need to do the marshalling by hand: int size = Marshal.SizeOf(typeof(Rect)); IntPtr param1 = Marshal.AllocHGlobal(size); try { func1(param1, size); Rect rect = (Rect)Marshal.PtrToStructure(param1, typeof(Rect)); } finally { Marshal.FreeHGlobal(param1); } A: I'd probably make life a bit easier for yourself by using an out param of type Rect rather than IntPtr. Like this: [StructLayout(LayoutKind.Sequential)] public struct Rect { int x; int y; int width; int height; }; [DllImport(NATIVE_DLL_NAME, CallingConvention = CallingConvention.Cdecl, EntryPoint = "func1")] private static extern int func1(out Rect param, int sizeOfParam); Then to call the function you can write this: Rect param; int res = func1(out param, Marshal.SizeOf(typeof(Rect))); A: Try passing ref Rect instead. [DllImport(NATIVE_DLL_NAME, CallingConvention = CallingConvention.Cdecl, EntryPoint = "func1")] private static extern int func1(ref Rect param, int sizeOfParam);
{ "language": "en", "url": "https://stackoverflow.com/questions/7633794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Query is not retrieving the data from table im trying to integrate a database into my project.This is for first time im implementing a database project.I integrated the database into my project.Database has 3 columns named rowid,col1,col2.Below code i used for acessing the datafrom database.But it is not enetering in "if loop"Can anyone help me where im doing wrong in this case.Thanks in advance.![enter image description here][1] /* -(void)print { sqlite3_stmt *statement; qsql=[NSString stringWithFormat:@"SELECT * from light where rowid = '%d'",1]; if(sqlite3_prepare_v2(database, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK) { NSLog(@"hhhhhhhhh"); while (sqlite3_step(statement) == (SQLITE_ROW)){ NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)]; // tv.text=qsql; } }}*/ -(void)print { sqlite3_stmt *statement; //qsql=[NSString stringWithFormat:@"SELECT * from light where rowid = %d",1]; qsql=[NSString stringWithFormat:@"SELECT * from light where rowid = %i",1]; //const char *sqlStatement = [qsql cStringUsingEncoding:NSUTF8StringEncoding]; const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding]; if(sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL) == SQLITE_OK) { NSLog(@"hhhhhhhhh"); while (sqlite3_step(statement) == (SQLITE_ROW)){ // NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)]; NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%i",sqlite3_column_int(statement, 0)]]; // tv.text=qsql; } } } -(void) checkAndCreateDatabase{ BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; success = [fileManager fileExistsAtPath:databasePath]; if(success) return; NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName]; [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil]; [fileManager release]; } -(void) openDB { databaseName = @"Lighthr.sqlite"; NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDir = [documentsPaths objectAtIndex:0]; databasePath = [documentDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; if(sqlite3_open([databasePath UTF8String],&database) == SQLITE_OK){ NSLog(@"coming here???"); } } [1]: http://i.stack.imgur.com/lm1ZV.png A: because rowid is always integer and you are trying to access using string. I thing you have to try this. Edit if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { qsql=[NSString stringWithFormat:@"SELECT * from light where rowid = %i",1]; const char *sqlStatement = [qsql cStringUsingEncoding:NSUTF8StringEncoding]; if(sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK) { NSLog(@"hhhhhhhhh"); while (sqlite3_step(statement) == (SQLITE_ROW)){ NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)]; // tv.text=qsql; } } } A: Are you trying to test without your "where" clause ? And what is the error code return by sqlite3_prepare_v2 ? int sql_answer = sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL); NSLog(@" SQL answer : %d",sql_answer ); if(sql_answer == SQLITE_OK) { ... A: NSString *Q_NO = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)]; above stameny replace with below statement NSString *Q_NO = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%i",sqlite3_column_int(statement, 0)]]; and const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding]; now replace [qsql UTF8String] with qsql_stament. It will work fine. A: i think you should do in this way . -(void)print { sqlite3_stmt *statement; qsql=[NSString stringWithFormat:@"SELECT * from light where rowid = %d",1]; const char *qsql_stament = [qsql cStringUsingEncoding:NSUTF8StringEncoding]; if(sqlite3_prepare_v2(database, qsql_stament, -1, &statement, NULL) == SQLITE_OK) { NSLog(@"hhhhhhhhh"); while (sqlite3_step(statement) == (SQLITE_ROW)){ NSString *Q_NO =[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)] }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to manage Excel With Delphi 7 using paradox file? How can I open Excel file in Delphi 7 and move the data to a paradox file? A: Using the Ado___ components From the ADO tab. To "connect" with the file use the TAdoConnection then double-click it, in the provider tab you must select "Microsoft Jet 4.0 OLE DB Provider", in the connection tab you put the name of the file relative to the current directory of your process, in the fourth tab in extended properties you select the version of excel that you want to use. Note: This connection only works at runtime. Now you can add an TAdoQuery and link it up with the TAdoConnection, in this query you can use SQL DML statements like select, insert (didn't try this one) and update, delete doesn't work, the only trick is that instead of using table names in the from clause you use excel ranges, for example A range from the A1 cell to to the C10 cell on the sheet MySheet1: [MySheet1$A1:c10], here's the full select for this range: Select * From [MySheet1$A1:c10] You can also use named ranges [MyNamedRangeName$] and entire sheets: [MyEntireSheet$] (notice the mandatory $ after the names). Now with the data in a dataset you should be able to move it to the paradox dataset. This about.com article explains in more detail: http://delphi.about.com/od/database/l/aa090903a.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7633806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check movieClips is visible under mask This was something I looked at a while back but couldn't figure it out. Now returning to give it another go. Basically I want to find out how to check if a movieclip is visible under a mask. I've got a row of thumbs in a movieclip under a mask. Some are out with the the masked area so I've got some script to make the movieclip scroll the other thumbs into view of the masked area. Is there any code I can apply to the thumbs to check if they are in or not in view of the masked area? Any help or insight would be very much appreciated. A: You can use Rectangle intersection check to see if the bounds of the mask intersects with the bounds of the thumbs. var maskBounds : Rectangle = myMask.getBounds(this); var thumb : MovieClip; var thumbBounds : Rectangle; for(var i : int = 0 ; i < _thumbs.length ; i++) { thumb = _thumbs[i]; thumbBounds = thumb.getBounds(this); if(maskBounds.intersects(thumbBounds)) { trace(i, "in view"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.net / IIS authentication for static content (for example images) best practices I need to make a website with authentication of static content (images, html files, etc.) I've already build a private section protected with a login form against a users database; but if a user knows the url of a static file of that section, it will be served anyway, logged in or not. What are the best practices for protecting static content in asp.net? I've found this article from 4 guys from rolla, it is suitable (it works only in IIS 7.0)? Best practices for IIS 6.0? EDIT: if i put <location path="ImagesPrivate"> <system.web> <authorization> <deny users="?"/> </authorization> </system.web> </location> this works well, but only for .aspx files, not images or other static contents. A: If you want to use forms auth to protect non-.net content (such as static content) on IIS6 you have 2 choices. One is but the content in a non-browsable location & build a handler to get the content. The other option is to use wildcard mapping. You should probably test both approaches to see which best fits your use cases. A: please see this link http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cd72c0dc-c5b8-42e4-96c2-b3c656f99ead.mspx?mfr=true " By default, IIS handles all static content itself, only invoking the ASP.NET runtime when an ASP.NET resource is requested. So we need to map those static file extensions to be handled by ASP.NET run-time"
{ "language": "en", "url": "https://stackoverflow.com/questions/7633813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: c# Automatic colorcycle for legends in MS Chart I'm loading dataseries into a MS Chart and would like to set the legend/series colors automatically instead of having to choose manually.. Does anyone know of a good way to do that, so colors that are too close doesnt get chosen for the same chart? Thanks! A: Are you looking for palettes? This code is straight out of the chart samples (http://archive.msdn.microsoft.com/mschart) for palettes: // Standard palette chart2.Palette = ChartColorPalette.BrightPastel; // Use a custom palette Color[] colorSet = new Color[4] { Color.Red, Color.Blue, Color.Green, Color.Purple }; chart2.PaletteCustomColors = colorSet; chart2.Palette = ChartColorPalette.None;
{ "language": "en", "url": "https://stackoverflow.com/questions/7633819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How the jvm process can still be alive after crash in native code (EXCEPTION_ACCESS_VIOLATION (0xc0000005) )? I have a java application which uses JOGL panels to execute some openGL commands (they depend on some JNI dynamic libraries). Sometimes my application crashes and the jvm prompts me the crash report indicating that the crash is caused by an EXCEPTION_ACCESS_VIOLATION (0xc0000005) in native code, but the process is often still alive, while I expect it to be halted by the OS (Windows 7 in my case). How is it possible? Is there a way to recognize this situation?
{ "language": "en", "url": "https://stackoverflow.com/questions/7633821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: c# overwriting/saving current file I am doing editor in c#, windows forms. I wish to save 'new content' of file in the same file (usual usage of 'save' option) but I receive IOException, [ the process cannot access the file ' filename' because it is being used by another process. I have method that writes to a NEW file and it works. How to use it to overwrite current file. Edit: I am using binarywriter http://msdn.microsoft.com/en-us/library/atxb4f07.aspx A: Chances are that when you loaded the file, you didn't close the FileStream or whatever you used to read it. Always use a using statement for your streams (and other types implementing IDisposable), and it shouldn't be a problem. (Of course if you actually have that file open in a separate application, that's a different problem entirely.) So instead of: // Bad code StreamReader reader = File.OpenText("foo.txt"); string data = reader.ReadToEnd(); // Nothing is closing the reader here! It'll keep an open // file handle until it happens to be finalized You should use something more like: string data; using (TextReader reader = File.OpenText("foo.txt")) { data = reader.ReadToEnd(); } // Use data here - the handle will have been closed for you Or ideally, use the methods in File which do it all for you: string text = File.ReadAllText("foo.txt"); A: Check if you're closing stream to the file. If not then you're blocking yourself. A: Assuming that you have correctly closed the stream you used to open and read the file initially, to create, append or fail depending of file existence you should use the FileMode parameter in FileStream constructor. Everything depends on the way you open the FileStream, see here: FileStream Constructor (String, FileMode) if you specify FileMode Create: Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write. System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException is thrown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone Chart: How can we zoom in in Core Plot ? (example code: AAPLot) iPhone Chart: How can we zoom in in Core Plot ? (example code: AAPLot) I am now using Core Plot to draw a Chart by example Code AAPLot CPTGraphHostingView *graphHost; IBOutlet UIScrollView *_scrollview; IBOutlet UIView *zoom_view; APYahooDataPuller *datapuller; CPTXYGraph *graph; How to let the View zoom in and zoom out?
{ "language": "en", "url": "https://stackoverflow.com/questions/7633826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Server Progress in WCF RIA Services Can I send progress updates from the server to the client when using time consuming wcf ria services? A: Of course you can. It's not an out of the box solution anyway... All we know that every call that we make from Silverlight is async, so the client continue to respond regardless if there are pending requests. That said, you can either make use of HttpPollingDuplex and use that sort of callback to notify your client or you can simply poll the server ar regular interval to obtain the current status of the operation. Be aware that the server variable that holds the state should be ideally stored in ASP.NET Session and eventually accessed in a lock block cause you are writing it from a thread and reading it from another one Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7633828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any SDK available for Iphone so that we can show adds via push notification? In android we have Air push , using which we can send and show add via push notification. Is there any thing similar we have for iPhone. Thanks. A: Yes you can use same Urban Airship for Push Notification for iphone too... A: Advertising by use of push notifications are explicitly forbidden by Apple: according to section 2.2 of the APN terms and conditions: You may not use the APN or Local Notifications for the purposes of advertising, product promotion, or direct marketing of any kind (e.g. up-selling, cross-selling, etc.), including, but not limited to, sending any messages to promote the use of Your Application or advertise the availability of new features or versions. Technically you can do it by rolling your own push notification server or by signing up with one of the established APN providers, e.g. Urban Airship. But I doubt your App will be approved by Apple if you use it for sending ads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a partial class to a edmx and use it as a navigation property to a existing entity? I am going to create a model class of my own as a partial class. How to add this partial class as a navigation property to a existing entity. Help me on this... A: It doesn't matter if you created class yourselves or let some code generator to create it from EDMX file. Your hand made class still must have counter part in EDMX (the entity). Navigation properties are defined among entities in EDMX.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Turn on full backtrace in Ruby on Rails TestCase Only one line of backtrace is displayed when I run: rake test Output: ... ERROR should get search for keywords (1.93s) NoMethodError: undefined method `features' for #<Transcript:0x00000006243780> /usr/lib/ruby/gems/1.9.1/gems/activemodel-3.1.0/lib/active_model/attribute_methods.rb:385:in `method_missing' ... I need more lines of backtrack information. I have tried * *rake test --trace *Rails.backtrace_cleaner.remove_silencers! in config/initializers/backtrace_silencers.rb *setting global $DEBUG=true and it didn't work. How can I turn it on? A: Nowdays you can run: rails test --backtrace A: BACKTRACE=blegga rake test BACKTRACE=blegga rails test # rails 5+ Append --trace if you need rake related log. A: Finally figured this out. The issue is with the 'turn' gem included in Rails 3.1, or actually with turn v0.8.2, which is required by the default Gemfile: group :test do # Pretty printed test output gem 'turn', '0.8.2', require: false end Turn v0.8.2 doesn't include the full backtrace, so you have to upgrade to get it. I did that by changing the above in my Gemfile to this: group :test do # Pretty printed test output gem 'turn', require: false gem 'minitest' end (I had to add minitest because otherwise turn throws a RuntimeError saying "MiniTest v1.6.0 is out of date.") Then I ran bundle update turn and got the latest verion (0.9.2 as of this writing). That gives full backtraces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Can't Access TextBoxes in other pages of GridView I have an ASPxGridView with a column containg ASPxTextBox <dx:GridViewDataTextColumn Caption="Capacity" FieldName="Capacity" VisibleIndex="4" > <DataItemTemplate> <dxe:ASPxTextBox ID="txtCapacity" runat="server" Text='<%# Eval("Capacity") %>'> </dxe:ASPxTextBox> </DataItemTemplate> </dx:GridViewDataTextColumn> I added a button for saving the capacity. I use GetRowValues(index, field_name) to access other fields and FindRowCellTemplateControl(index, column, id) to be able to get txtCapacity's value. But the problem is, when paging is involved, I can't access the textboxes in other pages. Any ideas about this? Thanks EDIT v.1 Here is my code where I invoke FindRowCellTemplateControl() protected void btnSave_Click(object sender, EventArgs e) { List<Capacity> capacityList = new List<Capacity>(); for (int i = 0; gvCapacity.VisibleRowCount > i; i++) { Capacity c = new Capacity(); c.Id = (int)gvCapacity.GetRowValues(i, "Id"); ASPxTextBox txtCapacity = (ASPxTextBox)gvCapacity.FindRowCellTemplateControl(i, (GridViewDataColumn)gvCapacity.Columns["Capacity"], "txtCapacity"); c.Value = Convert.ToInt32(txtCapacity.Text); capacityList.Add(c); } //Save Capacity //... } A: The ASPxGridView creates template controls for an active page only. So, it is impossible to get a reference to the non-existing controls via the FindRowCellTemplateControl method. See the http://www.devexpress.com/issue=Q341997 discussion in the DX support center to learn more on how to solve this issue. A: Regardless my comment on your question, and if I got your question right then, you have an ASPxButton and you want when Click it to get all Capacities inside your ASPxGridView try this: protected void ASPxButton1_Click(object sender, EventArgs e) { //Loop throug all Pages for (int i = 0; i < ASPxGridView1.PageCount; i++) { //Select current page ASPxGridView1.PageIndex = i; //Loop through all rows inisde the page for (int J = 0; J < ASPxGridView1.SettingsPager.PageSize; J++) { //Get currnt TextBox DevExpress.Web.ASPxEditors.ASPxTextBox txtbox = ASPxGridView1.FindRowCellTemplateControl(J, (DevExpress.Web.ASPxGridView.GridViewDataColumn)ASPxGridView1.Columns["Capacitiy"], "txtCapacity") as DevExpress.Web.ASPxEditors.ASPxTextBox; //Do your logic here } } } I'm still encourage you to get your data through your underlying datasource
{ "language": "en", "url": "https://stackoverflow.com/questions/7633842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: making some items unselectable in dropdownlist using asp.net? Dropdownlist i binded the values but in that dropdownlist just like group means(employee,nonemployee) so that items value is empty(""), so i can use databound event split the two fileds ,that two fields i can apply the color and underline and bould and user doesnot select that fields , so pls see the below code and modify this code. protected void ddlconsultant_DataBound(object sender, EventArgs e) { foreach (ListItem item in ((DropDownList)sender).Items) { string r = item.Value; if (r == "") { item.Attributes.Add("style", "color:Red;font-weight:bolder"); } } thanks hemanth A: I'm handling this situation on the client side, using javascript, actually jQuery jQuery(document).ready(function () { $("[id*=ddlConsultant] option[value='']").each(function () { $(this).attr("disabled", "true"); $(this).css("color", "Red"); $(this).css("font-weight", "bolder"); }); }); A: It's probably easier to do this with server-side code, in the same place where you set the colour of list items: item.Attributes.Add("style", "color:Red;font-weight:bolder"); item.Attributes.Add("disabled", "disabled"); This will product HTML code that looks something like this: <option style="color:Red;font-weight:bolder" disabled="disabled">item text</option> I know this is kinda an old question, but I've just been looking for the same information, and having just found out, thought I'd add the answer here for completeness.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: imagemagick installation error - architecture mismatch I am trying to install ImageMagick via macports but am getting the following error msg: Error: Cannot install imagemagick for the arch(s) 'x86_64' because Error: its dependency bzip2 is only installed for the arch 'i386' Error: and the configured universal_archs 'i386 ppc' are not sufficient. Error: Unable to execute port: architecture mismatch To report a bug, see <http://guide.macports.org/#project.tickets> Any suggestion would be greatly appreciated :) A: This looks like the same question that was asked on Superuser, "Mac ports installation of gcc46 failing due to architecture problems", and on Apple.Stackexchange, "Mac ports installation of gcc46 failing due to architecture problems". Did you start building these MacPort binaries on MacOS 10.5, then upgrade to 10.6 -- or move to a new machine with 10.6 and copy the MacPorts files from the old machine -- and then build imagemagick under MacOS 10.6? Does your configuration file /opt/local/etc/macports/macports.conf differ from macports.conf.default? That's a sign that the MacPorts environment was migrated from 10.5 instead of being created new on 10.6. There should be a line there, reading universal_archs ppc i386 ppc64 x86_64. The official MacPorts migration instructions explain how to essentially update your environment for MacOS X 10.6 and do a complete rebuild. Their instructions: * *Reinstall Xcode and MacPorts *Update macports.conf *Save a list of installed ports *Uninstall all ports *Reinstall just those you still want The blog post Universal Binaries in Macports gives slightly different instructions. Basically it comes down to: * *update the universal_archs line in macports.conf *force a complete rebuild with $ sudo port upgrade --force installed -
{ "language": "en", "url": "https://stackoverflow.com/questions/7633845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MultiAutoCompleteTextView adds ", " I have a MultiAutoCompleteTextView. When i enter "Sal" it suggest "Salami" , but when i press it in the box stands "Salami, ". How could i prefent that? My Code: void addAutoSuggest () { myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null); ArrayList<String> list = new ArrayList<String>(); Cursor cursor = this.myDB.query(MY_DB_TABLE, new String[] {"name"},null,null,null,null,null,null); if (cursor.moveToFirst()) { do { String str= cursor.getString(0); list.add(str); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } if (list!=null) { name.setAdapter( new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list)); name.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); } } A: In MultiAutoCompleteTextView,it would always need separator so i think,you can't get rid of it. But you can use space as seperator instead of comma and then you can trim your final string for further use. You can find solution here - How to replace the comma with a space when I use the "MultiAutoCompleteTextView" Or if you want to continue using ',' as separator,then you would have to manually remove last comma from a final string you get in MultiAutoCompleteTextView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What data structure should I use for a simple synchronized LIFO? What data structure should I use for a simple synchronized LIFO? I'm using Android Java 1.6. The problem with Java collections is that there are millions of slightly different classes and interfaces. A: What about standard Stack? It is synchronized. UPDATE According to javadoc, you should use implementation of Deque instead of Stack. E.g. LinkedBlockingDeque A: Queues The java.util.concurrent ConcurrentLinkedQueue class supplies an efficient scalable thread-safe non-blocking FIFO queue. Five implementations in java.util.concurrent support the extended BlockingQueue interface, that defines blocking versions of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue, and DelayQueue. The different classes cover the most common usage contexts for producer-consumer, messaging, parallel tasking, and related concurrent designs. The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provides an implementation. Quoted from API Docs for Package java.util.concurrent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Objective-C : Auto Update Label text I am new to Objective-C and i need your help! In the code that you will see below, my labels pick data from a picker view. I would like instead of using a "calculate" IBAction, to have my "chargeLabel.text" updated in real time as soon as the user changes a value in the picker view. -(IBAction)calculate:(id)sender { float floatTime; if ([typeLabel.text isEqualToString:@"NiMH"]) { floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.5; } else { floatTime=([mAhLabel.text floatValue]/chargerSlider.value)*1.4; } int intHourhs=(floatTime); float floatHours=(intHourhs); float floatMinutes=(floatTime-floatHours)*60; NSString *stringTotal = [NSString stringWithFormat: @"Hours: %.0i Minutes: %.0f", intHourhs, floatMinutes]; chargeLabel.text=stringTotal; } A: You have to implement UIPickerViewDelegate Protocol. Then, perform whatever you want in didSelectRow method - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { ... //here your code } Check UIPickerViewDelegate Protocol Reference EDIT: I just realized that your accessing value property of chargerSlider if it is a UISlider you don't need to implement any delegate, just assing your IBAction to the Value Changed selector of the slider in IB. A: Set yourself up as the delegate of UIPickerView, and implement this method: pickerView:didSelectRow:inComponent When this method get called, simply call [self calculate:nil];
{ "language": "en", "url": "https://stackoverflow.com/questions/7633854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: event when adding element into document Adding new html string into the page: document.getElementById('container').innerHTML = '<div id="child"></div>'; Is there an event that let me know when child element is in the document? I have a function, which return some html codeas a string. And when this html will be added in the document, I need to execute javascript function. I've tried to use inline onload event document.getElementById('container').innerHTML = '<div id="child" onload="console.log(\'ready!\');"></div>'; but it does not seem to work. UPDATE: Probably, I should provide more details about the situation. I have a library function myLibrary.getHtml() In old version, users just call this function and append the result into the document: document.getElementById('container').innerHTML = myLibrary.getHtml(); In new version, the result is not a plain html. Now users can interact with it after they append it in the document. So after they append html into the document, I need to go through the result DOM and attach event handlers, hide some elements and other things. That is why, I need to know when they add it in the document and execute a javascript function, which turn plain html into fancy interactive widget. A: You could try using DOM Mutation Events, but they are still inconsistently implemented across browsers. A: If i have not misunderstood the question, you can probably get this to work document.getElementById('id').childNodes; A: If you can use jQuery, you could write your own custom event which would call the function you need to call whenever the new html has been added: $('#container').bind('changeHtml', function(e) { // Execute the function you need }); And of course instead of just adding the html to the element, you would need to wrap it up in a function which triggers your custom event. Then all you'd need to do is call this function instead of setting the innerHtml yourself. function addHtml(html) { $('#container').innerHTML = html; $('#container').trigger('changeHtml'); } A: Solved by myself this way: myLibrary.getHtml = function() { var html; ... var funcName = 'initWidget' + ((Math.random() * 100000) | 0); var self = this; window[funcName] = function() { self._initWidget(); }; return html + '<img src="fake-proto://img" onerror="' + funcName + '()"'; } The idea behind the code is that I specify incorrect url for the src attribute of the img tag and the image triggers error event and call my function. Quite simple :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7633856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .net statistics library for forecasting Is there a good .NET statistics library for forecasting? I need it to do the following: Decompose the input dataset with classical decomposition into Seasonal, Trend and Irregular. ARIMA modeling and forecasts. P.S. I had a look at R.NET. Thogh it will hopefully do the above, better solutions are welcome. A: Take a look at Math.Net http://www.mathdotnet.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7633862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: android mapview loading I am making an android app in which i am using mapviews. they are working perfectly on the device when installed from the pc.but when the same build is installed in device through android market, the maps does not load. following is the logcat output. 10-03 15:54:51.784: WARN/System.err(12994): java.io.IOException: Server returned: 3 10-03 15:54:51.784: WARN/System.err(12994): at android_maps_conflict_avoidance.com.google.googlenav.map.BaseTileRequest.readResponseData(BaseTileRequest.java:115) 10-03 15:54:51.784: WARN/System.err(12994): at android_maps_conflict_avoidance.com.google.googlenav.map.MapService$MapTileRequest.readResponseData(MapService.java:1473) 10-03 15:54:51.784: WARN/System.err(12994): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.processDataRequest(DataRequestDispatcher.java:1117) 10-03 15:54:51.784: WARN/System.err(12994): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher.serviceRequests(DataRequestDispatcher.java:994) 10-03 15:54:51.784: WARN/System.err(12994): at android_maps_conflict_avoidance.com.google.googlenav.datarequest.DataRequestDispatcher$DispatcherServer.run(DataRequestDispatcher.java:1702) 10-03 15:54:51.784: WARN/System.err(12994): at java.lang.Thread.run(Thread.java:1019) what could be the problem can anyone please help me over ths?? thanks A: You can't use debug.keystore to create a Google Maps API key for applications going into the market. If you already have the application (or indeed any application) in the market then you already have the keystore you should use. This is how you use this keystore to get a Google Maps API key: Step 1: At the command line navigate to the directory with your keystore file in it: cd <keystore-dir> Step 2: Now list the contents of your keystore: keytool -list -keystore <your-keystore-file> Step 3: Enter the password for your keystore when prompted. Keytool will now display a list of certificates and their MD5s. Step 4: Copy the MD5 for the certificate you are going to use to sign your application into your copy/paste buffer. Step 5: Open a browser and navigate to http://code.google.com/android/maps-api-signup.html - if you're not logged in with your Android Market account, you'll need to do that next, before you generate your API key. Step 6: Paste the MD5 from your copy/paste buffer into the text box labelled "My certificate's MD5 fingerprint:" and tick the "I have read and agreed..." box. Step 7: Click 'Generate API Key'. You'll now see the API key you need to use. Step 8: Copy and paste the API key into your MapView component's android:apiKey property. If you have multiple MapView components then you can declare a string resource: <string name="production_api_key">thisIsMyKeyValue</string> Now you can use this in your android:apiKey property in the same way that you reference any other string value: android:apiKey="@string/production_api_key" Now export the application to an APK file using the certificate you used in step 4. Provided you follow this step-by-step guide you should be OK - I've just myself started using a maps API key generated in this way. Things to watch out for: * *Using the MD5 of the keystore file (md5 <my-keystore-file>), not of the certificate. Its the MD5 of the certificate you need. *Being logged in to Google when you generate the API key, but with the wrong account. Your maps API key and your Android Market signing key must belong to the same Google account.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: asp CompareValidator on 2 dropdowns Scenario: I have the following controls: <telerik:RadComboBox ID="dd1" runat="server" ValidationGroup="g1" InitialValue="-1" /> <telerik:RadComboBox ID="dd2" runat="server" ValidationGroup="g1" InitialValue="-1" /> <asp:CompareValidator ID="cv" runat="server" ValidationGroup="g1" InitialValue="-1" ControlToValidate="dd1" ControlToCompare="dd2" Operator="NotEqual" Text="error" Type="String" /> I don't want the 2 dropDowns to have the same values, excluding "-1" which is the default value of any dropdown. Can I achieve this using the compareValidator? or should i use javascript? thanks in advance A: A single CompareValidator by itself will not do what you need, but you can just add another CompareValidator to your setup there. A typical ASP.NET DropDownList doesn't have a default value if empty. It's based on the first item in the list. I'm not sure if the telerik controls you are using have a default value of -1, but if they do, then you could add one or two CompareValidators for each dropdown and set the ValueToCompare attribute, and check for NotEqual: <asp:CompareValidator ID="cv3" runat="server" ValidationGroup="g1" ControlToValidate="lst1" ValueToCompare="-1" Operator="NotEqual" Text="Empty value is not allowed" Type="String" /> A: For comparision, compare validator is correct. But for initial value (-1), you need to add required field validators for both dropdowns. So user must select value. <telerik:RadComboBox ID="dd1" runat="server" ValidationGroup="g1" InitialValue="-1" /> <asp:RequiredFieldValidator ID="reqv1" runat="server" ErrorMessage="Please select value" ControlToValidate="dd1" ValidationGroup="g1" InitialValue="-1"></asp:RequiredFieldValidator> <telerik:RadComboBox ID="dd2" runat="server" ValidationGroup="g1" InitialValue="-1" /> <asp:RequiredFieldValidator ID="reqv2" runat="server" ErrorMessage="Please select value" ControlToValidate="dd2" ValidationGroup="g1" InitialValue="-1"></asp:RequiredFieldValidator> <asp:CompareValidator ID="cv" runat="server" ValidationGroup="g1" InitialValue="-1" ControlToValidate="dd1" ControlToCompare="dd2" Operator="NotEqual" Text="error" Type="String" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7633880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Add an NSMutableIndexSet to Another? I have an NSMutableIndexSet and I want to add indexes in it to another NSMutableIndexSet in my loop. I've been looking for right functions but unable to find anything. How can I do that? A: Have you tried this: [someIndexSet addIndexes:otherIndexSet]
{ "language": "en", "url": "https://stackoverflow.com/questions/7633882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: need to write compare point method in my class called point . ruby hi i have wrttien this points class in ruby but i need a compare method class to anybody any ideas where to start? class Point attr_reader :x, :y def initialize x,y @x = x @y = y end def addpoint(x,y) # used to add points Point.new(@x+x, @y+y) end def to_s x.to_s+" , "+y.to_s # used to change from object to strings end end A: class Point def == p return false unless p.kind_of? Point x == p.x and y == p.y end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7633889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Rails devise reset password not working I am using devise in a rails 3 application. I have devise fully working however the 'forgot password' function has decided to stop working. When I enter an email address and click the 'send me reset instructions' button I am redirected to the login page which displays a flash notice saying please login first. I have also found out that 'send me reset instructions' is trying to access http://0.0.0.0:3000/users/password. I previously had this working and now its decided to stop working. I do not think it has anything to do with any form of authorization like ACL9. Has anyone experienced the same similar problem. Are there any possible solutions to fixing this. Devise/Password_controller.rb class Devise::PasswordsController < ApplicationController prepend_before_filter :require_no_authentication include Devise::Controllers::InternalHelpers access_control do allow all end # GET /resource/password/new def new build_resource({}) render_with_scope :new end # POST /resource/password def create self.resource = resource_class.send_reset_password_instructions(params[resource_name]) if successful_and_sane?(resource) set_flash_message(:notice, :send_instructions) if is_navigational_format? respond_with({}, :location => after_sending_reset_password_instructions_path_for(resource_name)) else respond_with_navigational(resource){ render_with_scope :new } end rescue => e; puts e.backtrace; raise e; end # GET /resource/password/edit?reset_password_token=abcdef def edit self.resource = resource_class.new resource.reset_password_token = params[:reset_password_token] render_with_scope :edit end # PUT /resource/password def update self.resource = resource_class.reset_password_by_token(params[resource_name]) if resource.errors.empty? flash_message = resource.active_for_authentication? ? :updated : :updated_not_active set_flash_message(:notice, flash_message) if is_navigational_format? sign_in(resource_name, resource) respond_with resource, :location => redirect_location(resource_name, resource) else respond_with_navigational(resource){ render_with_scope :edit } end end protected # The path used after sending reset password instructions def after_sending_reset_password_instructions_path_for(resource_name) new_session_path(resource_name) end end ProjectRails::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = true # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true #SMTP #SMTP config.action_mailer.default_url_options = { :host => "0.0.0.0:3000" } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address => "smtp.example.example.ltd.uk", :user_name => "[email protected]", :password => "1Plonker", :authentication => "login" } end config/intializers/devise config.mailer_sender = "[email protected]" A: Run rake routes to check that it is routing to the correct location. Also check your view/password/new.html.erb and check that the URL is routing to your login path instead of :url => password_path(resource_name) as this is a common problem. This should solve your problem. Also change your :location => after_sending_reset_password_instructions_path_for(resource_name)) to :location => (whatever the login path is) :-) A: You're running this is a development environment, right? Have you checked the following is correct: # config/environments/development.rb config.action_mailer.raise_delivery_errors = true config.action_mailer.perform_deliveries = true config.action_mailer.default_url_options = { :host => 'mydomain.com' } # config/initializers/devise.rb config.mailer_sender = "[email protected]"
{ "language": "en", "url": "https://stackoverflow.com/questions/7633891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android - Radio button selections are not being registered I am trying to use radio buttons but they aren't working. I've got the toast in there at the moment purely for debugging, and it never appears. There seems to be various ways to use them so perhaps I'm just using a poor method. Any advice on what I've done wrong would be amazing. final RadioButton rbSDR = (RadioButton) findViewById(R.id.rbSDR); final RadioButton rbMM = (RadioButton) findViewById(R.id.rbMM); RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup); //int checkedRadioButtonID = radGrp.getCheckedRadioButtonId(); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup arg0, int id) { Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_SHORT).show(); switch (id) { case -1: rbMM.setChecked(false); rbSDR.setChecked(false); break; case R.id.rbSDR: rbMM.setChecked(false); break; case R.id.rbMM: rbSDR.setChecked(false); break; default: break; } }); EDIT: Apparently the issue was that I had a linear layout WITHIN the radio button group. Now to figure out how to put the buttons side by side... A: the id will always return -1 only. Try the following edited code, final RadioButton rbSDR = (RadioButton) findViewById(R.id.rbSDR); rbSDR.setId(R.id.rbSDR); final RadioButton rbMM = (RadioButton) findViewById(R.id.rbMM); rbMM.setId(R.id.rbMM); RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup); //int checkedRadioButtonID = radGrp.getCheckedRadioButtonId(); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup arg0, int id) { Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_SHORT).show(); switch (id) { case -1: rbMM.setChecked(false); rbSDR.setChecked(false); break; case R.id.rbSDR: rbMM.setChecked(false); break; case R.id.rbMM: rbSDR.setChecked(false); break; default: break; } }); A: set the listener to radio buttons instead of radio group A: Instead of using radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { Use radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){ A: To put the radio buttons side-by-side, add this to the XML properties: android:orientation="horizontal"
{ "language": "en", "url": "https://stackoverflow.com/questions/7633893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting inline ASM to Intrinsic I've been give a task to convert small piece of asm into intrinsic in order to test performance. I ve never developed any code for either one, but I understand asm and c, and reading up on intrinsic syntax. But I cant find info on how intrinsic is dealing with accessing registers. i found 2 functions: getReg() and setReg() getReg() comes with a table of different register tables and their id/number: -General Integer Registers -Application Registers -Control Registers -Indirect Registers But none of them seems to correspond to asm registers like rax,rdi and so on. How can I address registers eg rcx, rdi and so on in intrinsic? Or in other words how can I convert this: mov %0, %rcx to intrinsic equivalent? A: You're missing the point of intrinsics - you don't need to worry about register allocation when using intrinsics (except perhaps in the case of access to special registers in some cases). The general idea is to let the compiler take care of all this kind of low level house-keeping for you. To port raw asm to intrinsics you need to firstly reverse-engineer the asm code, so that you understand what it is meant to do, then re-implement the equivalent code using intrinsics. If you post some of the actual code then you may get more specific suggestions. A: See if you can use any of these: GCC: X86 Built-in Functions MSVC++: Alphabetical Listing of Intrinsic Functions
{ "language": "en", "url": "https://stackoverflow.com/questions/7633899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Serializing Font Object from C# and Deserializing on Java Using @Elad solution at this answer I could serialize and de-serialize a Font using C# but I need to de-serialize it in Java. Is there a way to achieve it? If someone has any good article on doing this for any other object it could be helpful. A: In Elad's answer, the System.Drawing.Font is converted to XML, and then to a pure binary form. On the Java, side, it's pretty trivial to deserialize from binary to XML, but from there, you will have to know what you plan on doing with the XML. Do you have a java class you are wanting/needing to use? A: You can try Protocol Buffers. Its serialized form is language neutral and you can use it on serialize on C# and deserialize on java side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to obtain CN of the certificates in particular store? i want to obtain the CN of the certificates stored in the MY store as i want to verify if the certificate exists or not in that store. I don't know the which method should be used to perform this task. I tried using below code but it doesn't works X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindBySubjectName,"Root_Certificate",false); if(cers.Count>0) { //certificate present } else { //certificate not present } Does the subjectName gives CN? is there any other method? Please suggest me how to check whether a particular certificate is present or not and i want to do it using CN. A: You could use the store.Certificates.Find(X509FindType.FindBySubjectName, "SubjectName", false) function to search for a certificate by its subject name. Do NOT include "CN=" in the subject name. To search more specific you could use the thumbprint to search for your certificate. The following code sample demonstrates this: X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.IncludeArchived); foreach (var c in store.Certificates) { Console.Out.WriteLine(c.Thumbprint); Console.Out.WriteLine(c.Subject); } // Find by thumbprint X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, "669502F7273C447A62550D41CD856665FBF23E48", false); store.Close(); I've added a foreach loop to the code sample to iterate over all certificates in the selected store. Your certificate must be listed there. If not, you probably use the wrong store. Note, there is a My store for the Machine and the Current User. So, be sure to open the right store. To get the thumbprint of your certificate follow these steps: * *Open certmgr.msc. *Double click on your certificate. *Go to the details tab. *Under thumbprint you will find the thumbprint of your certificate. Hope, this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Sending HTTPPost in Android I am new to android development. What I am trying to do is send some data on a server. i.e. the HTTPPOst. For example I want to send an image or send an XML in the HTTP Post's Body.... Can some body give me sample code or project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows service installer not reading App.Config file I have added App.Config in my project. I have a installer class(ProjectInstaller.cs) which needs to read values from App.config. I am providing the keys . Below is the sample Code : ConfigurationManager.AppSettings["CONFIG_FILE"] I am getting null values as per above code ,when invoked in Installer class. But in App.Config file the value for the above key exists. A: Google helps: http://social.msdn.microsoft.com/Forums/ar/winformssetup/thread/896e110e-692d-4934-b120-ecc99b01c562 the point is that your installer is NOT running as exe alone and an app.config called whatever you imagine will not be loaded by default as the exe running your installer is InstallUtil.exe and it would eventually search appSettings from the file InstallUtil.exe.config which is not yours and is not what you want, read the following and check the links... If you invoke it through InstallUtil then the configuration file is defined as InstallUtil.exe.config which is not what you want. You could manually load the config file using Configuration but it will probably be a little messy The trick is in the execution context of the installer classes. If you install your app using InstallUtil all code will be executed in the same process as InstallUtil.exe. If you need to pass some data to the Installer class during deployment you should use install parameters. They are passed to the installer during execution of Install, Commit, Rollback and Uninstall methods by the execution enviroment (installutil, windows instller...). You can access there parameters using InstallContex property ot the installer class. There is a excellent artiicle on CodeProject regarding Setup projects and parameters: http://www.codeproject.com/dotnet/SetupAndDeployment.asp Check out http://msdn2.microsoft.com/en-us/library/system.configuration.install.installcontext.aspx A: Try: public string GetServiceNameAppConfig(string serviceName) { var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetAssembly(typeof(MyServiceInstaller)).Location); return config.AppSettings.Settings[serviceName].Value; } A: For me the easiest solution was to create InstallUtil.exe.config file, and fill it up with content from application config file. Service installer successfully read from this config file. I created my service by following steps described in: Host a WCF Service in a Managed Windows Service A: Davide Piras explained very well, why you can't use your app.config and suggests to pass your values as parameters. I found a nice and helpful article on how to pass parameters to the installutil.exe and use them in the serviceInstaller or projectInstaller: Part 1: Using Parameters with InstallUtil Part 2: Configuring Windows Services with Parameters from InstallUtil It explains very shortly how to pass arguments and how to read them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Rails timezones VS MySQL timezones In my Rails (3.0) application, I use timezones using the helper time_zone_select(). It generates timezone names like "(GMT+01:00) Paris"... But these names are different from those in MySQL, where the same timezone would be "Europe/Paris". How can I convert Rails timezones to MySql ones ? The tricky part is that for several reasons I have to use the default Rails helper, and in my models I have to use the MySQL timezones. So I can't use Ruby timezones in my models, and I can't use a list of MySQL timezones instead of the Rails helper... I really need a way to convert from the first to the latter. Any idea? Edit: I'm currently trying to use ActiveSupport::TimeZone[(ruby_timezone)].tzinfo.name, is there a better way? A: Okay, I finally found a way : ActiveSupport::TimeZone[ruby_timezone].tzinfo.name Romain suggested there may be some Rails timezones not supported by MySQL, so I tested the following in the console, and the answer is: they all work :) ActiveSupport::TimeZone.all.each do |ruby_timezone| mysql_timezone = ActiveSupport::TimeZone[ruby_timezone.name].tzinfo.name puts ActiveRecord::Base.connection.execute("select convert_tz('2011-01-01 00:00:00', 'UTC', '#{mysql_timezone}')").first end end If a timezone was not supported by MySQL, it would have returned nil. I don't know if there is a better way, but at least it works :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7633922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Automatic height setting for input tag I'm having a dynamic input box, heigth of which need to be increaed based on the data adding. I tried to put new line after 10 characters in javascript but its not reflecting in input tag. My code is for(var i=0; i < field.length; i++) cityNameLength = cityNames.length; tempLength = cityNameLength; if(tempLength > 12) { tempLength = 0; cityNames+='\r\n'; } } document.getElementById('val').value =cityNames ; // it is displaying everything in one line and <input type="text" id="val"/> A: For Multi Line you should use textarea tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MYSQL: How to use outer aliases in subquery properly? The first query works just fine. It returns one row from the table 'routepoint'. It has a certain 'route_id' and 'geo_distance()' is on its minimum given the parameters. I know that the subquery in the FROM section seems unnecessarily complicated but in my eyes it helps to highlight the problem with the second query. The differences are in the last two rows. SELECT rp.* FROM routepoint rp, route r, (SELECT * FROM ride_offer WHERE id = 6) as ro WHERE rp.route_id = r.id AND r.id = ro.current_route_id AND geo_distance(rp.lat,rp.lng,52372070,9735690) = (SELECT MIN(geo_distance(lat,lng,52372070,9735690)) FROM routepoint rp1, ride_offer ro1 WHERE rp1.route_id = ro1.current_route_id AND ro1.id = 6); The next query does not work at all. It completely freezes mysql and I have to restart. What am I doing wrong? The first subquery returns excactly one row. I don't understand the difference. SELECT rp.* FROM routepoint rp, route r, (SELECT * FROM ride_offer WHERE id = 6) as ro WHERE rp.route_id = r.id AND r.id = ro.current_route_id AND geo_distance(rp.lat,rp.lng,52372070,9735690) = (SELECT MIN(geo_distance(lat,lng,52372070,9735690)) FROM routepoint rp1 WHERE rp1.route_id = ro.current_route_id); A: The problem is, as pointed out by Romain, that this is costly. This article describes an algorithm that reduces the cost by a 2-step process. Step 1: Find a bounding box that contains at least one point. Step 2: Find the closest point by examining all points in the bounding box, which should be a comparatively small number, thus not so costly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to merge resource files from other assemblies in Silverlight / wp7 In my app i need to merge the resource file from an external assembly. Is it possible to do so? If the answer is yes please guide me to resolve this issue . A: Try this: <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/StyleResource.Styless;component/ButtonStyle.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
{ "language": "en", "url": "https://stackoverflow.com/questions/7633932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get result in javascript from a WCF method returns int? I have one method in my wcf Service class that returns int and I am calling this method through javascript as below: //Interface for Service [ServiceContract(Namespace = "TestService")] public interface ITestService { [OperationContract] int GetTest(int A,int B); } [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class TestService : ITestService { public int GetTest(a,b) { return a + b; } } Calling the service in javascript goes like this: TestService.ITestService.GetTest(a,b,returnId); //method to get result id in javascript function returnId(result) { alert('Result :' + result); } Now here in alert everytime I am getting this result as null, why? Even I changed that int to List<int> and tried but getting the result as null. and this is working fine on FireFox and other browser but not working on IE. Even use fiddler to find issue and in fiddler it is giving Content-Length mismatch error. but getting the Service method value in fiddler. Can anyone please help me why the result is null everytime with IE?
{ "language": "en", "url": "https://stackoverflow.com/questions/7633936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use Google Charts for dynamic Data from database I am planning to use Google charts to display the data available on my server by an ajax request from the client side. But I am not able to figure out how to set the callback method for the Google API as the callback method will be having some parameters to populate the chart. The method needs to have the parameters as I was thinking to write the method to be generic to be used elsewhere as well. A: Since it has been long since the question is left unanswered, hence replying to my own question. I found the way to handle this. The trick was pretty simple. Even if you want to pass some parameter in the call back method for Google Charts, pass the name of the method as usual. But in the method itself if the param is set or not. Thing to take care is that Google sends you the event available for the charts, hence you could search for the set params as per your bussiness logic. Hence if set, no issue and if not set it to blank or some default value. Hope it helps!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7633937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The connection to the server was unsuccessful.(file:///android_asset/www/index.html) I am developing a android app using phonegap, it calls a website (http://siteaddress.com:8081) to get json encoded data. This is working fine on the emulator, then I built the android package .apk file using phonegap build but when i installed this package on my android phone and started the app, it force closes the application showing the error "The connection to the server was unsuccessful.(file:///android_asset/www/index.html)". I have built the app using phonegap build, passed it the index.html as well as tried the .zip file package but still getting this error. I tried searching for this error and also included the below code in my app as suggested on some sites but still it is giving error. super.setBooleanProperty("loadInWebView", true); super.setIntegerProperty("loadUrlTimeoutValue", 60000); Has this got something to do with the website that i am trying to call from my app? I tried opening that site in the mobile browser but it didn't opened but the website works fine on a desktop browser. Is there something wrong that i am doing? A: I'm guessing its the port number your using. Have you tried using port 80 for your server rather than 8081? Its possible that port isn't open on your device. A: The following code snippet solved my problem @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.loadUrl("file:///android_asset/www/home/index.html"); super.setIntegerProperty("loadUrlTimeoutValue", 10000); I have added super.setIntegerProperty("loadUrlTimeoutValue", 10000); to the com.mypackage.xxx.java file for 10 sec waiting time A: *I had Same problem solved by referring * this link... This error occurs bcoz of Server connection timeout so, Has mentioned in above post u can give 10 sec delay in that time put some splash screen..
{ "language": "en", "url": "https://stackoverflow.com/questions/7633940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Jquery check boxes to populate list I am attempting to populate a list of links depeding on what checkbox options are checked by a user. You can see what I have done so far here to give you an idea of what I am doing http://dev.perfectdaycanada.com/filter - the problem I am having is that I cant seem to get the checkboxes to populate links if only a county or a farm is selected. So at the moment one of the first set of checkboxes must be selected for the subsequent ones to work. Ideally any checkboxes ckecked should populate the list of links. Any help would be much appretiated. Thanks A: In your code just add this link at the top of your code $(document).ready(function(){ $('body').find(':input.type_check:first').attr({'checked':'checked'}); .... });
{ "language": "en", "url": "https://stackoverflow.com/questions/7633942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to retrieve items from server after fixed time period? I am returning 7 URL's that I retrieve from a Text document on a remote server. The URL's are links to images that I want to then download and put into a cache. These URL's will change every week. I want to retrieve these URL's from the text document only once on a fixed day of week (e.g. Monday only). How I can do that? A: 1: Make a service that connect server and get URL's then write URL to a file for use in you application. 2: Then Use alarm manger to create a alarm for a specif day. You can find details here. how do I set an alarm manager to fire after specific days of week While creating alarm you have to add your service with your alarm object so that when alarm time come. Then it run the service.(But be careful In that time there may be no internet.) you can add your service to alarm object e.g /* Scheduling Alarm for URL's update service to run at One */ Log.i(TAG, "Alarm started"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 10); Intent versionUpdateService = new Intent(getApplicationContext(), MyURLUpdaterService.class); PendingIntent recurringUpdate = PendingIntent.getService(getApplicationContext(), 0, versionUpdateService, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringUpdate); Log.i(TAG, "Alarm ended");
{ "language": "en", "url": "https://stackoverflow.com/questions/7633944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there no use in defining auto increment column as primary key In php myadmin it says it is no use in defining auto increment column as primary key for table. you can remove primary key constrain. (since both do the same job like). Is this true. should I remove primary key constrain? won't it good to have a primary key column for where clause rather than auto increment column A: You can create a column that is auto_incrementing without it being the primary key: This statement is legal: mysql> create table silly_but_possible ( id int auto_increment not null, xx varchar(9), key(id), primary key (xx)); Query OK, 0 rows affected (0.15 sec) So if you want your auto_incrementing column to be the PK, you'd better define it as such. Note that a table (at present) can only have one auto_incrementing column. What happens if you don't define a PK? If you don't MySQL will define a hidden auto_incrementing PK for you. However if you already have a auto_increment column, that column will always have an index, and because there can only be one auto_incrementing column, MySQL (at present!) has no other choice than to promote that row to the primary key. A: Keep The PK constraint. It will save you from some trouble: * *if you intend to use some frameworks which check for this constraint to determine which columns are used as PK. They will be lost or require additional configuration if the constraint is not present. *When you'll use DB design software it will work better if your DB is properly designed. *When you'll have to change your DB software (upgrade or change brands) You will be happy to have all the constraints properly defined in your SQL statements. A: when u define a column as a auto_increment it must be key(primary , unique ,index). take an example mysql> create table test -> (id int(5) auto_increment, -> name char(10) -> ); ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key so when we define a column as auto_increment it should be key.So it is better to define the column as PK. The primary index is used by the database manager for efficient access to table rows, and allows the database manager to enforce the uniqueness of the primary key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make dots between numbers in php I would like to make dots between my total value. If i have 425000 i would like it to show as 425.000 Is there a function in php that implodes dots for numbers or how can i do this then? A: Use number_format for this: $number = 425000; echo number_format( $number, 0, '', '.' ); The above example means: format the number, using 0 decimal places, an empty string as the decimal point (as we're not using decimal places anyway), and use . as the thousands separator. Unless of course I misunderstood your intent, and you want to format the number as a number with 3 decimal places: $number = 425000; echo number_format( $number, 3, '.', '' ); The above example means: format the number, using 3 decimal places, . as the decimal point (default), and an empty string as the thousands separator (defaults to ,). If the default thousands separator is good enough for you, you can just use 1: $number = 425000; echo number_format( $number, 3 ); 1) Mind you: number_format accepts either 1, 2 or 4 parameters, not 3. A: I guess you're looking for the number_format function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it preferred to make a function declaration after the function call in as3? In all the examples I've been going through online for as3, it seems as though the function declaration is always after the function call. Is this preferred to declaring the function before you call it? Ex: myButton.addEventListener(MouseEvent.CLICK, eventListenerFunc); function eventListenerFunc (eventargument:Object):void{ trace ("My button was clicked"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change the css class associated with a column based on value of column with javascript I have a grid and for one of the columns i want to dynamically change the css used based on the value of another field in the resultset. So instead of something like <td class='class1'> ${firstname} </td> pseudo-wise I would like {{if anotherColumnIsTrue }} <td class='class1'> ${firstname} </td> {{/if}} {{if !anotherColumnIsTrue }} <td class='class2'> ${firstname} </td> {{/if}} Is this thing possible..? A: I think that jQuery makes this a lot easier. It is very possible. I assume that you would want this for each row. Lets assume you have the following table: <table id="coolTable"> <tr> <td class="anotherColumn">True</td> <td class="firstName">Chris</td> </tr> <tr> <td class="anotherColumn">False</td> <td class="firstName">Roger</td> </tr> </table> You could go through rows and selectively add classes using the following code: $(function(){ $("#coolTable tr").each(function(i,row){ if($(row).children("td.anotherColumn").html()=="True") // Any condition here { $(row).children("td.firstName").addClass("class1"); }else{ $(row).children("td.firstName").addClass("class2"); } }); }); Have a look at this fiddle: http://jsfiddle.net/mrfunnel/LXq3w/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7633955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to give userchoice file name in browserdialog box Hi in my windows form application i want to save some data in a folder and when user selcts the browse button it should browse to reqired folder and should consist of a textbox to enter the filename of user choice. How can i achieve this . The below code is not working for me private void OutputFolder_button_Click(object sender, EventArgs e) { FolderBrowserDialog fd = new FolderBrowserDialog(); try { if (fd.ShowDialog() == DialogResult.OK) { if (string.IsNullOrEmpty(OutputFolder.Text)) { MessageBox.Show(" Please provide output file to do backup "); return; } outputFileName = fd.SelectedPath + "\\" + outputFileName; File.Create(outputFileName).Dispose(); OutputFolder.Text = outputFileName; //File.Create(outputFileName); DisplayMainWindow("Selected path to backup" + outputFileName); Logger.Log("Selected path to backup" + outputFileName); } } catch (Exception ex) { MessageBox.Show("Exception" + ex); } A: Sounds like you need the SaveFileDialog class. A: You need a SaveFileDialog. The example in the MSDN page should be enough to get you started.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to use Flash code completion? At this years Flash on the beach i saw a speaker using small 'code-keywords' that would complete entire sets of AS-code, depending on the keyword. Ex.: He would write @forloop, hit enter/space and a typical for-loop would be written automatically. Unfortunately he never said how to access this functionality in Flash. Can anyone tell me what this is called and how to set it up in Flash Professional? A: Flash Professional is about the worst ActionScript editor you will find. What you speak of, are snippets, and it's supported by any decent editor in one form or another. My personal favourite is FlashDevelop, where snippets are triggered using Ctrl+B by default. You might also consider FDT or a number of other editors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - XML conversion I'm new to stackoverflow and after some searching didn't find an answer to my question so I'm hoping someone can help me out. I have to use this web service method that takes three parameters, a string and two xml params. Below's an example of the code I'm using. The web service method throws an exception, 'Required parameters for method SubmitXml are null.' So I'm guessing it's not receiving any xml on the 2nd and 3rd params. Can anyone give me a hint on how to correctly use the DOM or any other with PHP here? thank you in advance. $soapClient = new SoapClient($this-SOAPURL, array('login'=>$this->account,'password'=>$this->password)); $xmlstr ='<xmlbody>'; $xmlstr.='<someXML>Some XML text content here!</someXML>'; $xmlstr.='</xmlbody>'; $dom = new DOMDocument(); $dom->loadXML($xmlstr); $filter = new DOMDocument(); $filter->loadXML('<_ xmlns=""/>'); print_r ($soapClient->SubmitXml('userIDString',$dom->saveXML(), $fil->saveXML())); A: After some struggling I finally got it. It didn't end up being a syntax error or anything. The code I presented in my question was OK except that I wasn't wrapping my XML string in a required node... something like: $xmlstring = "<somenode>" . $xmlstring . "</somenode>"; and then send it to the function. Thank you all for helping in trying to solve this 'mistery' ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7633965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTTP Last Updated I want to write something in .NET that will be given a URI and return the date/time when it was last updated. Is there something easy I can check? I assume there is a last updated property I can hook into? Is this reliable? How does it work with timezones? Thanks A: There is an HTTP-Last-Modified header, which should suit your purposes. A properly configured server should return this in UTC. Something like this might do: using (WebClient client = new WebClient()) { client.OpenRead("http://www.stackoverflow.com"); string lastModified = client.ResponseHeaders["Last-Modified"]; DateTime dateLastModified = DateTime.Parse(lastModified); Console.WriteLine(string.Format("Last updated on {0:dd-MMM-yyyy HH:mm}", dateLastModified)); } which (right now) returns Last updated on 03-Oct-2011 12:03
{ "language": "en", "url": "https://stackoverflow.com/questions/7633977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Many setTimeouts for scrolling events I want to show a tooltip when mousewheel scroll even is triggered. Here is the current code: if (window.hideTimeout) { clearTimeout(window.hideTimeout); } handle.qtip('show'); window.hideTimeout = setTimeout(function() { handle.qtip('hide'); }, 1000); This works correctly, however it runs slowly in Firefox when scrolling quickly, presumably because of the many setTimeouts being used. I was wondering if there is a better solution to this? I want the tooltip to hide if there have been no scroll events for a second, essentially. THanks A: I think the bottleneck is in the handle.qtip call, so use if (window.hideTimeout) { clearTimeout(window.hideTimeout); //qtip is already shown. } else { handle.qtip('show'); } window.hideTimeout = setTimeout(function() { handle.qtip('hide'); window.hideTimeout=false}, 1000); You could also not create a new anonymous function every time for the setTimeout. Just create it once and use it over and over again. //define once var tipHide = function(){handle.qtip('hide'); window.hideTimeout=false} ... //use many times window.hideTimeout = setTimeout(tipHide, 1e3); A: Try this out: window.hideTimeout = function(){ clearTimeout(window.hideTimeout); return setTimeout(function(){ handle.qtip('hide'); },1000); } This essentially clears your tiemout before registering a new one.. A: If all else fails, take a look at the debounce function from underscore.js.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding event clicks to POIs in Android Augmented Reality framework? I'm developing an application based on Android AR framework : http://code.google.com/p/android-augment-reality-framework Can anyone please suggest how to add click to the POIs or icons in camera view to view address of the POIs? A: When a marker is clicked, the markerTouched(Marker marker) method is called in the Demo class. On 4 October was integrated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to insert dot instead of comma in js keypress In my website i have textbox that contains currency amount separeted by dot. Users sometimes press dot on numpad, and that inserts coma in textbox. How can I convert it to dot ? I was trying to do it in keypress event but didn't menage to make it work. A: <input type='text' onkeypress='return check(this,event);'> function check(Sender,e){ var key = e.which ? e.which : e.keyCode; if(key == 44){ Sender.value += '.'; return false; } } UPDATE: This should work if you type anywhere in the input box function check(Sender,e){ var key = e.which ? e.which : event.keyCode; if(key == 44){ if (document.selection) { //IE var range = document.selection.createRange(); range.text = '.'; } else if (Sender.selectionStart || Sender.selectionStart == '0') { var start = Sender.selectionStart; var end = Sender.selectionEnd; Sender.value = Sender.value.substring(0, start) + '.' + Sender.value.substring(end, Sender.value.length); Sender.selectionStart = start+1; Sender.selectionEnd = start+1; } else { Sender.value += '.'; } return false; } } A: If you're looking to transform a comma character as it is typed, I've answered similar questions on Stack Overflow before: * *Can I conditionally change the character entered into an input on keypress? *show different keyboard character from the typed one in google chrome However, I agree with @ChrisF's comment above. A: You could do: $('input').keyup(function(e){ var code = e.which ? e.which : e.keyCode; console.log(code); if (code === 110){ var input = this.value; input = input.substr(0, input.length -1); console.log(input); input += ','; this.value = input; } }); fiddle http://jsfiddle.net/PzgLA/
{ "language": "en", "url": "https://stackoverflow.com/questions/7633981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display an UIAlert when a UIImageView is touch I have an ImageView and I want that when user press the image view to display a message as an alert. What method should I use? Can you provide me an example ? Thanks in advance.. A: Add a UITapGestureRecognizer: imageView.userInteractionEnabled = YES; UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [imageView addGestureRecognizer:tapRecognizer]; [tapRecognizer release]; And then your callback... - (void)handleTap:(UITapGestureRecognizer *)tapGestureRecognizer { //show your alert... } A: Use Touch Events method to do ur task -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; CGPoint location= [touch locationInView:self.view]; if(CGRectContainsPoint(urImageView.frame, location)) { //AlertView COde } } A: If you don't intent to subclass UIImageView to override touch event methods -- or implement the touch methods in the ViewController and check the frame the touch lies in the imageview frame -- you can (and that's probably easier) add an UITapGestureRecognizer to your UIImageView. See here in the documentation for more details UITapGestureRecognizer* tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnImage:)]; [yourImageView addGestureRecognizer:tapGR]; [tagGR release]; Then implement the -(void)tapOnImage:(UIGestureRecognizer*)tapGR method as you wish A: UITapGestureRecognizer *singleTapOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)]; singleTapOne.numberOfTouchesRequired = 1; singleTapOne.numberOfTapsRequired = 1; singleTapOne.delegate = self; [self.view addGestureRecognizer:singleTapOne]; [singleTapOne release]; - (void)handleSingleTap:(UITapGestureRecognizer *)recognizer A: First of all, Enable property yourImgView.setUserInteractionEnabled = TRUE; Then apply the below code on viewDidLoad; UITapGestureRecognizer *tapOnImg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapOnImgView:)]; tapOnImg.numberOfTapsRequired = 1; tapOnImg.delegate = self; [yourImgView addGestureRecognizer:tapOnImg]; A: Use touch delegate method and find your image view there, A: Instead of using a UITapGestureRecognizer if the class where you have your imageview overrides UIResponder you could just override touchesBegan: - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if ([touch view] == YOUR_IMAGE_VIEW) { // User clicked on the image, display the dialog. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Image Clicked" message:@"You clicked an image." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } } You must be sure that userInteractionEnabled is YES for your image view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: custom performance counter in c# / perfmon Hi I am trying to to create a custom performance counter for use in perfmon. The following code works pretty well, however I have one problem.. With this solution I have a timer updating the value of the performance counter, however I would like to not have to run this executable to get the data I need. That is I would like to just be able to install the counter as a one time thing and then have perfmon query for the data (as it does with all the pre-installed counters). How can I achieve this? using System; using System.Diagnostics; using System.Net.NetworkInformation; namespace PerfCounter { class PerfCounter { private const String categoryName = "Custom category"; private const String counterName = "Total bytes received"; private const String categoryHelp = "A category for custom performance counters"; private const String counterHelp = "Total bytes received on network interface"; private const String lanName = "Local Area Connection"; // change this to match your network connection private const int sampleRateInMillis = 1000; private const int numberofSamples = 100; private static NetworkInterface lan = null; private static PerformanceCounter perfCounter; static void Main(string[] args) { setupLAN(); setupCategory(); createCounters(); updatePerfCounters(); } private static void setupCategory() { if (!PerformanceCounterCategory.Exists(categoryName)) { CounterCreationDataCollection counterCreationDataCollection = new CounterCreationDataCollection(); CounterCreationData totalBytesReceived = new CounterCreationData(); totalBytesReceived.CounterType = PerformanceCounterType.NumberOfItems64; totalBytesReceived.CounterName = counterName; counterCreationDataCollection.Add(totalBytesReceived); PerformanceCounterCategory.Create(categoryName, categoryHelp, PerformanceCounterCategoryType.MultiInstance, counterCreationDataCollection); } else Console.WriteLine("Category {0} exists", categoryName); } private static void createCounters() { perfCounter = new PerformanceCounter(categoryName, counterName, false); perfCounter.RawValue = getTotalBytesReceived(); } private static long getTotalBytesReceived() { return lan.GetIPv4Statistics().BytesReceived; } private static void setupLAN() { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface networkInterface in interfaces) { if (networkInterface.Name.Equals(lanName)) lan = networkInterface; } } private static void updatePerfCounters() { for (int i = 0; i < numberofSamples; i++) { perfCounter.RawValue = getTotalBytesReceived(); Console.WriteLine("perfCounter.RawValue = {0}", perfCounter.RawValue); System.Threading.Thread.Sleep(sampleRateInMillis); } } } } A: In Win32, Performance Counters work by having PerfMon load a DLL which provides the counter values. In .NET, this DLL is a stub which uses shared memory to communicate with a running .NET process. The process periodically pushes new values to the shared memory block, and the DLL makes them available as performance counters. So, basically, you're probably going to have to implement your performance counter DLL in native code, because .NET performance counters assume that there's a process running.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: CakePHP containable and paginate - deep associations not appearing I'm trying to use containable in a paginated query. The code is below, in full. $this->paginate = array( 'conditions'=>array( 'Track.pending'=>0, 'Track.status'=>1 ), 'contain'=>array( 'Vote'=>array( 'conditions'=>array( 'Vote.created >'=>$start, 'Vote.created <='=>$end ), 'fields'=>array( 'Vote.vote_type_id', 'Vote.id', ), ), 'Artist'=>array( 'Image'=>array( 'fields'=>array( 'Image.name' ) ), 'Genre'=>array( 'fields'=>array( 'Genre.name' ) ), 'fields'=>array( 'Artist.name', 'Artist.id', 'Artist.slug', 'Artist.city', 'Artist.genre_id' ) ) ), 'fields'=>array( 'Track.id', 'Track.slug', 'Track.name', 'Track.featured', 'Track.plays', 'Track.vote_score', 'Track.vote_week_score', 'Track.video', 'Track.status', 'Track.created' ), 'order'=>$order ); The direct associations (Vote and Artist) are picked up, but Image and Genre are not. Here's the SQL that is being generated: SELECT COUNT(*) AS `count` FROM `tracks` AS `Track` LEFT JOIN `artists` AS `Artist` ON (`Track`.`artist_id` = `Artist`.`id`) WHERE `Track`.`pending` = 0 AND `Track`.`status` = 1 SELECT `Track`.`id`, `Track`.`slug`, `Track`.`name`, `Track`.`featured`, `Track`.`plays`, `Track`.`vote_score`, `Track`.`vote_week_score`, `Track`.`video`, `Track`.`status`, `Track`.`created`, `Artist`.`name`, `Artist`.`id`, `Artist`.`slug`, `Artist`.`city`, `Artist`.`genre_id` FROM `tracks` AS `Track` LEFT JOIN `artists` AS `Artist` ON (`Track`.`artist_id` = `Artist`.`id`) WHERE `Track`.`pending` = 0 AND `Track`.`status` = 1 ORDER BY `Track`.`vote_week_score` DESC LIMIT 20 SELECT `Vote`.`vote_type_id`, `Vote`.`id`, `Vote`.`track_id` FROM `votes` AS `Vote` WHERE `Vote`.`created` > '2011-09-26' AND `Vote`.`created` <= '2011-10-03' AND `Vote`.`track_id` IN (24, 35, 31, 25, 27, 34, 56, 58) Cake is not picking up the deeper associations. Is this a limitation of Containable + paginate or am I missing something? Thanks! A: Check if you have zero value for recursion property of the model. $this->Post->recursive = 0; After hours of headbanging removing the above line fixed it for me A: Make sure you attach the behavior: $this->ModelName->Behaviors->attach('Containable'); A: Probably the problem is $uses in your controller, in case you have it set in AppController. Example: Let's say your controller is ProductsController, your model is Product and your database table is products. Also you probably have some sort of associations set in your Model. If you don't set $uses in the Controller, but set it in AppController, Cake presumes the database table correctly and workes fine. But he doesn't look for your Model file as it doesn't appear in $uses (the one defined in AppController). So it will work if you write in your controller: public $uses = array('Yourmodel'); Also: * *You don't have to set 'recursive', this is why contain exists *Don't forget to fetch the foreignKeys in contain ex: Product 'fields'=>array('category_id'); Category 'fields'=>'product_id'
{ "language": "en", "url": "https://stackoverflow.com/questions/7633986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: can XML be send as response to iframe I am trying send xml data as response to iframe which is dynamically generated. i am sending the follwing data as response out.println( "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + " <response> " + My_data + "</response>" ); when i check using firebug i only see the follwing innerHTML <response> My_data </response> if i am trying to parse the xml i get uncaught exception: Invalid XML error. here is my js var xml = this.contentDocument.body.innerHTML, /* this : iframe id */ xmlDoc = $.parseXML( xml ), $xml = $( xmlDoc ), $title = $xml.find( "<file-url>" ); alert($title.text()); How can i send XML response & parse. A: It is generaly a good idea to use AJAX. How do you actually load that xml into an IFRAME? By using static SRC or Javascript? You have also typos in your code. * *Javascript command has to end with semicolon not a comma *jQuery.find accepts only name of the tag without <> *You can prepend a xml header (<?xml ..?>) just before your innerHTML, but its not neccessary here This should work: var xml = this.contentDocument.body.innerHTML, /* this : iframe id */ var xmlDoc = $.parseXML( xml ); var $xml = $( xmlDoc ); var $title = $xml.find( "file-url" ); alert($title.text());
{ "language": "en", "url": "https://stackoverflow.com/questions/7633987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove the title in Dialog? I created an Activity as a dialog using the code below which I put in my manifest. But the problem is it has Title bar, how can I remove it? android:theme="@android:style/Theme.Dialog" A: if Dialog .............. Dailog dialog = new Dialog(MainActivity.this, R.style.mydialogstyle); res-->values-->mydialog.xml <?xml version="1.0" encoding="utf-8"?> <resources> <style name="mydialogstyle" parent="android:style/Theme.Dialog"> <item name="android:windowBackground">@null</item> <item name="android:windowNoTitle">false</item> </style> </resources> A: For Me following worked : <style name="MyActivityDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog"> <item name="android:windowNoTitle">true</item> <item name="android:windowActionBar">false</item> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> A: Use this code when creating a dialog: requestWindowFeature(Window.FEATURE_NO_TITLE); A: For those who are using AppCompatActivity, above answers may not work. Try this supportRequestWindowFeature(Window.FEATURE_NO_TITLE); immediately before setContentView(R.layout.my_dialog_activity); A: Use This Code final Dialog dialog = new Dialog(context); dialog.getWindow(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.yourlayout); dialog.show(); A: this is work for me <?xml version="1.0" encoding="utf-8"?> <resources> <style name="mydialogstyle" parent="android:style/Theme.Dialog"> <item name="android:windowBackground">@null</item> <item name="android:windowNoTitle">true</item> </style> </resources> and this requestWindowFeature(Window.FEATURE_NO_TITLE); A: Remove Title Bar from Activity extending ActionBarActivity or AppcompatActivity with Dialog Theme <style name="Theme.MyDialog" parent="@style/Theme.AppCompat.Light.Dialog"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> A: It work for me: In the onCreate() of my custom Dialog Activity: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_alert_dialogue); //your code.... } Manifest: <activity android:name=".AlertDialogue" android:theme="@style/AlertDialogNoTitle"> </activity> Style: <style name="AlertDialogNoTitle" parent="Theme.AppCompat.Light.Dialog"> <item name="android:windowNoTitle">true</item> </style> A: Handler _alerthandler = new Handler(); Runnable _alertrunnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub ProfileActivity.this.runOnUiThread(new Runnable() { public void run() { // Create custom dialog object final Dialog dialog = new Dialog(ProfileActivity.this); // Include dialog.xml file dialog.getWindow(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.alertbox); TextView title = (TextView) dialog .findViewById(R.id.AlertBox_Title); title.setText(Appconstant.Toast_Title); TextView text = (TextView) dialog .findViewById(R.id.AlertBox_Msg); text.setText(Appconstant.Toast_Msg); dialog.show(); Button declineButton = (Button) dialog .findViewById(R.id.AlertBox_Ok); // if decline button is clicked, close the custom dialog declineButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Close dialog dialog.dismiss(); } }); } }); } }; A: I try requestWindowFeature(Window.FEATURE_NO_TITLE); but not working for me, if you are like me so do this : first Add the following code in your res/values/styles.xml: <style name="NoTitleDialog" parent="Theme.AppCompat.Dialog"> <item name="android:windowNoTitle">true</item></style> Pass the theme to your dialog: Dialog dialog = new Dialog(this, R.style.NoTitleDialog); that's it very simple
{ "language": "en", "url": "https://stackoverflow.com/questions/7633990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: C Structure formula Having problems with the output of this formula: typedef struct { float t, Vx, Vy, Px, Py; } datapoint; datapoint *data; data = malloc(steps * sizeof(datapoint)); data[0].Vx = (20*cos(30)); //30 is changed to radians data[0].Vy = (20*sin(30)); data[0].Px = 0; data[0].Py = 0; steps=100; i=1; do { printf("Time: %.2f\t",i*q5); // X data[i].Vx = data[i-1].Vx ;//- CalculateDrag(data[i-1].Vx, q4); data[i].Px = ((data[i-1].Px) + ((data[i].Vx) * i)); printf("X = %.2f\t",data[i].Px); // Y data[i].Vy= data[i-1].Vy - (9.81)*i; //- CalculateDrag(data[i-1].Vy,q4); data[i].Py= data[i-1].Py + (data[i].Vy * i); printf("Y = %.2f\t", data[i].Py); printf("\n"); i++; } while(((data[i].Py) >0) && (i<=steps)); The output should look like this: Time 0.10s: X = 1.73m Y = 1.00m Time 0.20s: X = 3.46m Y = 1.90m Time 0.30s: X = 5.20m Y = 2.71m .... .... Time 2.00s: X = 34.64m Y = 1.36m Time 2.10s: X = 36.37m Y = 0.40m Time 2.20s: X = 38.11m Y = -0.66m Landed at X = 38.11 at time 2.20s But instead it prints out other values. Tried what i can but think there is maybe faulty code with the formula. A: From the code you've posted: datapoint *data; data[0].Vx = (20*cos(30)); You're using data uninitalised here. It could be pointing anywhere and this is undefined behaviour so anything could happen. I think from reading your code you wanted to do something like: data = malloc(sizeof(datapoint) * steps); A: Your datapoint variable is not initialized, it points somewhere in the data, which can be really dangerous. You should initialize it by allocating memory for your structs. I suggest you use the malloc or calloc function to do so. e.g: datapoint *data = calloc(sizeof(datapoint), 20); Now that you have allocated your array of structs, you should deallocate it in the end, after you are done reading/writing it: free(data); EDIT: I don't even think you are needing dynamic memory, it would be sufficient if you declare your array as follows: datapoint data[20]; You do not have to free it now. In fact it would be dangerous to do so. A: It looks like you're trying to incrementally update values but are using absolute time values: data[i].Px = ((data[i-1].Px) + ((data[i].Vx) * i)); since you're using the previous step value to calculate the new value (LHS of +) but adding on the current speed multiplied by the total time so far (RHS of +). You either need to use absolute values: data[i].Px = ((data[0].Px) + ((data[i].Vx) * i)); or incremental values: data[i].Px = ((data[0].Px) + ((data[i].Vx) * t)); // where t is the time step This works OK with Px since there's no acceleration component. The Py component has an acceleration component so doing the incremental version will introduce an error, since speed is not constant throughout the time step interval. You are approximating a curve with a series of linear sections. I guess you're trying to implement the following: s = ut + at2/2 and trying to find the point where s.y is zero (hitting the ground). Rather than using an array and incrementally calculate s, use the above equation like this: t = 0; u = initial vector; a = gravity; do { t += time step; s = u * t + a * t * t / 2; } while (s.x >= 0); You would also benefit from using a vector library (not std::vector, but a math vector), then you can write the equation just like in the code above and not calculate the x and y parts individually. It will also be easier to migrate to a 3D system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Panel arrangement in wxpython Background As a newbie to python as well as to GUI Programming, I would like to create a wxpython based GUI application. This GUI will run a series of tests The tests written in text files will be running and it's steps should be displayed in the Window. For selecting a particular test,click the checkbox (CheckListCtrl in Figure below) for that particular test. The result of the test will be displayed in MulilineTextCtrl_2Log The window should be like this : My ASCII art is not so good but anyways |-------------------------------------------------------------| |WINDOW TITLExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx_[]X| |xxx[SelectAll]xxxxxx[DeselectAll]xxxxxxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |[CheckListCtrl] [MultilineTexTCtrl_1]xxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx[Refresh]xxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx[Execute]xxx| |xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |xxxxxxx[MulilineTextCtrl_2Log]xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx| |_____________________________________________________________| I have having trouble over creating the boxsizers for this window. I am having trouble visualizing the creation of panels TestList = [('Test1', 'Test1Description1', 'base'), ('Test2', 'Test1Description1', 'base'),'Test3', 'Test1Description3', 'base'),] class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin): def __init__(self, parent): wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER) CheckListCtrlMixin.__init__(self) ListCtrlAutoWidthMixin.__init__(self) class MainGUI(wx.frame): panel = wx.Panel(self, -1) vbox = wx.BoxSizer(wx.VERTICAL) hbox = wx.BoxSizer(wx.HORIZONTAL) #topPanel = wx.Panel(panel,-1) topPanel = wx.Panel(panel, -1,pos=(0,0)) bottomPanel = wx.Panel(panel, -1,pos=(1,0)) self.log = wx.TextCtrl(bottomPanel, -1, style=wx.TE_MULTILINE) self.list = CheckListCtrl(bottomPanel) self.list.InsertColumn(0, 'TestID', width=140) self.list.InsertColumn(1, 'TestDescription') for i in TestList: index = self.list.InsertStringItem(sys.maxint, i[0]) self.list.SetStringItem(index, 1, i[1]) self.list.SetStringItem(index, 2, i[2]) vbox2 = wx.BoxSizer(wx.VERTICAL) sel = wx.Button(topPanel, -1, 'Select All', size=(100, -1)) des = wx.Button(topPanel, -1, 'Deselect All', size=(100, -1)) refresh = wx.Button(bottomPanel, -1, 'Refresh', size=(100, -1)) apply = wx.Button(bottomPanel, -1, 'Execute', size=(100, -1)) self.Bind(wx.EVT_BUTTON, self.OnSelectAll, id=sel.GetId()) self.Bind(wx.EVT_BUTTON, self.OnDeselectAll, id=des.GetId()) self.Bind(wx.EVT_BUTTON, self.OnRefresh, id=refresh.GetId()) self.Bind(wx.EVT_BUTTON, self.OnExecute, id=apply.GetId()) vbox2.Add(sel, 0, wx.TOP, 5) vbox2.Add(des) vbox2.Add(apply,wx.RIGHT) vbox2.Add(refresh) topPanel.SetSizer(vbox2) vbox.Add(self.list, 1, wx.EXPAND, 3) vbox.Add((-1, 10)) vbox.Add(self.log, 0.5, wx.EXPAND) vbox.Add((-1, 10)) bottomPanel.SetSizer(vbox) hbox.Add(bottomPanel, 0, wx.EXPAND | wx.RIGHT, 5) panel.SetSizer(hbox) self.Centre() self.Show(True) def OnSelectAll(self, event): num = self.list.GetItemCount() for i in range(num): self.list.CheckItem(i) def OnDeselectAll(self, event): num = self.list.GetItemCount() for i in range(num): self.list.CheckItem(i, False) def OnRefresh(self, event): num = self.list.GetItemCount() for i in range(num): if i == 0: self.log.Clear() if self.list.IsChecked(i): self.log.AppendText(self.list.GetItemText(i) + '\n') def OnExecute(self, event): num = self.list.GetItemCount() for i in range(num): if i == 0: self.log.Clear() if self.list.IsChecked(i): self.log.AppendText(self.list.GetItemText(i) + '\n') app = wx.App() MainGUI(None, -1, 'Tester') app.MainLoop() A: I recommend to you the use of wxglade to design your GUIs. It is fast and effective and after you have some experience you can do most of the things you can do manually. wxglade does not have wx.lib widgets suchs as CheckListCtrlMixin or ListCtrlAutoWidthMixin that you are using or combinations such as your class CheckListCtrl. In order to be able to use these, fill temporarily a slot in the GUI with an available widget (p.e. a wx.panel) and then later, after generating the code, substitute manually the wx.Panel instantiation with that of your special or custom class. Finally, your code has some major problems that produce exceptions such as wx.frame (for wx.Frame), the bad indentation or the undefined TestList. Your MainGUI class has not __init__ method and does neither initialize the parent wx.Frame. Also the bottomPanel is added to hbox sizer but not the topPanel. The organization you wrote does not produce the GUI structure you describe but that of two panels with several widgets: To be closer to your description you need at least to add a couple of additional sizers. Use wxglade and it will do everything for you. Here you have the wxglade generated code for a design like yours (substitute the wx.ListCtrl with your CheckListCtrl: #!/usr/bin/env python # -*- coding: iso-8859-15 -*- # generated by wxGlade HG on Tue Oct 04 12:45:03 2011 import wx # begin wxGlade: extracode # end wxGlade class MainGUI(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MainGUI.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.button_3 = wx.Button(self, -1, "Select All") self.button_4 = wx.Button(self, -1, "DeselectAll") self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER) self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) self.button_1 = wx.Button(self, -1, "Refresh") self.button_2 = wx.Button(self, -1, "Execute") self.text_ctrl_2 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MainGUI.__set_properties self.SetTitle("frame_1") self.SetBackgroundColour(wx.Colour(255, 170, 5)) self.list_ctrl_1.SetMinSize((200, 264)) # end wxGlade def __do_layout(self): # begin wxGlade: MainGUI.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_2 = wx.BoxSizer(wx.HORIZONTAL) sizer_3 = wx.BoxSizer(wx.VERTICAL) sizer_4 = wx.BoxSizer(wx.HORIZONTAL) sizer_4.Add(self.button_3, 0, wx.ALL, 5) sizer_4.Add(self.button_4, 0, wx.ALL, 5) sizer_4.Add((20, 20), 1, wx.EXPAND, 0) sizer_1.Add(sizer_4, 0, wx.EXPAND, 0) sizer_2.Add(self.list_ctrl_1, 0, wx.ALL|wx.EXPAND, 5) sizer_2.Add(self.text_ctrl_1, 0, wx.ALL|wx.EXPAND, 5) sizer_3.Add(self.button_1, 0, wx.ALL, 5) sizer_3.Add(self.button_2, 0, wx.ALL, 5) sizer_2.Add(sizer_3, 0, wx.EXPAND, 0) sizer_1.Add(sizer_2, 1, wx.EXPAND, 0) sizer_1.Add(self.text_ctrl_2, 0, wx.ALL|wx.EXPAND, 5) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() # end wxGlade # end of class MainGUI if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MainGUI(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop() And the look: Note, as said in other answer, there is not need for putting your widgets in panels (widget(panel,..)) and the panels in sizers. It works, but it is better to simply put your widgets (as child of the frame -> widget(self,..)) in the sizers (sizerx.Add(widget,..)) and sizers in sizers (sizery.Add(sizerx)) to build the structure. Normally you do not modify this code. You subclass it instead to add your functionality or whatever fancy addition you need. In this way you can always use again wxglade to make changes in the position of the widgets ot to add additional widgets or sizers and regenerate the full file. A: You don't really need all those extra panels. In fact, you rarely need more than one except for wx.Notebooks and the like. Instead, what I find to be the easiest way to visualize this sort of thing is to sketch it out on a piece of paper and then draw rectangles around the stuff. For this, I would have a main BoxSizer vertically oriented. Then I'd use two horizontal BoxSizers for the buttons and the next to controls. If you have to position the other three single widgets that way, then you'd probably want some other BoxSizers with spacers in them. Anyway, once you have the widgets in the various BoxSizers, you add them to the MainSizer and you're done. Or you could use a GridSizer with a few spacers for the last three.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.net Caching Issue I have cached a dataset which has "StoreId" column. When I want to export the dataset to Excel I suppose to remove the "StoreId" column from the dataset and Exprot. Following is the code for Removing and Exporting to Excel. if (HttpContext.Current.Cache["stores"] != null) { using (DataSet dsStores = (DataSet)HttpContext.Current.Cache["stores"]) { if (TrainingUtil.isDataSetValid(dsStores)) { DataTable dt = dsStores.Tables[0]; dt.Columns.Remove("storeId"); Quality.Qulaity_Utility.ExportDataSet(dt, ddlCity.SelectedItem.Text.ToString() + "_StoreCodes"); } } } public static void ExportDataSet(DataTable dt,string filename) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "application/vnd.xls"; HttpContext.Current.Response.Charset = ""; HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename.Replace(" ", "_").ToString() + ".xls"); DataGrid dgRecord = new DataGrid(); //Color Setttings dgRecord.HeaderStyle.BackColor = System.Drawing.Color.Cyan; dgRecord.DataSource = dt; dgRecord.DataBind(); //Cells color settings foreach (DataGridItem dgi in dgRecord.Items) { foreach (TableCell tcGridCells in dgi.Cells) { tcGridCells.Attributes.Add("class", "sborder"); } } //Render the datagrid StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter); dgRecord.RenderControl(htmlTextWriter); //lstMonthlyReport.RenderControl(htmlTextWriter); //Add the style sheet class here HttpContext.Current.Response.Write(@"<style> .sborder { color : Black;border : 1px Solid Black; } </style> "); //Export HttpContext.Current.Response.Write(stringWriter.ToString()); //End HttpContext.Current.Response.End(); //style to format numbers to string //string style = @"<style> body { mso-number-format:\@; } </style>"; } } after exporting the data and When I once againg want Stores information from Cached dataset I was unable to find the "StoreId" Column, I'm unable figure out where I'm doing wrong. Plz help me out. Thanks in advance. A: You will make your life easier if you never modify objects you put in Cache. Removing columns from a DataSet is not thread-safe, so if multiple requests access the Cache concurrently, you're in trouble. In this case, I would create a clone of the DataSet and export the clone. To do so, use the DataSet.Copy method: DataSet dsStores = ((DataSet)HttpContext.Current.Cache["stores"]).Copy() Or find a way of doing the export that doesn't require you to modify the DataSet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jQuery and label input <div id="one"> <label for="number">Number</label> <div id="two"> <input id="number" type="text" name="number"> </div> </div> This show me: * *Number *[input] How can I make: * *Number [input] How can I modify this with jQuery? (not modify html) LIVE: http://jsfiddle.net/UBx6p/ A: Use a <span> instead of a <div>. <div id="one"> <label for="number">Number</label> <span id="two"> <input id="number" type="text" name="number"> </span> </div> A: Can you use CSS rather than javascript? #two { display:inline-block; } A: If you want it only in JS. Then as suggested use something like this document.getElementById('two').style.display = 'inline'; A: Well, you really should change the HTML as stated above by Xavi. If that is out of the question, you can perform the HTML changes via jQuery: $('#one label').css('float', 'left'); $('#one #two').css('float', 'left'); $('#one #two').css('margin-left', '5px'); $('#one').append('<div style="clear:both"></div>'); put it here : http://jsfiddle.net/UBx6p/8/
{ "language": "en", "url": "https://stackoverflow.com/questions/7634000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i add textbox value entered by user to label dynamically using jquery? Hi How can i add textbox value on button click to the label like this http://jsfiddle.net/NT4Zr/29/ In above code user can type his hobby and add into the form by using add hobby link. when user press add hobby link the textbox value should be added to the label and for each entry new label created dynamically. after adding hobbies user can free to delete hobbies by using delete button. how can i do that? A: Would something like the below be what you're looking for? <!-- The container into which new hobbies will be inserted --> <ul id="hobbies"> </ul> <form method="post" action=""> <!-- The form element the user will use to enter new labels. Note that the value of the for attribute of the label element matches the value of the id attribute of the input element --> <label for="hobby">Hobby:</label><input type="text" id="hobby" /><br /> <a id="add-hobby">Add Hobby</a><br /> <input type="submit" id="saveStudentInfo" value="Save Details" /> </form> <!-- $(handler) is a shorthand for $(document).ready(handler) see http://api.jquery.com/ready/ --> <script> // would be placed in the HEAD, of course $(function (){ $('#add-hobby').click(function () { // Extract the input value var newHobbyText = $("#hobby").val(); // Create the list item to add var $newHobbyListItem = $("<li></li>").text(newHobbyText); // Create the delete link var $deleteLink = $("<a></a>").text("Delete").css("margin-left","5px"); // Register a delete handler (could be done as part of the above line) $deleteLink.click(function () { $newHobbyListItem.remove(); }); // Add the delete link to the list item $newHobbyListItem.append($deleteLink); // Finally, add the new item to the DOM $("#hobbies").append($newHobbyListItem); }); }); </script> Some notes on this implementation: * *I choose to use an unordered list over a table because it's less work and, arguably, more semantically correct. *If you need to add an input element (or similar) to the form to track what hobbies have been added, that's simple enough to do (just follow the above pattern for building, appending, and removing elements; currently, the delete handler removes only the list item, but it could remove an input element as well. However, I wasn't sure how you planned to process this data, so it's not clear what the best information to place in the input elements would be. *I removed a few HTML elements (e.g. the "Hobbies" heading, the cancel button) as they seemed to clutter the example. There's no reason they need to be omitted, but I was hoping to keep things concise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I save in mongodb Hebrew characters? I work with ruby on rails and want to save in mongodb data with Hebrew characters. How can I do this? thanks, A: MongoDB supports UTF-8 out of the box, which means you simply have to encode your strings into UTF-8. Here's a few links you can peruse: MongoDB & I18n strings I18n and rails railscast and finally, Encoding strings in Ruby 1.9
{ "language": "en", "url": "https://stackoverflow.com/questions/7634003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: perl input multiple files Possible Duplicate: How can I pass command-line arguments to a Perl program? I have a perl script that I need to run on the command line but also provide three input files and one output. I dont want to do a STDIN as I am writing a wrapper script to use the perl script multiple times for multiple files. So, I have this now: open (FICHIER, "<$file1") || die "file not found"; chomp($file1); @b=<FICHIER>; open (SPECIES, "<$file2"); $species=<SPECIES>; chomp($species); open (FILE3, "<$file3>"); $file3 = <FILE3>; chomp($file3); open (OUTFILE, ">$outfile"); chomp($outfile); I need to do something like this: perl myscript.pl textfile1 textfile2 textfile3 outputfile I need $file1 to represent textfile1, $file2 for textfile2 etc. Thanks in advance Mark A: In the main program a shift function pulls arguments of off @ARGV, which is the list of command line parameters. So you could say: my $file1 = shift || die "Need 4 file names"; my $file2 = shift || die "Need 4 file names"; my $file3 = shift || die "Need 4 file names"; my $outfile = shift || die "Need 4 file names"; Also, "use strict;" and "use warnings;" is good practice, and the three argument open:: open my $FICHIER, '<', $file1 or die "$file1 - $!";
{ "language": "en", "url": "https://stackoverflow.com/questions/7634007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scala Predef unimport Possible Duplicate: How to unimport String “+” operator in Scala? So things from Predef get automatically imported into scala programs. But how can I disable- unimport certain or all imported functions from Predef? As an example if I don't like the '+' operator on String how to disable this functionality? A: As mentioned in the linked answer, the method String#+(other: Any) is added to the String class with compiler magic, rather than with an implicit conversion. As such, it isn't related to the automatic import of Predef._. The same applies to Int#+(x: String), and corresponding method on the other value types. However, there is another String concatenation method that is added by an implicit conversion in Predef. x + "2" is treated as Predef.any2stringAdd(x).+("2"). By explicitly importing Predef on the first line of your file, you can rename unwanted members to _, disabling them. import Predef.{any2stringadd => _, _} object Test { object A A + "20" // error: value + is not a member of object Test.A } I don't think that this works in Scala Scripts or in the REPL. There is also an unsupported option, -Yno-predef, to turn of the automatic import globally. Related: SI-1931
{ "language": "en", "url": "https://stackoverflow.com/questions/7634015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Split payment process on magento? * *How can we split payment process on magento? Suppose i purchased a product from magento store worth of 1000 USD. Im having 500 USD in my credit card and 500 USD in my paypal account. Is it possible to split the payment to purchase this product? Note: Not by recurring payment, i want to use more than one payment method for single order.. * *Is there any option to add MISC amount by admin for the orders that are in pending status in magento? Thanks in advance, Satheesh A: There is no bundled way for this. to achieve this you need to implement a payment method that allows this and enables storing n amount of payment instances to one order. It's rather easy to implement this with one payment method available and use the transactions method provided by payment api. To achieve multiple different payment methods you must extend the payment api or if you are satisfied with one payment method instance being available you can also use transactions api for this
{ "language": "en", "url": "https://stackoverflow.com/questions/7634018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is it preferred to import a class (ex. import flash.events.MouseEvent ) instead of the entire contents of a package (ex. import flash.events.*) Is there benefit to specifying which class, function or namespace you intend to use at the beginning of the code? A: the reference says: If you import a class but do not use it in your script, the class is not exported as part of the SWF file. This means you can import large packages without being concerned about the size of the SWF file; the bytecode associated with a class is included in a SWF file only if that class is actually used. One disadvantage of importing classes that you do not need is that you increase the likelihood of name collisions. however, it's much more convinient (for me) to have an exact list of classes that are used in the code that follows A: It only affects compile time, and not to any great extent as far as I've noticed. One benefit is that your import statements act as a "definition" of what external classes are used, but personally I don't really find that useful. A: well, if you call the specified object more than once in your code you have the benefit of saving keystrokes. also, if the class is moved to a different folder it's much easier to simply update only one import line. it's also cleaner looking, in my opinion. i thought i tried writing the path once in my AS3 code and it wouldn't compile. perhaps it was a setting i have but i was under the impression that this was not possible in AS3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to do lower() and raise() for QGraphicsItem in Qt? I wanted to changed z-order of graphicsitems in my graphicsscene. I have used QGraphicsWebView as graphicsitem. How can i achieve it ? A: You can use setZValue, isObscured and isObscuredBy. Documentation is precise about these methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: It takes time while exporting telerik grid to pdf I am trying to export telerik grid data to pdf/excel. Although telerik provides handy methods to export grid to pdf/excel but it takes lots of time to export the grid to desired format if there are more than 500 rows in the grid. Note: I want to export whole data but not visible page in the grid. Thanks Anil. A: The time needed to export this content depends strongly on your grid structure. You may be able to export 500 items or even 30000 items but to reiterate, it all depends on your setup. Post your markup here and I will look inside for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ExtJs - GroupingView style Need to make tpl for Grouping Grid. Now I'm doing a property groupTextTpl. Code in it: groupTextTpl : '{[values.rs[0].data["name"]]} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})' But I want to display next to the name drop-down lists - references and to move the inscription "1 items" to the right like this How to implement it? A: I'm not 100% sure if this is possible, but try wrapping the "# items" part in a HTML <span> tag, give it a class name and then create CSS code to align it to the right side. I.e: groupTextTpl : '{[values.rs[0].data["name"]]} <span class="quantity">({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})</span>' Then in the CSS you can do something like this: .quantity { float: right; } Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find quickly index of item in sorted list I have a object: public class MyObject { int id; string value; } I also have a list: List<MyObject> list = new List<MyObject>; for(int i=0;i;i<100000;i++) { list.Add(new MyObject(i, string.Format("Item {0}", i)); } And list will be: 1, "Item 1" 2, "Item 2" .... 99999, "Item 99999" This list is a sorted list which sorted on ID field. Note this is an example to describe a sorted list, it is not simple like the above example. I want to find a item of ordered list based on ID field. I don't know .NET Framework has support quickly search on a ordered list without enumerating. I am interested in performance because of a big list. Thanks. Best regards. A: You can use a binary search for this. You can use the built-in implementation, providing a custom IComparer<T> that compares on your type's id property: var objToFind = new MyObject { id = 42 }; int foundIndex = yourList.BinarySearch(objToFind, new MyObjectIdComparer()); // ... public class MyObjectIdComparer : Comparer<MyObject> { public override int Compare(MyObject x, MyObject y) { // argument checking etc removed for brevity return x.id.CompareTo(y.id); } } A: Four options: * *If your list will always contain items with ID 1...n, then you can just do: MyObject foo = list[id - 1]; *You could populate a Dictionary<int, MyObject> *You could make MyObject implement IComparable<T> or IComparable (ordering by ID) and use List<T>.BinarySearch, providing a dummy MyObject with the desired ID *You could implement binary searching yourself - it's not terribly hard to do so Note that if you take the last approach, you may want to do so in a generic way as an extension method so that you can reuse it later: // Optionally another overload with an IComparer<TKey> public static TItem ProjectedBinarySearch<TItem, TKey>( this IList<TItem> list, Func<TItem, TKey> projection) { // Do the binary search here. // TODO: Decide what to do if you can't find the right value... throw // an exception? Change the return type to return the *index* instead of the // value? } A: I assume it won't actually be 1:1 with array index and ID field (like in your example), or you could just use the []-method to find it. Option 1 would be to add it to a Dictionary instead, and use ID field as key. Option 2 is to write a makeshift binary search, starting at the middle of the array and checking if the current id is larger, smaller or correct. Then doing it again with the new sub-array until you find your ID. A: Instead of a brute force, start-end, search, you could implement some kind of binary division and that should speed it up nicely. Or use the Dictionary type instead? A: You can simply use .Find() to find an item in a list, without explicitely enumerating: http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx EDIT: Actually, looking in more detail it looks like this is a linear search and might not be what you want. A: The index regarding you ID is ID - 1. However, if you have deleted items, that way will no work. You can then use Binary search, PROVIDED that you list is sorted. So you have to keep it always sorted, or you will use uneffecient Linear search. A: Take a look at Linq using System.Linq; Obtain a queryable from your list (usually via .AsQueryable() call) Apply a .Select() on obtained Queryable var c = queryable.Select (x => x.field == 999) A: For those people who have come across this question based on it's title (Find quickly index of item in sorted list) you may be interested to know that SortedList< TKey, TValue> has the following two methods:- public int IndexOfKey(TKey key); public int IndexOfValue(TValue value); and SortedList has:- public virtual int IndexOfKey(object key); public virtual int IndexOfValue(object value);
{ "language": "en", "url": "https://stackoverflow.com/questions/7634033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Ajax Crawlable Rewrite!!? _escaped_fragment_= I have started down the ajax site path using hash bang currently my urls look like: http://www.domain.com/#!/index http://www.domain.com/#!/studio http://www.domain.com/#!/about from reading google's docs: http://code.google.com/web/ajaxcrawling/ it looks like google will try and rewrite http://www.domain.com/#!/studio to http://www.domain.com/?_escaped_fragment_=studio I was wondering how I would get an IIS7 rewrite rule to redirect the escaped fragment to: http://www.domain.com/studio i.e. take the querystring arg and map it back to the root the site is done in asp.net using umbraco so i have access to the rewrite config file from umbraco also! Cheers A: @Giberno : It seems that you do not understand what pennylane is asking. The whole reason pennylane is trying to redirect through IIS / web.config is so that the search engine robots are redirected to a static pre generated .htm/.html file. The next gen robots, like googlebot, recognise a hashbang. hashbang = '#!' in 'http://example.com/#!/some/page/with/ajax/content' When a robot detects this hashbang in the url it will convert the url to a _escaped_fragment_ query string url. The example from above will be converted to: 'http://example.com/?_escaped_fragment_=/some/page/with/ajax/content' This because robots can not execute the javascrip. Yet you give a javascript solution? Enlighten me if I am wrong. More info on AJAX Applications and SEO @pennylane : I am trying to do the same and I think I got it. Situation: * *snapshots directory = 'http://example.com/snapshots/...' *snapshot name = 'snapshot_{page}' where {page} = the pagename ex : 'http://example.com/snapshots/snapshot_contact.html' When I browse to a snapshot, the snapshot is shown with a statuscode 200 OK. I placed the following rewrite rule for the web.config file: <configuration> <system.webServer> <rewrite> <rules> ... other rewrite rules ... <rule name="EscapedFragment" stopProcessing="true"> <match url="(.*)"/> <conditions> <add input="{QUERY_STRING}" pattern="_escaped_fragment_=/([_0-9a-zA-Z-]+)" /> </conditions> <action type="Rewrite" url="snapshots/snapshot_{C:1}.html" appendQueryString="false" /> </rule> ... other rewrite rules ... </rules> </rewrite> ... other configs ... </system.webServer> </configuration> Redirect Rule Explenation: Match: <match url="(.*)"/> The rule is called on any url. Condition: <add input="{QUERY_STRING}" pattern="_escaped_fragment_=/([_0-9a-zA-Z-]+)" /> If '_escaped_fragment_=/' is followed by a alphanumiriq string, with or without cased characters, underscore (_) or hyphen (-) ... Rewrite Action: <action type="Rewrite" url="snapshots/snapshot_{C:1}.html" appendQueryString="false" /> Rewrite to the url without appending the query string. Where {C:1} = the value of the '_escaped_fragment_' query string parameter Info Sources: I constructed this rewrite rule based on the following information: * *Creating Rewrite Rules for the URL Rewrite Module *URL Rewrite Module 2.0 Configuration Reference : TRACKING CAPTURE GROUPS ACROSS CONDITIONS *Testing patterns : Testing Rewrite Rule Patterns Result: Browsing to: 'http://example.com/?_escaped_fragment_=/test' Should rewrite to: GET 'http://example.com/snapshots/snapshot_test.html' Testing the pattern {C:1} = 'test'. Testing: In my opinion the easiest way to test if your rewrite rule is working is to follow these steps: <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>URL Rewrite Module Test</title> </head> <body> <h1>URL Rewrite Module Test Page</h1> <table> <tr> <th>Server Variable</th> <th>Value</th> </tr> <tr> <td>Original URL: </td> <td><%= Request.ServerVariables["HTTP_X_ORIGINAL_URL"] %></td> </tr> <tr> <td>Final URL: </td> <td><%= Request.ServerVariables["SCRIPT_NAME"] + "?" + Request.ServerVariables["QUERY_STRING"] %></td> </tr> </table> </body> </html> * *create a snapshot_test.aspx file under the same directory that contains the code from above. *change the rewrite rule to rewrite to .aspx files instead of .html files *And finaly enter the following url in your browser: 'http://example.com/?_escaped_fragment_=/test' For more info on IIS rewrite testing In addition: Use the pretty url for the canonical url and the sitemap.xml. Pretty url: 'http://example.com/#!/test' Ugly url: 'http://example.com/?_escaped_fragment_=/test' A: Try to do: javascript code: var hashchange; function MyHash() { if(window.location.hash) { MyHash = window.location.hash.replace("#!/", ""); $.get("process_page.asp?_escaped_fragment_=" + MyHash, function(data) { $("#content").html(data); }); } } $(document).ready(function() { hashchange(); }); $(window).bind('hashchange', function() { hashchange(); }); HTML code: <div id="content"><!--#include file="process_page.asp"--></div> and in process_page.asp: do something to GET _escaped_fragment_ you can also reference: http://www.gingerhost.com/ajax-demo/ BTW: I am not good at asp. my main language is php. but i did above code and do not need url rewrite
{ "language": "en", "url": "https://stackoverflow.com/questions/7634043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Simply rearrange/rename array (php) I just don't get it, it's actually so basic, but I just can't make it happen. I've got the following array: Array ( [15] => Array ( [id] => 15 [name] => Name of course [date] => 1300863780 [price] => 0 ) [14] => Array ( [id] => 14 [name] => Name of course [date] => 1303545780 [price] => 0 ) ) And I just want to rearrange it a little bit, so it looks like: Array ( [03] => Array ( [id] => Array(15) [name] => Array(Name of course) [day] => Array(23) [year] => Array(2011) [price] => Array(0) ) [04] => Array ( [id] => Array(14) [name] => Array(Name of course) [day] => Array(23) [year] => Array(2011) [price] => Array(0) ) ) To explain it: I want to make the month (calculated from [date]) to be the main key and then more or less list each field in their corresponding fields/some new ones. Later on there will be more entries in the same month, so it makes sense to arrange it that way. What I got yet is the following, and for the sake of foo, I don't understand why it doesn't work that way (and no other way I can come up with). $this->data is the array above! <?php foreach($this->data as $field) { while(list($id, $name, $date, $price) = each($field)) { $month = date('m',$date); $this->month[$month]['id'] = $id; $this->month[$month]['name'] = $name; $this->month[$month]['day'] = date('F',$date); $this->month[$month]['year'] = date('Y',$date); $this->month[$month]['price'] = $price; } } ?> All I get are heaps of 'undefined offset' notices in the line with the list() statement. Much appreciate your help !! A: This should do: $rearranged = array(); foreach ($this->data as $data) { $rearranged[date('m', $data['date'])][] = array( 'id' => array($data['id']), 'name' => array($data['name']), 'day' => array(date('F', $data['date'])), 'year' => array(date('Y', $data['date'])), 'price' => array($data['price']) ); } A: Iterate over the array and change the items accordingly. On the way, collect the new key names and then combine the new array afterwards (Demo): $keys = array(); foreach($array as &$v) { $keys[] = date('m', $v['date']); $v['day'] = date('d', $v['date']); $v['year'] = date('Y', $v['date']); unset($v['date']); foreach($v as &$v2) $v2 = array($v2); unset($v2); } unset($v); $array = array_combine($keys, $array); A: To explain it: I want to make the month (calculated from [date]) to be the main key and then more or less list each field in their corresponding fields/some new ones. Later on there will be more entries in the same month, so it makes sense to arrange it that way. As I wrote in comment, after reading this, I would not store all those id, name etc as arrays. $this->month[$month][$n]['id'] is the way to go, not $this->month[$month]['id'][$n], i.e., you need multiple "arrays of id, name etc" rather than "separate array of id, another array of name etc". function convert(array $data) { $result = array(); foreach ( $data as $value ) { $month = date('m', $value['date']); $value['day' ] = date('d', $value['date']); $value['year'] = date('Y', $value['date']); unset($value['date']); $result[$month][] = $value; } return $result; } $data = array( 15 => array( 'id' => '15', 'name' => 'Name of course', 'date' => '1300863780', 'price' => '0', ), 16 => array( 'id' => '16', 'name' => 'Name of course', 'date' => '1300863780', 'price' => '0', ), 14 => array( 'id' => '14', 'name' => 'Name of course', 'date' => '1303545780', 'price' => '0', ), ); print_r(convert($data)); Output: Array ( [03] => Array ( [0] => Array ( [id] => 15 [name] => Name of course [price] => 0 [day] => 23 [year] => 2011 ) [1] => Array ( [id] => 16 [name] => Name of course [price] => 0 [day] => 23 [year] => 2011 ) ) [04] => Array ( [0] => Array ( [id] => 14 [name] => Name of course [price] => 0 [day] => 23 [year] => 2011 ) ) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7634046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL if statement conditional join I am trying to do something like SELECT * from accounttable, peopletable, companytable WHERE if accounttable.account_type = company JOIN companytable WHERE companytable.id = accounttable.company_id ELSE IF accounttable.account_type = = person JOIN peopletable WHERE peopletable.id = accounttable.person_id I'm sorry its a bit sqlenglish, but I really don't know how to write it out. A: SELECT a.*, p.*, c.* from accounttable a LEFT JOIN peopletable p ON (a.person_id = p.id AND a.account_type = 'person') LEFT JOIN companytable c ON (a.company_id = c.id AND a.account_type = 'company') Note that a,p,c are aliases for the full tablenames, this saves on typing. This query will give all null for either p.* or c.* in a row. You can rewrite the select part like so: SELECT a.id, a.accounttype , COALESCE(p.name, c.name) as name , COALESCE(p.address, c.address) as address .... FROM ..... See: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce A: What about something like: SELECT * from accounttable left join peopletable ON (accounttype = 'person' AND peopletable.id = accounttable.person_id) left join companytable ON (accounttype = 'company' AND companytable.id = accounttable.company_id) I'll join against both tables, so you'll have fields of all three tables in the output. The fields from peopletable will be NULL if accounttype != 'person', and those of companytable will be NULL where accounttype != 'company'. You can find more on the LEFT JOIN syntax in places like here... A: IT MUST BE like below ( as far as i understand ) SELECT a.*,p.*,c.* FROM accounttable a LEFT JOIN companytable c ON c.id = a.company_id AND a.account_type = 'company' LEFT JOIN peopletable p ON p.id = a.person_id AND a.account_type = 'person'
{ "language": "en", "url": "https://stackoverflow.com/questions/7634061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to display iphone version,IOS version,name of the the Network Provider in my app? I am developing an iPhone app. In its about page I want to display the iPhone version, iOS version, and the name of the the Network Provider. I want fetch these from the phone itself. How would I do that? Please Help. Thanks in advance. A: Model Version: NSString *model = [[UIDevice currentDevice] model]; iOS Version: NSString *systemVersion = [[UIDevice currentDevice] systemVersion]; Carrier name (iOS 4.0 minimum): #import <CoreTelephony/CTTelephonyNetworkInfo.h> #import <CoreTelephony/CTCarrier.h> CTTelephonyNetworkInfo *netInfo = [[CTTelephonyNetworkInfo alloc] init]; CTCarrier *carrier = [netInfo subscriberCellularProvider]; NSString *carrierName = [carrier carrierName]; [netInfo release];
{ "language": "en", "url": "https://stackoverflow.com/questions/7634063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating Gif with Image Transitions using c#, ASP.net I have a requirement where I have many images and need to create a slide show with various image transitions and I should be able to save it as a gif file along with image transitions. I am able to create various transitions between the images in C# but not yet found out how to save it as a gif. There is a component NGif which allows to create a gif with multiple images. I tried to save the image at every trasition and then create a gif of all these images but it does not show the transtion effect but shows only the image to be shown next at different transition level with black backgroud. Is there a way to create a gif with transition effects between the images? A: I would aim for a library that creates animated GIF. It either has to be .NET or COM based to easily use. Perhaps something like this project at CodeProject. A: GIF doesn't support transparency with an alpha channel. The only transparency supported is full transparency (not an opacity level like with an alpha channel). You need to designate a palette entry as the transparent color, and then use that palette entry where you want transparency (GIF is always saved with a palette). In animated GIF, the next image is overlaid on the previous one, so transparent areas show the previous image. Alternatively, you could just render the entire new image and not rely on transparency.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to dynamically change jQuery Datatables height I'm using jQuery Datatables. I want to change the height of the table whenever a user resizes the window. I'm able to catch the window resize event which allows me to calculate the new height. How can I assign the new height to the datatable object? A: The current answer didn't work for me (using v 1.9.1). I think this solution not only works but will perform better (and is based on the author's suggestion). This example is using smartresize to solve cross browser window re-size issues. var defaultOptions = {...};//your options var calcDataTableHeight = function() { //TODO: could get crazy here and compute (parent)-(thead+tfoot) var h = Math.floor($(window).height()*55/100); return h + 'px'; }; defaultOptions.sScrollY = calcDataTableHeight(); var oTable = this.dataTable(defaultOptions); $(window).smartresize(function(){ $('div.dataTables_scrollBody').css('height',calcDataTableHeight()); oTable.fnAdjustColumnSizing(); }); A: Using newer versions of Datatables, there's other methods, which, when combined with the judicious use of a timer for watching the resize event triggers, works pretty well. I've left the "ancient" "window.location.reload()" line in for those who are stuck running older versions of DataTables - simply uncomment it and comment out the "table.draw()" call. Side note, the documentation says the correct call is "table.Draw()" - that is not the case on the version I am using (call is all lowercase). $(window).on('resize', function(e) { if (typeof resizeTimer !== 'undefined') { clearTimeout(resizeTimer); } resizeTimer = setTimeout(function() { // Get table context (change "TABLENAME" as required) var table = $('#TABLENAME').DataTable(); // Set new size to height -100px $('.dataTables_scrollBody').css('height', window.innerHeight-100+"px"); // Force table redraw table.draw(); // Only necessary for ancient versions of DataTables - use INSTEAD of table.draw() // window.location.reload(); }, 250); // Timer value for checking resize event start/stop }); That's it. A: For DataTables 1.10: $("#table").DataTable( { scrollY: '250px', scrollCollapse: true, paging: false, }); $('#table').closest('.dataTables_scrollBody').css('max-height', '500px'); $('#table').DataTable().draw(); When you changed CSS you must call draw(). A: You can use the following code: var calcDataTableHeight = function() { return $(window).height() * 55 / 100; }; var oTable = $('#reqAllRequestsTable').dataTable({ "sScrollY": calcDataTableHeight(); }); $(window).resize(function() { var oSettings = oTable.fnSettings(); oSettings.oScroll.sY = calcDataTableHeight(); oTable.fnDraw(); }); A: Simply put it like this: $('#example').dataTable({ "sScrollY": "auto" }); A: This is work for me $(document).ready(function () { $('#dataTable1').dataTable({ "scrollY": 150, "scrollX": 150 }); $('.dataTables_scrollBody').height('650px'); }); A: Here is a simple solution as documented here $(document).ready(function() { $('#example').DataTable( { scrollY: '50vh', scrollCollapse: true, paging: false }); }); vh Relative to 1% of the height of the viewport* You can use the vh unit to set a height that varies based on the size of the window. Supported in: Chrome 20.0+, IE 9.0+, FireFox 19.0+, Safari 6.0+, Opera 20.0+ A: I think you can change the height of the table by css $(window).resize(function(){ $('#yourtable').css('height', '100px'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7634066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How to change received data in Model? I have a typical function in model which is receiving 'time' from table 'Orders': public function get_time() { $result = array(); $result = DB::select('id', 'time', 'description')->from('orders')->execute(); return $result; } The problem is, that 'time' field is stored in MySQL in format (TIME): 'HH:mm:ss', example: 11:45:00. But I don't need seconds, so I can do: date('H:i', strtotime($time)); Doing this in a View isn't good idea. I need to do this conversion in Model or Controller. Of course: $result['time'] = date('H:i', strtotime(result['time'])); won't work ;) A: Doing it in the view is perfect, it's formatting the model result to be displayed correctly. $result['time'] = date('H:i', strtotime(result['time'])); There is a syntax error, you forgot to prefix result with the dollar sign. What zombor said was important too (I missed it) $result is a database result iterator object, not a single result A: Have a look at TIME_FORMAT function: SELECT TIME_FORMAT('11:45:00', '%H:%i') result in 11:45. Change the code like this: $result = DB::select('id', array('TIME_FORMAT("time", '%H:%i')', 'formatted_time'), 'description')->from('orders')->execute();
{ "language": "en", "url": "https://stackoverflow.com/questions/7634069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling a function from a PHP file to another PHP file? I created a file called "page.php" with the below code. <!DOCTYPE HTML> <html> <body> <?php require 'form.php'; ?> <a href="#" onclick="call_popup('form_container')">Click this link!</a> </body> </html> And I created another file "form.php" with the below code: <script type="text/javascript"> function call_popup (container_id) { var id= document.getElementById(container_id); alert(id); } </script> <div id="form_container"> <form> <input type="text" /> <input type="button" value="submit" /> </form> </div> I am trying to call the "call_popup(container_id)" function in "page.php" which is defined in "form.php". When I click the "Click this link!" of the anchor tag it gives an error saying call_popup('form_container') not found! Where did I go wrong? A: Place your JavaScript code in a different file - for example file.js. Include this file in all HTML files you wish to use your code in, in the head section: <!DOCTYPE HTML> <html> <head> <script type="text/javascript" src="file.js"></script> <head> <body> <a href="#" onclick="call_popup('form_container')">Click this link!</a> </body> </html> It's better practice to separate client-side code (JavaScript) from server-side code (PHP). A: You need to add this in the beginning of "page.php": require_once("form.php"); But I am not sure that works with JavaScript functions.. Try create a JavaScript file, "file.js", and reference it in two PHP files: <script src="file.js" type="text/javascript" /> A: Instead of using require 'form.php'; inside the php tags use include () A: I just tested your setup on my local XAMPP and it works (though it's not the best practice to mix JavaScript and HTML code). Are you sure the "require" call works? Do you see the form defined in "form.php" in your browser? Maybe you just get the path to "form.php" wrong and have PHP error messages disabled on the server (not uncommon in a production environment). In that case PHP would die due to a missing file but won't throw any message that something went wrong...
{ "language": "en", "url": "https://stackoverflow.com/questions/7634074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: iOS phonegap plugin : ChildBrowserCommand (pluginName: ChildBrowserCommand) does not exist I am trying to use ChildBrowserPlugin(from https://github.com/purplecabbage/phonegap-plugins) of phonegap 1.0.0 and X-Code 4. but it gives error. Even I have added key : ChildBrowserCommand string : ChildBrowserCommand in PhoneGap.plist 2011-10-03 16:17:06.530 samplePlugins[3913:40b] PGPlugin class ChildBrowserCommand (pluginName: ChildBrowserCommand) does not exist. 2011-10-03 16:17:06.531 samplePlugins[3913:40b] ERROR: Plugin 'ChildBrowserCommand' not found, or is not a PGPlugin. Check your plugin mapping in PhoneGap.plist. Can anyone help me whats is wrong with my setting or code. I put the ChildBrowser.js in www folder index.html <script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script> function onDeviceReady() { var cb = ChildBrowser.install(); if(cb != null) { cb.onLocationChange = function(loc){ root.locChanged(loc); }; cb.onClose = function(){root.onCloseBrowser()}; cb.onOpenExternal = function(){root.onOpenExternal();}; window.plugins.childBrowser.showWebPage("http://google.com"); } } function onLocationChange(loc) { navigator.notification.alert('Change to URL : '+loc); } function onClose() { navigator.notification.alert('onClose :'); } function onOpenExternal() { navigator.notification.alert('onOpenExternal :'); } A: Issue was solved Objective C files was not included properly. I delete the reference of files and re include it.. then works fine... Related post : https://github.com/purplecabbage/phonegap-plugins/issues/35
{ "language": "en", "url": "https://stackoverflow.com/questions/7634077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Local installation of gcc on CentOS I would like to know if it is possible to install gcc as a "local installation" on my home directory? Thanks! I am running CentOS 5.5 and exploring the possibility of installing gcc 4.2.* in my home directory btw. ~Susanth A: try this: yum install gcc If you're going to compile from source you'll also want to have kernel-devel installed... yum install kernel-devel A: Short Ans : You need a sysadmin access if you are installing any app in Linux but there are ways to tweak it like - Using sudo $sudo make install Using a prefix ./configure --prefix=$HOME/install Creating a private RPM database and installing from it (though for gcc I doubt it should work) ref - http://www.nordugrid.org/documents/rpm_for_everybody.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7634079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I filter keyboard number keys I wish to focus a specific Textbox and accept the key press only when the user presses a number key (1,2,3 etc.) otherwise I don't want to focus that Textbox... Senario: I have ListView (having a custom view) in a view. below the list view i have a Textbox. Lets say ListView contains items numbered as 1, 2, 3, 33, 373 etc. Now when I press a number key, lets say Key 3, the following action should occur: * *Focus that Specific TextBox *Append the TextBox text with the number input *Select the item in the ListView with the same number as TextBox.Text has My Xaml for what I tried <ListView Name="lv" Grid.Row="1" ItemsSource="{Binding}" View="{Binding Path=SelectedItem, ElementName=viewComboBox}" DisplayMemberPath="Name" IsTextSearchEnabled="True" TextSearch.TextPath="{Binding Path=Person.Name}"/> <TextBox Grid.Row="2" Text="{Binding Path=TextSearch.Text,ElementName=lv}"></TextBox> Nothing is displayed in the TextBox and I don't know how to handle numeric key press. I need this and its bewildering using MVVM... Any help in this regard would be great. And some guidance using code would be even better... Thanks... A: This logic is specific to view. Its fine if you put it in code behind. MVVM doesn't stop you from writing view specific code in code behind. However if your religiously follow the 'no code behind' approach then you can create a Behavior and put all the code in that. Your behavior will be attached to listbox and will take textbox reference as property. It will listen to keydown event on listbox and add keys to textbox's text property. You shouldn't really be having logic like this in ViewModel A: If you are using MVVM then attached behavior is the way to go ... http://eladm.wordpress.com/2009/04/02/attached-behavior/ * *Name you key press source element like ListView ... <ListView x:Name="MyListView"> .... </ListView> *Declare and define an attached property of type ListView say NumericKeyPressBehavior.FocusTarget *The Source for this FocusTarget will be you MyListView and the behavior will be attached to your TextBox <TextBox local:NumericKeyPressBehavior.FocusTarget="{Binding ElementName=MyListView}" .... /> *In NumericKeyPressBehavior.FocusTarget's dependency property changed event handler, handle the key press on the ListView and then based on if a numeric key was pressed, focus the target TextBox and also append the pressed key character to it. private static void OnFocusTargetChanged( DependencyObject o, DependencyPropertyChangedEventArgs e) { var textBox = o as TextBox; var listView = e.NewValue as ListView; if (textBox != null && listView != null) { listView.KeyUp += (o1, e1) => { var keyChar = GetKeyCharFromKeyCode(e1.Key); if ("0123456789".Contains(keyChar.ToString())) { textBox.Focus(); textBox.Text += keyChar.ToString(); } } } } GetKeyCharFromKeyCode is found here.... C# How to translate virtual keycode to char? Does this help?
{ "language": "en", "url": "https://stackoverflow.com/questions/7634082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: The program created objective c++ is getting crash I am developing a application to get list of installed software in Mac OS X 10.5 or above. The program is created using objective-c++ (c,c++, obj-c). Every time I run the program, it is crashing. int main (int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //My part of coding [pool drain]; // This is the crash prone place return 0; } Here I'm providing project setting details: file extention: .mm compiled as : objective c++ Objc GC : unsupported libraries used : libxml2.2.dylib, Foundation Framework target platfom: x86_x64 development: Mac OS X 10.6.8, Xcode 3.2.6 Application type: console application I don't know any other option need to set to compile objective c++. Any help regarding this would be appreciated. yes. I already set base sdk as 10.5 Here is the log trace: The Debugger has exited with status 0. [Session started at 2011-10-03 22:29:25 +0530.] GNU gdb 6.3.50-20050815 (Apple version gdb-1515) (Sat Jan 15 08:33:48 UTC 2011) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys003 Loading program into debugger… Program loaded. run [Switching to process 2973] Running… Program received signal: “EXC_BAD_ACCESS”. sharedlibrary apply-load-rules all (gdb) I have one more question. Is it valid to release the obj-c object in c++ class destructor? like this myclass::myclasss() { myobjcinterface* myobjc = [[myobjcinterface alloc] init]; } myclass::~myclass() { [myobjc release]; } A: I have one more question. Is it valid to release the obj-c object in c++ class destructor? like this Yes. As for your EXC_BAD_ACCESS, if it's hapening on drain of an autorelease pool, it's almost certain that you have autoreleased something and released it, so the pool is trying to release a dangling pointer. Try setting the environment variable NSZombieEnabled to YES and then running your program. It should give you diagnostics about over-releases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieving information from database (1 field/object; no arrays) I'm doing a sort of login page for my website which I'm just testing right now, and this code is after the login. The thing is, I want to retrieve some information from my database, but the code doesn't work (it doesn't echo anything). I checked that the MySQL query is fine and it works, but there is no result in the PHP. Please I would be happy for any help and answers, //---MySQL connection---// $server = "localhost"; $user = "root"; $pass = "password"; $db = "users"; $table = "users"; mysql_connect($server,$user,$pass) or die(mysql_error()); mysql_select_db($db) or die(mysql_error()); //----------------------// //---MySQL query, data selection---// $sesuser = $_SESSION['username']; $sql = "SELECT data FROM $table WHERE username='$sesuser'"; $predata = mysql_query($sql); $data = mysql_fetch_field($predata); //---------------------------------// //---Check if session is registered---// session_start(); if(session_is_registered("username")){ echo "\n"."Hello ".$_SESSION["username"]."<br />"; echo $data; //!!this line doesn't work } else{ echo "<script>window.location=/login/</script>"; } //------------------------------------// ?> A: put session_start() at the top or just before you use $_SESSION variable one more thing : The function session_is_registered has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. better way session_start(); //---MySQL query, data selection---// $sesuser = mysql_real_escape_string($_SESSION['username']); $sql = "SELECT data FROM $table WHERE username='$sesuser'"; $predata = mysql_query($sql); $data = mysql_fetch_field($predata); //---------------------------------// //---Check if session is registered---// if(isset($_SESSION['username'])){ echo "\n"."Hello ".htmlentities($_SESSION["username"])."<br />"; echo $data; } else{ header("Location :"login.php"); exit(); } A: var_dump($data); - What is says? And YES, but session_start at begining of file; And try(via php): $i = 0; while ($i < mysql_num_fields($result)) { echo "Information for column $i:<br />\n"; $meta = mysql_fetch_field($result, $i); if (!$meta) { echo "No information available<br />\n"; } echo "<pre> blob: $meta->blob max_length: $meta->max_length multiple_key: $meta->multiple_key name: $meta->name not_null: $meta->not_null numeric: $meta->numeric primary_key: $meta->primary_key table: $meta->table type: $meta->type unique_key: $meta->unique_key unsigned: $meta->unsigned zerofill: $meta->zerofill </pre>"; $i++; } And if you change mysql_fetch_field to mysql_fetch_row you would be able to reach your data over: $data[0]; A: Basically there is an object returned in $data and you can echo it like $data->name
{ "language": "en", "url": "https://stackoverflow.com/questions/7634091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Iterating over a list of Strings in C++, what's going wrong? I'm trying to print out a list of strings thus: std::list<String> const &prms = (*iter)->getParams(); std::list<String>::const_iterator i; for(i = prms.begin(); i != prms.end(); ++i){ log.debug(" Param: %s",*i); } But my program crashes saying Illegal Instruction. What am I doing wrong? A: *i is a String, not a char *. If log.debug() is a function of the printf family, you want a zero-terminated string. Depending on how your String class is implemented you might have a function that returns a const char *. For example with std::string that function is c_str: for(std::list<std::string>::const_iterator i = my_list.begin(); i != my_list.end(); ++i) { printf("%s\n", i->c_str()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Webservice calling EJB creates SSL exception I have a JAX-WS webservice which makes calls to a remote EJB on the same server. Everything runs on Glassfish 3.1.1, and the apps are deployed EARs – one for the webservice, another for the EJB. This works fine locally, but when deploying to a test server, I get typical exceptions about untrusted (self-signed) SSL certificates. Here's a relevant excerpt: Caused by: com.sun.xml.ws.client.ClientTransportException: HTTP transport error: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at com.sun.xml.ws.transport.http.client.HttpClientTransport.getOutput(HttpClientTransport.java:132) The exception occurs exactly on the line in the webservice where the EJB call is being made. It puzzles me because I wouldn't expect anything to do with HTTPS at that point. The most promising angle so far is that this has to do with transaction coordination, as described here, which is supposed to use HTTPS by default. However, setting com.sun.xml.ws.tx.preferredScheme=http has no effect on the problem. Any suggestion is much appreciated. A: This is because the client does not know which truststore it should use - so therefore it does not trust the service and the SSL handshake fails. Run the 'client' with the following VMargs: -Djavax.net.ssl.trustStore=${truststore.location} -Djavax.net.ssl.trustStorePassword=${ssl.password} If you use NetBeans it can be set at project properties.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Codeigniter modifying session data I store few data in session as the following: $session_data = array("uid" => "test user", "loged_in" => true); $this->session->set_userdata($session_data); To modify the "uid" I tried $uid = array("uid" => "New user"); $this->session->set_userdata($uid); It did not work so I tried $this->session->set_userdata("uid","New user"); It also did not work. Cant find any useful stuff on google. Please help how can I change values in the session?? A: Aside from all your typos (of course those matter in programming), you might want to see if you are just confusing yourself and typo'ing the array/value/key name incorrectly: Do the following: echo "<pre>"; print_r($this->session->all_userdata()); echo "</pre>"; and after doing that you will be one step closer to knowing what typo's or problems you ran into as that will display your session array: Array ( [session_id] => 4a5a5dca22728fb0a84364eeb405b601 [ip_address] => 127.0.0.1 [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; [last_activity] => 1303142623 [uid] => 2 etc... ) A: Did you load your session library? $this->load->library('session'); It might be a dumb question but it does not hurt to ask. What about setting your encryption key? I imagine you would see an error message for that https://www.codeigniter.com/user_guide/libraries/encryption.html $session_data = array('uid' => 'test user', 'logged_in' => TRUE); $this->session->set_userdata($session_data); // modify session $this->session->set_userdata('uid', 'New user'); A: ///set session data $data = array('Id' => 'test Id', 'is_logged_in' => TRUE); $this->session->set_userdata($data); // modify session data $this->session->set_userdata('Id', 'New test Id');
{ "language": "en", "url": "https://stackoverflow.com/questions/7634098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: System Error 955 when using resolver::async_resolve At times I get the System Error 995 when using the async_resolve method from an tcp::resolver. The code below shows the relevant code lines. #include <boost/bind.hpp> #include <boost/asio.hpp> #include <iostream> class connection { public: connection(boost::asio::io_service& io_service) : m_resolver(io_service), m_socket(io_service) { } void async_connect( std::string const& host, std::string const& service, boost::asio::ip::tcp::socket::protocol_type tcp = boost::asio::ip::tcp::v4() ) { m_resolver.async_resolve( boost::asio::ip::tcp::resolver::query(tcp, host, service), boost::bind( &connection::resolve_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator ) ); } protected: virtual void on_connected(boost::system::error_code const& connect_error) { if (!connect_error) { std::cout << "Connection established. Endpoint: " << m_socket.remote_endpoint() << std::endl; } else std::cout << "error: " << connect_error << std::endl; } private: void connect_handler(boost::system::error_code const& connect_error) { on_connected(connect_error); } void resolve_handler( boost::system::error_code const& resolve_error, boost::asio::ip::tcp::resolver::iterator endpoint_iterator ) { if (!resolve_error) { m_socket.async_connect( *endpoint_iterator, boost::bind( &connection::connect_handler, this, boost::asio::placeholders::error ) ); } } private: boost::asio::ip::tcp::socket m_socket; boost::asio::ip::tcp::resolver m_resolver; }; int main() { boost::asio::io_service io_service; connection foo(io_service); foo.async_connect("www.google.de", "http"); io_service.run(); return 0; } 995 (0x3E3) - ERROR_OPERATION_ABORTED means: The I/O operation has been aborted because of either a thread exit or an application request. But I have no idea why. I think something goes out of scope but I don't know what exactly. Hope you can help me. Thanks in advance! A: Sometimes we're blind to the most obvious. This is how the main-function should look like: int main() { boost::asio::io_service io_service; connection conn(io_service); // Perhaps we should actually declare the object if conn.async_connect("www.google.de", "http"); // we want to use it beyond this line ... io_service.run(); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't PHP recognise when the date given is after today's date? I want to compare two dates in PHP. One date is the date due, which is provided by the user, stored in a database and retrieved with PHP. The second is today's date. $unixdue = strtotime($query['date_due']); //Converts the database integer to Unix date $duestamp = date("dmY", $unixdue); //Converts the Unix date to dd-mm-yyyy //If the due date is larger than today (i.e., after today), it's early. if ($query['complete'] == 0 AND date("dmY") < $duestamp) {echo "Early";} //If the due date is smaller than today (i.e., before today), it's late. elseif ($query['complete'] == 0 AND date("dmY") > $duestamp) {echo "Late";} //If the due date IS today, it's today. elseif ($query['complete'] == 0 AND date("dmY") == $duestamp) {echo "Today";} It works with dates that are today, but all the others return "Early" even if they are not early. Due to this I can't even tell if the rest is working at all. I have tried comparing two Unix dates, but they include the time as well, when really I only want the date. If I compare two unix dates, I can't say if something is "Today". A: You can't compare whether two strings are less than or greater than each other. Or you can, but in this case you shouldn't because the results are not what you want ("03092011" < "29082011" for example). You can first compare if the dates are equal as you have done; if they are not, you can compare the timestamps. Even though you use only dates it doesn't matter because the timestamp of an earlier date is always smaller than the timestamp of a later date, regardless of the time part. if( $query['complete'] == 0 ) { if( date("dmY") == $duestamp ) { echo "Today"; } elseif( time() < $unixdue ) { echo "Early"; } elseif( time() > $unixdue ) { echo "Late"; } } A: You are comparing in a wrong way. A possible solution would be using date('Ymd') but even better is using timestamps as time() and the $unixdue A: Use the time function: $msg = "Late"; if( $unixdue > time() ){ $msg = "Early"; } if(date("dmY") === $duestamp){ $msg = "Today"; } Here is where it is documented. A: you have overcomplicated your code by introducing unix timestamp, absolutely unnecessarily and and it seems you have to move completeness check into SQL query. So if ($query['date_due'] > date("Y-m-d")) echo "Early"; elseif ($query['date_due'] < date("Y-m-d")) echo "Late"; else echo "Today"; and I believe you can move this condition into query too
{ "language": "en", "url": "https://stackoverflow.com/questions/7634108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to use the XML result of SolrNet in my ASP.NET code behind I found http://code.google.com/p/solrnet/wiki/Stats link. But I cannot understand it properly. I want to use a (min,max) kind of function with a Solr query. My query (display min, max and average price of Round shape and color D and clarity FL and caratweight. (This query will be generated based on user's selection dynamically.) (Shape:"Round") AND (Color:"D") AND (Clarity:"FL") AND (CaratWeight:[1 TO 10]) But how can I use such kind of function and select specific column? Now I am somewhat nearer... By using the following URL, I am getting min, max, count and mean.. Things like those I want. But it's in XML format. Now I want to customize. I want to use this result in my ASP.NET code behind and want to do further computation. http://localhost:8983/solr/coreMikisa/select/?q=%3A&version=2.2&start=0&rows=10&indent=on&stats=true&stats.field=Price What should I do? A: Load the XML result into XML document and use XPath to access get the value of desired elements. var xmlDocument = new XmlDocument(); xmlDocument.Load(solrXmlResult); var mean = double.Parse(xmlDocument.DocumentElement.GetElementByTagName("//mean")[0].InnerText); ... or based on your XML var mean = double.Parse( xmlDocument.DocumentElement.GetElementByTagName( "//lst[@name=\"tag\"]/double[@name=\"min\"]" )[0].InnerText);
{ "language": "en", "url": "https://stackoverflow.com/questions/7634109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make JLabel background transparent again I have a JLabel that changes its background color when the mouse enters it. The problem I have is that I want the JLabel to become transparent after the mouse exits. Is there a statement I can use to accomplish this? A: JLabel is by default transparent and non-opaque, if you want to change background on mouse exit, then you have to: * *setBackground() for both states, enter and exit *change to JPanel or another JComponent A: It's a lazy holiday here in Germany, so combining the two answers: final JLabel label = new JLabel("some label with a nice text"); label.setBackground(Color.YELLOW); MouseAdapter adapter = new MouseAdapter() { /** * @inherited <p> */ @Override public void mouseEntered(MouseEvent e) { label.setOpaque(true); label.repaint(); } /** * @inherited <p> */ @Override public void mouseExited(MouseEvent e) { label.setOpaque(false); label.repaint(); } }; label.addMouseListener(adapter); The problem (actually, I tend to regard it as a bug) is that setting the opaque property doesn't trigger a repaint as would be appropriate. JComponent fires a change event, but seems like nobody is listening: public void setOpaque(boolean isOpaque) { boolean oldValue = getFlag(IS_OPAQUE); setFlag(IS_OPAQUE, isOpaque); setFlag(OPAQUE_SET, true); firePropertyChange("opaque", oldValue, isOpaque); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is it possible to get data from web response in a right encoding using (WebResponse response = webRequest.GetResponse()) { using (var reader = new StreamReader(response.GetResponseStream())) { string tmpStreamData = string.Empty; while (!reader.EndOfStream) { while (reader.Peek() > -1) { tmpStreamData += (char)reader.Read(); } } MessageBox.Show(tmpStreamData); } } Sometimes I get � symbols in the "tmpStreamData". Is it possible to avoid such situations and get data in the readable format? A: // Get HTTP response. If this is not an HTTP response, you need to know the encoding yourself. using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse()) { // If not an HTTP response, then response.CharacterSet must be replaced by a predefined encoding, e.g. UTF-8. using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet))) { // Read whole stream to string. string tmpStreamData = reader.ReadToEnd(); MessageBox.Show(tmpStreamData); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7634113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android different versions compatibility I have developed an application for android 2.3. Now I want to test it under android 2.1. Do I have to create a new project with target set to android 2.1 and copy all the code across or is there any other method? Also how to make this application compatible with different android versions as a single program? A: Take a look at the documentation on specifying your target version You'll see that android has a special meaning to the word "target". But generally you can run your app on any device running android >= minSdkVersion and <= maxSdkVersion But there's no reason you can't test out your application on any version of android greater than the android:minSdkVersion you specify. To do so, just create an AVD (android virtual device) with Android 2.1 (you'll need to install version 2.1 of the SDK to do so) and launch into it. Otherwise if you've got a physical device running 2.1 you're already set to try it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: asp.net wizard control to create registration from Sir Am New to Asp.net What is Asp.net Wizard Control and how it is use to create the registration as steps please any one help me i want complete details of wizard control and how to develop registration from using wizard and how to store data from Wizard to SqlServer 2005 please help me...... A: Have a look at the following post: https://web.archive.org/web/20211020103243/https://www.4guysfromrolla.com/articles/070506-1.aspx It will give you a clear idea about how the createuserwizard works and its relation with the database by using asp.net membership. Hope this helps! A: This post from Scott Gu has several useful links regarding this topic; in particular, a link to a video demonstrating exactly what you are trying to accomplish.
{ "language": "en", "url": "https://stackoverflow.com/questions/7634117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }