text
stringlengths
8
267k
meta
dict
Q: What's the best way to implement an application server for smartphone app? I intend to write a multi platform smartphone app (currently only I-phone and android). Which has to send and recieve information from a web server I intend to create. The web server will do all the algorithms, and handles also DB connection. My question, is how is this best accomplished, which kind of web-server technology fit best the scenario, and supports connections from various devices. Basically, I thought about implementing a simple TCP/IP protocol, making the app (on the phone) the client, and server on the web on the other side. however, I want to deploy the application to an application server (maybe google app, JBOSS, etc.) and I don't want to be stopped by various firewalls. does anyone has an idea ? edit: few things are certain, the application server will be written in java, and db will be mysql. A: This is a very broad question and any suggestion about which backend technology to use will depend on your language preferences, your other requirements, etc. For starters, I'd suggest JSON over HTTP as a transport mechanism: it's easy to parse on both client and server-side, and it's directly usable in Javascript should the need arise. XML is another choice, but it can be annoying to parse. JSON-over-HTTP (or XML) will be completely device agnostic and won't have the firewall/proxy problems you'll run into trying to do a custom-implemented TCP-based protocol. For the backend, may folks use MySQL or Postgres for their database, and connect to it from Java, C#, Ruby, PHP, or other server-side languages. Use what you're comfortable with or what you want to learn next. A: Why not write the server-side as a regular web application - in whatever technology you like (php, asp.net, java)? This way you can deploy the app on any web server and your client apps on the phones would simply establish a connection to an HTTP server. Normally, firewalls would not be a problem in such situation. I have used this setup for my apps (both android and iphone) - connecting to a web server app written in php with postgres back-end.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Applying textures to a vertex buffer object primitive How do you apply textures to a vertex buffer object in Android? ANSWER: The code works fine, except it is missing a call to glEnable(GL_TEXTURE_2D); This and the call of glEnableClientState(GL_TEXTURE_COORD_ARRAY); are both required for in order for vertex buffer object to draw texture. QUESTION: From what I know, first you must create a NIO Buffer: ByteBuffer tbb = ByteBuffer.allocateDirect(texCoords.length * 4); tbb.order(ByteOrder.nativeOrder()); FloatBuffer textureBuffer = tbb.asFloatBuffer(); textureBuffer.put(texCoords); textureBuffer.position(0); In this code sample, the array texCoords contains the 2-component (s, t) texture data. After creating the NIO Buffer, you need to pass it to opengl and create Vertex Buffer Object: int[] id = new int[1];//stores the generated ID. gl11.glGenBuffers(1, id, 0); gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, id[0]); gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoords.length * 4, textureBuffer, GL11.GL_STATIC_DRAW); So that takes care of all the initalization. Next we need to draw it, and we do so like this: gl11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);//enable for textures gl11.glActiveTexture(GL11.GL_TEXTURE0); //lets pretend we created our texture elsewheres and we have an ID to represent it. gl11.glBindTexture(GL11.GL_TEXTURE_2D, textureId); //Now we bind the VBO and point to the buffer. gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, id[0])//the id generated earlier. gl11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);//this points to the bound buffer //Lets also pretend we have our Vertex and Index buffers specified. //and they are bound/drawn correctly. So even though this is what I would think would be needed in order for OpenGL to draw the texture, I have an error, and only a red triangle (without my modulated stone texture) renders. A: Both functions for VBO's need to be called to enable textures. gl.glEnable(GL11.GL_TEXTURE_2D); gl.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
{ "language": "en", "url": "https://stackoverflow.com/questions/7628809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iScroll sensitivity Im using the latest iscroll script for a site viewed on an ipad. It works but you have to pressed down and scroll slowly for it to scroll properly. Is there anything I can change in the iscroll script or settings that would allow for better sensitivity to the touch and the scrolling itself is faster? A: It is a bit hard to really suggest the solution. But here are some pointers. Attach the global touchmove event (and prevent defaultbehavior). document.attachEvent('touchmove', function(e) { e.preventDefault(); }, false); Keep the html elements inside the scroller to a minimum. You can add -webkit-transform: translate3d(0,0,0) to force the elements through the hardware acceleraion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading jScrollPane after initializing Facebook Comments - how? Is there an "onComplete" state or similar for the Facebook Comments plugin? I'm trying to add a jScrollPane scrollbar to a content box that has FB Comments inside it. What happens is I get the FB Comments iframe placed on top of the box's content (as if it had an absolute position / was floating. Guessing this has to do with FB Comments initializing after jScrollPane. Edit: Now what I'm really after is combining ColorBox, Facebook Comments and jScrollPane and the headache starts pretty soon: $('.mybox').colorbox({ innerWidth: 640, innerHeight: 480, scrolling: false, onComplete: function() { $('#cboxLoadedContent').jScrollPane({ // Init FB Comments here instead? Then call jScrollPane? showArrows: true, scrollbarWidth: 15, scrollbarMargin: 0 }); }, onClosed: function() { // What would happen here if I need to listen for FB Comments also? $('#cboxContent').jScrollPaneRemove(); } }); Sorry if my question is a bit unclear, it's late and I've been in front of a screen for 10+ hours. A: Using the xfbml.render event: FB.Event.subscribe('xfbml.render', function() { console.log('Loaded!'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7628819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Defensive code for controlling a service I'm trying to revamp my multi-activity app to use just once instance of a LocationListener which I intend to implement in a service. Prior to doing this I've been experimenting with a stub activity and a stub service to see what happens under error conditions. I want to see what happens if I attempt to unbind from a service which has already been unbound and avoid any errors if this should happen. The activity has two buttons to bind/unbind. If I deliberately hit the unbind twice in succession I do get a runtime error. What condition can I test for at the point marked '<<<<<' in the code below to skip calling unbind again? My activity code is public void myClickHandler(View target) { switch (target.getId()) { case R.id.bind: Log.d("STAG", "Activity One pressed BIND button"); mServiceConnected = bindService(new Intent( "com.nbt.servicetest.LOCATIONSERVICE"), mServconn, Context.BIND_AUTO_CREATE); break; case R.id.unbind: Log.d("STAG", "Activity One pressed UNBIND button"); try{ if (mServconn != null) // <<<< What to put here if already unbound? unbindService(mServconn);} catch(Exception e){ Log.d("STAG", "Exception " + e.getMessage()); } break; } } ServiceConnection mServconn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d("STAG", "Activity One service connected"); mIbinder = service; } @Override public void onServiceDisconnected(ComponentName name) { Log.d("STAG", "Activity One service disconnected"); } }; The service is starting/stopping OK. I've put log lines in the service code with the same tag on all the pertinent lines. The output is : STAG(2945): Activity One onCreate STAG(2945): Activity One onStart STAG(2945): Activity One onResume STAG(2945): Activity One pressed BIND button STAG(2945): Loc service ONCREATE STAG(2945): Loc service ONBIND STAG(2945): Activity One service connected STAG(2945): Activity One pressed UNBIND button STAG(2945): Loc service ONUNBIND STAG(2945): Loc service ONDESTROY STAG(2945): Activity One pressed UNBIND button STAG(2945): Exception Service not registered: com.nbt.servicetest.ServiceTesterActivityOne$1@43b8b290 I note that the activity's onServiceDisconnected() never gets called, is this normal? A: The simplest thing to do would be to introduce another variable, say, isServConnBound, and add checks on both bind and unbind actions. Of course, remember to update the variable after you call bindService and unbindService. A: I agree with vhallac - just use boolean flags. What are your concerns with this approach? As for me there's nothing to be afraid of. As to why "the activity's onServiceDisconnected() never gets called" - yes, this is normal. Look what API says on this callback: Called when a connection to the Service has been lost. This typically happens when the process hosting the service has crashed or been killed. Your process has neither crashed nor been killed, so this is an expected behavior. Even more, since you have your service in the same process, you'll never get this called. This is important when you bind to a service that runs in another process (inter process communication).
{ "language": "en", "url": "https://stackoverflow.com/questions/7628820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using ViewBinder for a custom ListView item with TextView I'm trying to add a background color for an TextView on my ListView using a SimpleCursorAdapter with ViewBinder, but it doesn't work: listrow.xml: <TextView android:id="@+id/catcolor" android:layout_width="4dp" android:layout_height="match_parent" android:layout_margin="4dp" android:background="#FF0099FF" /> <LinearLayout android:paddingTop="4dp" android:paddingRight="4dp" android:paddingLeft="4dp" android:paddingBottom="2dp"> <TextView android:id="@+id/title" android:text="{title}" android:textSize="@dimen/text_size_medium" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="10" android:textStyle="bold" /> </LinearLayout> Activity where I call the ViewBinder(class TextActivity extends ListActivity) private void fillData() { Cursor notesCursor = mDbHelper.fetchAllNotes(); startManagingCursor(notesCursor); String[] from = new String[]{ NoteAdapter.KEY_CATID, NoteAdapter.KEY_TITLE, NoteAdapter.KEY_CONTENT }; int[] to = new int[]{ R.id.catcolor, R.id.title, R.id.content }; SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.noterow, notesCursor, from, to); notes.setViewBinder(new ViewBinder()); setListAdapter(notes); } private class ViewBinder implements SimpleCursorAdapter.ViewBinder { public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); switch(viewId) { case R.id.catcolor: ImageView catcolor = (ImageView) view; int catColor = cursor.getInt(columnIndex); switch(catColor) { case 0: catcolor.setBackgroundColor(R.color.catcolor1); break; case 1: catcolor.setBackgroundColor(R.color.catcolor2); break; case 2: catcolor.setBackgroundColor(R.color.catcolor3); break; } break; } return false; } } What am I doing wrong? A: In setViewValue(), you have to return true once you've set the value wanted for the specified view. Check out the documentation for more info. Here's what I'm thinking of for your code: public boolean setViewValue(View view, Cursor cursor, int columnIndex) { int viewId = view.getId(); switch(viewId) { case R.id.catcolor: ImageView catcolor = (ImageView) view; int catColor = cursor.getInt(columnIndex); switch(catColor) { case 0: catcolor.setBackgroundColor(R.color.catcolor1); return true; break; case 1: catcolor.setBackgroundColor(R.color.catcolor2); return true; break; case 2: catcolor.setBackgroundColor(R.color.catcolor3); return true; break; } break; } return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving the opened file in particular folder I have a dropdownlist and a textbox. When i write some name and select some options in dropdownlist like word or excel or powerpoint, that particular file opens as an attachment and i should save it in "data" folder which is already present in the solution explorer. My code is like this string file = TextBox1.Text; if (dd1.SelectedIndex == 1) { Response.ContentType = "application/word"; Response.AddHeader("content-disposition", "attachment;filename =" + file + ".docx"); } How can I store this file in "data" folder? A: The simple answer is "you cannot". Saving file is taking place on the client side. Your web application knows nothing about the client machine (not even whether it's a real browser or another script) and has no control over the client. The end user will have to manually select data folder to save the file to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Animating a series of images using blocks in iOS 4 I'm relatively new to iOS and I want to animate an UIImageview through a series of images. I would usually do this with code like this: UIImageView *planetView = // get view I want to animate // [planetView setAnimationImages: [NSArray arrayWithObjects:image1, image2, image3, image4, image5, image6, nil]]; [planetView setAnimationDuration:0.65]; [planetView setAnimationRepeatCount:1]; [planetView startAnimating]; However I want to start using blocks properly for this and so far I'm stumped. I also need to remove the planetView from the superview after its done its animation. I thought of using "transitionFromView" but that only goes from one view to a second, not a series of them. Any help would appreciated. A: There are no block-using methods for this. I think you're confusing UIImageView animations (much like animated GIFs) with UIView animations in general. As for removing it from display, there are no callbacks AFAIK. You can try using an NSTimer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript page repaint halted during touchmove event I have an element that is moved (via altering it's leftmargin) relative to a user touch on a mobile device (i.e. dragging it around the screen with your finger). I have noticed that during a touchmove event (which i believe fires repeatedly for the entire time between touchstart and touchend), the browser does not repaint the window, meaning that the display is not updated until after the user takes their finger off the screen. I haven't had the opportunity to test this across various devices, so it could only relate to Android devices, or to webkit, or a wider group. Has anybody come accross this and might there be a workaround to force the browser to redraw during the events duration? A: Call event.preventDefault() on the touchstart event. http://uihacker.blogspot.tw/2011/01/android-touchmove-event-bug.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7628828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I write into Google Chrome Url Address bar using an extention ? Can I create a Google chrome extension to change the URL of Google Chrome URL address bar? Example : If I wrote in the address bar شةثقثىشغشزؤؤخة by wrong, it detects the letters and convert them into English letter to to : amerenaya.com A: You can listen to changes in the URL's of the tab using the onUpdated event then you need to determine if there is a litteral keyboard translation and then reload the tab using the update method, unfortunately this will cause the page to reload, but it gets you partially to your solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How Can I Get Context Sensitive He-lp in Delphi to Use Symbolic Names instead of HelpID Aliases? I'm building my help system into my program, and I'm working on my context sensitive help which should bring up the appropriate help page for the active control when F1 is pushed. On each control, I can set HelpType to htContext and HelpContext to the HelpID, or I can set HelpType to htKeyword and HelpContext to the HelpID Alias. But in my help system (Dr. Explain), I have set up symbolic names (i.e. some text that is used as a bookmark in my help system). This is different than the HelpID and its alias, and is accessible from the Help system with the call: Application.HelpJump(SymbolicName). I would like to use the HelpContext field for my symbolic names which is much simpler and easier to maintain than creating a duplicate set of HelpID Aliases. And I won't have to worry about creating the Help map file or have to deal with it. It is the HelpKeyword routine, in the Forms unit, that processes the F1 when when HelpType is htKeyword: function TApplication.HelpKeyword(const Keyword: string): Boolean; var CallHelp: Boolean; begin {$IF DEFINED(CLR)} Result := DoOnHelp(HELP_COMMAND, TObject(Keyword), CallHelp); {$ELSE} Result := DoOnHelp(HELP_COMMAND, Integer(PChar(Keyword)), CallHelp); {$IFEND} if CallHelp then begin if ValidateHelpSystem then begin { We have to asume ShowHelp worked } Result := True; HelpSystem.ShowHelp(Keyword, GetCurrentHelpFile); end else Result := False; end; end; To get this to work to process my symbolic names, all I really have to do is replace the routine with: function TApplication.HelpKeyword(const Keyword: string): Boolean; begin Application.HelpJump(Keyword); Result := true; end; What I can't seem to do is figure out how to write the proper code to customize the functionality of this routine in a clean way, without having to hack the Forms unit itself. How can I do this? Or alternatively, is there another way to easily get the context sensitive help to access my help page based on the symbolic name? For reference, I'm using Delphi 2009 (but will be upgrading to XE2 in the next month or so). p.s. The word in the title is "He-lp" because stackoverflow won't let me put the word "Help" in the title. A: Try this in your OnHelp event handler (of your form, or of the global Application, depending on what you're using): function TForm1.FormHelp(Command: Word; Data: Integer; var CallHelp: Boolean): Boolean; begin if Command = HELP_COMMAND then begin // avoid default processing CallHelp := False; // do your own processing - in this case, do what Application.HelpJump would do Application.HelpSystem.ShowTopicHelp(PChar(Data), Application.CurrentHelpFile); // assume it worked Result := True; end; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7628832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Stop app window overlapping Windows start bar On my Win7 PC I have the start-bar running vertically, it's about 60px wide. In my win32 application, the created window always appears overlapping the start bar, which looks bad - I just use (0,0) as the top-left position for the window. How should I be doing it to get (0,0) relative to the desktop, taking the Start Bar into account? Is there a flag, or do I manually need to look up a metric? A: Use SetWindowPlacement. The (0,0) for that function excludes the taskbar and any other appbars. A: There are a few problems here. You don't want to use a hard-coded value like (0,0). That might not even be visible on a multi-monitor system. As you have discovered, you should try to avoid overlapping with the taskbar or other appbars. If there are multiple monitors you should try and start on the monitor where the user has most recently interacted. There is a simple way to make much of this happen for free. Pass CW_USEDEFAULT as the x and y coordinates when you call CreateWindow. This will let the window manager do the hard work of making your window appear in a sensible location. You can get the system to tell you the coordinates of the work area. The work area is that part of the desktop that does not contain the taskbar or other appbars. Call SystemParametersInfo passing SPI_GETWORKAREA. Retrieves the size of the work area on the primary display monitor. The work area is the portion of the screen not obscured by the system taskbar or by application desktop toolbars. The pvParam parameter must point to a RECT structure that receives the coordinates of the work area, expressed in virtual screen coordinates. To get the work area of a monitor other than the primary display monitor, call the GetMonitorInfo function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I implement MVVM with WCF? I'm new to MVVM. Currently I'm developing a WPF project in C# that will have a SQl Server backend and I'll be using a standard WCF service to communicate with it. All the tutorials I've seen on MVVM thus far always seem to use some static data repository such as an xml file for their backend. I haven't yet seen implemenations using a database and a data access layer, so I'm confused as to where my WCF service fits in. The service has all data objects defined in it, so does the service itself then become the model? In addition, how do I go about including the service in the ViewModel so that the designer doesn't throw an error stating that it cannot create an instance f the service class? Any help here would be greatly appreciated as I find it strange that so many tutorials on this subject omit the most prctical implementation for a line-of-business application. PS I would like to steer clear of WCF RIA services and Silverlight as the Silverlight's lack of support for commands makes the book I'm following (Pro WPF and Silverlight MVVM Effective Application Development with Model-View-ViewModel) difficult to understand. A: OK, I'll try to get you up to speed ... First, I do recognize the question about the model and the object model exposed with WCF. Are they the same? Well, I would like to make that assumption currently, for sake of simplicity. So then we do not need the model part of MVVM on the client side? Depends ... The ViewModel is in the driving seat. We let it create the client proxy to your WCF service. The objects used in the request and returned as result makes your model. Anything you want to cache on the client side or is not directly bindable with the UI will be put in properties in your model container class. Generate bindable properties from these model properties for consumption in your UI. Every else will just be direct properties in your view model. About WCF and the data access layer, there are a few important thing to recognize. First of all, you will need to have a seperation between you logical (information) model and your physical (database) model. One reason is to abstract your database technology away from your application. Another to allow small deviations between your application / domain logic and your physical implementation. Make sure your (entity) model classes are generic enough to support changes in your UI without having to modify the complete application stack for every UI change. It is hard to talk about this matter without a clear example, so to wrap up I would like to invite you to look at http://aviadezra.blogspot.com/2010/10/silverlight-mvvm-odata-wcf-data.html. I know, it IS using WCF data services and SilverLight. Don't be mad at me directly for directing to this sample and give me the thumb down. It is just such a damn good example of what you want to achieve and what to introduce and what to think about setting up such an application. Just replace Silverlight by WPF and Data Services by regular typed data contracts and the rest of the story will help to get your thoughts clear. Hope it helps you in your quest!
{ "language": "en", "url": "https://stackoverflow.com/questions/7628844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: DotNetOpenAuth WebConsumer with Google Apps domain How can I set the WebConsumer object to utilise the domain-level authorization ? I need this for saving the access token. I can do this with the OpenIdRelyingParty class, by calling CreateRequest(domain), but could not find a way to obtain the access token this way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to see if two shapes overlap I'm trying to write a simple firemonkey test app. I have a form, with a panel (align:= alClient). On the form are 2 TCircle's. I have set TCircle.Dragmode:= dmAutomatic. I would like to drag the circles around and have something happen when the circles overlap. The question is: I don't see any method in TCircle called overlap, nor do I see an event called on overlap. I've tried all the xxxxDrag events, but that does not help me with the hittesting. How can I see when a shape being dragged overlaps with another shape ? I was expecting one of the DragOver, DragEnter events to detect this for me, but that does not seem to be the case. Surely there must be some standard method for this in Firemonkey? For now the pas file just looks like: implementation {$R *.fmx} procedure TForm8.Circle1DragEnter(Sender: TObject; const Data: TDragObject; const Point: TPointF); begin if Data.Source = Circle1 then Button1.Text:= 'DragEnter'; end; procedure TForm8.Circle1DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Accept: Boolean); begin if (Data.Source = Circle2) then Button1.Text:= 'Circle2 drag'; end; procedure TForm8.Circle2DragEnd(Sender: TObject); begin Button1.Text:= 'DragEnd'; end; procedure TForm8.Circle2DragEnter(Sender: TObject; const Data: TDragObject; const Point: TPointF); begin Button1.Text:= 'DragEnter'; end; procedure TForm8.Circle2DragLeave(Sender: TObject); begin Button1.Text:= 'DragLeave'; end; procedure TForm8.Circle2DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Accept: Boolean); begin if Data.Source = Circle2 then begin Button1.Text:= 'DragOver'; Accept:= true; end; end; The dfm looks something like this: object Form8: TForm8 Left = 0 Top = 0 BiDiMode = bdLeftToRight Caption = 'Form8' ClientHeight = 603 ClientWidth = 821 Transparency = False Visible = False StyleLookup = 'backgroundstyle' object Panel1: TPanel Align = alClient Width = 821.000000000000000000 Height = 603.000000000000000000 TabOrder = 1 object Button1: TButton Position.Point = '(16,16)' Width = 80.000000000000000000 Height = 22.000000000000000000 TabOrder = 1 StaysPressed = False IsPressed = False Text = 'Button1' end object Circle1: TCircle DragMode = dmAutomatic Position.Point = '(248,120)' Width = 97.000000000000000000 Height = 105.000000000000000000 OnDragEnter = Circle1DragEnter OnDragOver = Circle1DragOver end object Circle2: TCircle DragMode = dmAutomatic Position.Point = '(168,280)' Width = 81.000000000000000000 Height = 65.000000000000000000 OnDragEnter = Circle2DragEnter OnDragLeave = Circle2DragLeave OnDragOver = Circle2DragOver OnDragEnd = Circle2DragEnd end end end A: The general problem is difficult and known as collision detection - you can google the term to find the related algorithms. The particular case of circles collision detection is easy - just calculate a distance between the centers of the circles. If the distance obtained is less than the sum of the circle's radii, the circles overlap. A: Although this question is over a year old, i was facing a similar problem recently. Thanks to a bit of research into TRectF (used by FMX and FM2 Primitives), i came up with the following very simple function; var aRect1, aRect2 : TRectF; begin aRect1 := Selection1.AbsoluteRect; aRect2 := Selection2.AbsoluteRect; if System.Types.IntersectRect(aRect1,aRect2) then Result := True else Result := False; end; Self-explanatory, but if the 2 rectangles/objects intersect or overlap, then the result is true. Alternative - Same routine, but code refined var aRect1, aRect2 : TRectF; begin aRect1 := Selection1.AbsoluteRect; aRect2 := Selection2.AbsoluteRect; result := System.Types.IntersectRect(aRect1,aRect2); end; You'll need to work on it to accept some input objects (in my case, i used TSelection's known as Selection1 and Selection2) and perhaps find a way to add an offset (take a look at TControl.GetAbsoluteRect in FMX.Types), but theoretically it should work with just about any primitive or any control. Just as an additional note, there are numerous TRectF's in use for objects like this; * *AbsoluteRect *BoundsRect *LocalRect *UpdateRect (May not apply to this situation, investigation needed) *ParentedRect *ClipRect *ChildrenRect It's important to use the one most appropriate to your situation (as results will vary wildly in each case). In my example, the TSelection's were children of the form so using AbsoluteRect was very much the best choice (as LocalRect didn't return the correct values). Realistically, you could loop through each child component of your parent to be able to figure out if there's collision between any and potentially, you could build a function that tells you exactly which ones are colliding (though to do so would likely require a recursive function). If you ever need to deal with "basic physics" under which Collision Detection would be considered one (at least in this case, it's at the basic level) in Firemonkey, then dealing with TRectF is where you need to look. There's a lot of routines built into System.Types (XE3 and likely XE2) to deal with this stuff automatically and as such you can avoid a lot of math commonly associated with this problem. Further Notes Something i noted was that the routine above wasn't very precise and was several pixels out. One solution is to put your shape inside a parent container with alClient alignment, and then 5 pixel padding to all sides. Then, instead of measuring on the TSelection.AbsoluteRect, measure on the child object's AbsoluteRect. For example, i put a TCircle inside each TSelection, set the circles alignments to alClient, padding to 5 on each side, and the modified the routine to work with Circle1 and Circle2 as opposed to Selection1 and Selection2. This turned out to be precise to the point that if the circles themselves didn't overlap (or rather, their area didn't overlap), then they'd not be seen as colliding until the edges actually touched. Obviously, the corners of the circles themselves are a problem, but you could perhaps add another child component inside each circle with it's visibility set to false, and it being slightly smaller in dimensions so as to imitate the old "Bounding Box" method of collision detection. Example Application I've added an example application with source showing the above. 1 tab provides a usable example, while a second tab provides a brief explanation of how TRectF works (and shows some of the limitations through the use of a radar-like visual interface. There's a third tab that demonstrates use of TBitmapListAnimation to create animated images. FMX Collision Detection - Example and Source A: It seems to me that there are far too many possible permutations to easily solve this problem generically and efficiently. Some special cases may have a simple and efficient solution: E.g. mouse cursor intersection is simplified by only considering a single point on the cursor; a very good technique for circles has been provided; many regular shapes may also benefit from custom formulae to detect collision. However, irregular shapes make the problem much more difficult. One option would be to enclose each shape in an imaginary circle. If those circles overlap, you can then imagine smaller tighter circles in the vicinity of the original intersection. Repeat the calculations with smaller and smaller circles as often as desired. This approach will allow you to choose a trade-off between processing requirements and accuracy of the detection. A simpler and very generic - though somewhat less efficient approach would be to draw each shape to an off-screen canvas using solid colours and an xor mask. After drawing, if any pixels of the xor colour are found, this would indicate a collision. A: Hereby a begin/setup for collision-detection between TCircle, TRectangle and TRoundRect: unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, FMX.Types, FMX.Controls, FMX.Forms, FMX.Objects, Generics.Collections, Math; type TForm1 = class(TForm) Panel1: TPanel; Circle1: TCircle; Circle2: TCircle; Rectangle1: TRectangle; Rectangle2: TRectangle; RoundRect1: TRoundRect; RoundRect2: TRoundRect; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Panel1DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Accept: Boolean); procedure Panel1DragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); private FShapes: TList<TShape>; function CollidesWith(Source: TShape; const SourceCenter: TPointF; out Target: TShape): Boolean; end; var Form1: TForm1; implementation {$R *.fmx} function Radius(AShape: TShape): Single; begin Result := Min(AShape.ShapeRect.Width, AShape.ShapeRect.Height) / 2; end; function TForm1.CollidesWith(Source: TShape; const SourceCenter: TPointF; out Target: TShape): Boolean; var Shape: TShape; TargetCenter: TPointF; function CollidesCircleCircle: Boolean; begin Result := TargetCenter.Distance(SourceCenter) <= (Radius(Source) + Radius(Target)); end; function CollidesCircleRectangle: Boolean; var Dist: TSizeF; RHorz: TRectF; RVert: TRectF; begin Dist.cx := Abs(TargetCenter.X - SourceCenter.X); Dist.cy := Abs(TargetCenter.Y - SourceCenter.Y); RHorz := Target.ShapeRect; RHorz.Offset(Target.ParentedRect.TopLeft); RVert := RHorz; RHorz.Inflate(Radius(Source), 0); RVert.Inflate(0, Radius(Source)); Result := RHorz.Contains(SourceCenter) or RVert.Contains(SourceCenter) or (Sqr(RVert.Width / 2 - Dist.cx) + Sqr(RHorz.Height / 2 - Dist.cy) <= Sqr(Radius(Source))); end; function CollidesRectangleCircle: Boolean; var Dist: TSizeF; RHorz: TRectF; RVert: TRectF; begin Dist.cx := Abs(TargetCenter.X - SourceCenter.X); Dist.cy := Abs(TargetCenter.Y - SourceCenter.Y); RHorz := Source.ShapeRect; RHorz.Offset(Source.ParentedRect.TopLeft); RHorz.Offset(SourceCenter.Subtract(Source.ParentedRect.CenterPoint)); RVert := RHorz; RHorz.Inflate(Radius(Target), 0); RVert.Inflate(0, Radius(Target)); Result := RHorz.Contains(TargetCenter) or RVert.Contains(TargetCenter) or (Sqr(RVert.Width / 2 - Dist.cx) + Sqr(RHorz.Height / 2 - Dist.cy) <= Sqr(Radius(Target))); end; function CollidesRectangleRectangle: Boolean; var Dist: TSizeF; begin Dist.cx := Abs(TargetCenter.X - SourceCenter.X); Dist.cy := Abs(TargetCenter.Y - SourceCenter.Y); Result := (Dist.cx <= (Source.ShapeRect.Width + Target.ShapeRect.Width) / 2) and (Dist.cy <= (Source.ShapeRect.Height + Target.ShapeRect.Height) / 2); end; function CollidesCircleRoundRect: Boolean; var Dist: TSizeF; R: TRectF; begin Dist.cx := Abs(TargetCenter.X - SourceCenter.X); Dist.cy := Abs(TargetCenter.Y - SourceCenter.Y); R := Target.ShapeRect; R.Offset(Target.ParentedRect.TopLeft); if R.Width > R.Height then begin Dist.cx := Dist.cx - (R.Width - R.Height) / 2; R.Inflate(-Radius(Target), Radius(Source)); end else begin Dist.cy := Dist.cy - (R.Height - R.Width) / 2; R.Inflate(Radius(Source), -Radius(Target)); end; Result := R.Contains(SourceCenter) or (Sqrt(Sqr(Dist.cx) + Sqr(Dist.cy)) <= (Radius(Source) + Radius(Target))); end; function CollidesRoundRectCircle: Boolean; var Dist: TSizeF; R: TRectF; begin Dist.cx := Abs(TargetCenter.X - SourceCenter.X); Dist.cy := Abs(TargetCenter.Y - SourceCenter.Y); R := Source.ShapeRect; R.Offset(Source.ParentedRect.TopLeft); R.Offset(SourceCenter.Subtract(Source.ParentedRect.CenterPoint)); if R.Width > R.Height then begin Dist.cx := Dist.cx - (R.Width - R.Height) / 2; R.Inflate(-Radius(Source), Radius(Target)); end else begin Dist.cy := Dist.cy - (R.Height - R.Width) / 2; R.Inflate(Radius(Target), -Radius(Source)); end; Result := R.Contains(TargetCenter) or (Sqrt(Sqr(Dist.cx) + Sqr(Dist.cy)) <= (Radius(Source) + Radius(Target))); end; function CollidesRectangleRoundRect: Boolean; begin Result := False; end; function CollidesRoundRectRectangle: Boolean; begin Result := False; end; function CollidesRoundRectRoundRect: Boolean; begin Result := False; end; function Collides: Boolean; begin if (Source is TCircle) and (Target is TCircle) then Result := CollidesCircleCircle else if (Source is TCircle) and (Target is TRectangle) then Result := CollidesCircleRectangle else if (Source is TRectangle) and (Target is TCircle) then Result := CollidesRectangleCircle else if (Source is TRectangle) and (Target is TRectangle) then Result := CollidesRectangleRectangle else if (Source is TCircle) and (Target is TRoundRect) then Result := CollidesCircleRoundRect else if (Source is TRoundRect) and (Target is TCircle) then Result := CollidesRoundRectCircle else if (Source is TRectangle) and (Target is TRoundRect) then Result := CollidesRectangleRoundRect else if (Source is TRoundRect) and (Target is TRectangle) then Result := CollidesRoundRectRectangle else if (Source is TRoundRect) and (Target is TRoundRect) then Result := CollidesRoundRectRoundRect else Result := False; end; begin Result := False; for Shape in FShapes do begin Target := Shape; TargetCenter := Target.ParentedRect.CenterPoint; Result := (Target <> Source) and Collides; if Result then Break; end; end; procedure TForm1.FormCreate(Sender: TObject); begin FShapes := TList<TShape>.Create; FShapes.AddRange([Circle1, Circle2, Rectangle1, Rectangle2, RoundRect1, RoundRect2]); end; procedure TForm1.FormDestroy(Sender: TObject); begin FShapes.Free; end; procedure TForm1.Panel1DragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); var Source: TShape; begin Source := TShape(Data.Source); Source.Position.Point := PointF(Point.X - Source.Width / 2, Point.Y - Source.Height / 2); end; procedure TForm1.Panel1DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Accept: Boolean); var Source: TShape; Target: TShape; begin Source := TShape(Data.Source); if CollidesWith(Source, Point, Target) then Caption := Format('Kisses between %s and %s', [Source.Name, Target.Name]) else Caption := 'No love'; Accept := True; end; end. A: Guess we have to roll our own. One option for this is a 2D implementation of the Gilbert-Johnson-Keerthi distance algorithm. A D implementation can be found here: http://code.google.com/p/gjkd/source/browse/
{ "language": "en", "url": "https://stackoverflow.com/questions/7628848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Netbeans project skeleton Is there a plugin for netbeans that will help you create a skeleton project so everytime you are starting a new project you could simply click File -> New Project from Skeleton instead of copying files manually? Or does anyone have any idea on how to do that? Cheers A: Here's a link to an blog describing how to do this: Hack Your Own Custom NetBeans Project Templates
{ "language": "en", "url": "https://stackoverflow.com/questions/7628851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Template based code generation that tracks/merges user changes? Does a template/code generator already exist that tracks user changes to it's output? I'm not even posative this makes sense - but the space cadet in me thinks something like this could be an interesting kind of change tracking that integrates more tightly to the code than SCM... Data.xml <Classes> <Class>Class1</Class> </Classes> Template <# for(var c in XDocument.Load("Data.xml").Element("Classes").Elements("Class")) { #> class <#=c.Value#> { public <#=c.Value#>() { // <InsertPoint> // </InsertPoint> } } <# } #> Output class Class1 { public Class1() { // <InsertPoint> // </InsertPoint> } } User Change class Class1 { public Class1() { // <InsertPoint> System.Console.WriteLine("I am Class1"); // </InsertPoint> } } --> The template changes to something like: <# for(var c in XDocument.Load("Data.xml").Element("Classes").Elements("Class")) { #> class <#=c.Value#> { public <#=c.Value#>() { // <UserInsert id="1"> System.Console.WriteLine("I am Class1"); // </UserInsert> // <InsertPoint> // </InsertPoint> } } <# } #> A: What you have in data.xml is what's normally called a model. Being done in XML, we could call this a "tree model". In other words, you are applying (executing) templates according to a pre-defined model. Tracking user changes in this case can also be called "round-trip" engineering: a bi-directional change. The ABSE project (disclaimer: I am the project lead) defines a model-driven code generation approach that is very close to your request: It uses executable templates and generates code by means of a tree model (but it's not XML). But instead of detecting your changes in code, you can add your own code directly in the model so that you can skip the "round-trip" step. A: There are tools for diff'ing on xml documents. If you can convert your code into an ast, represented in xml, you could apply these tools on the document, then transform it back to code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pushViewController failing I am trying to do a "list of items" -> "item details" kind of an application. I've managed to do the list part just fine so far. I've also created a new view for the item detail but here I get a error when I click the item I want to see the details. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ItemDetailsView *detailViewController = [[ItemDetailsView alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]]; // ERROR HERE [self.navigationController pushViewController:detailViewController animated:YES]; [detailViewController release]; } So far the new view only have a empty label that says "View Changed: OK". Nothing else. ItemDetailsView is a view that inherits from UIViewController. To create this view I went to New File -> Cocoa Touch -> UIViewController subclass. The error I'm getting is a "signabrt" when I try to execute the line below //ERROR HERE Here follows the complete message: 2011-10-02 17:26:03.582 Teste Data Nav[10035:b303] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/leo/Library/Application Support/iPhone Simulator/4.3.2/Applications/FA60D1E7-1B98-4943-98AA-C86A2339AC3E/Teste Data Nav.app> (loaded)' with name 'DetailView'' *** Call stack at first throw: ( 0 CoreFoundation 0x00dc25a9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x00f16313 objc_exception_throw + 44 2 CoreFoundation 0x00d7aef8 +[NSException raise:format:arguments:] + 136 3 CoreFoundation 0x00d7ae6a +[NSException raise:format:] + 58 4 UIKit 0x0020f0fa -[UINib instantiateWithOwner:options:] + 2024 5 UIKit 0x00210ab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168 6 UIKit 0x000c6628 -[UIViewController _loadViewFromNibNamed:bundle:] + 70 7 UIKit 0x000c4134 -[UIViewController loadView] + 120 8 UIKit 0x000c400e -[UIViewController view] + 56 9 UIKit 0x000c2482 -[UIViewController contentScrollView] + 42 10 UIKit 0x000d2f25 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48 11 UIKit 0x000d1555 -[UINavigationController _layoutViewController:] + 43 12 UIKit 0x000d27aa -[UINavigationController _startTransition:fromViewController:toViewController:] + 326 13 UIKit 0x000cd32a -[UINavigationController _startDeferredTransitionIfNeeded] + 266 14 UIKit 0x000d4562 -[UINavigationController pushViewController:transition:forceImmediate:] + 932 15 UIKit 0x000cd1c4 -[UINavigationController pushViewController:animated:] + 62 16 Teste Data Nav 0x00002d4c -[RootViewController tableView:didSelectRowAtIndexPath:] + 220 17 UIKit 0x0008bb68 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1140 18 UIKit 0x00081b05 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219 19 Foundation 0x0079b79e __NSFireDelayedPerform + 441 20 CoreFoundation 0x00da38c3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19 21 CoreFoundation 0x00da4e74 __CFRunLoopDoTimer + 1220 22 CoreFoundation 0x00d012c9 __CFRunLoopRun + 1817 23 CoreFoundation 0x00d00840 CFRunLoopRunSpecific + 208 24 CoreFoundation 0x00d00761 CFRunLoopRunInMode + 97 25 GraphicsServices 0x00ffa1c4 GSEventRunModal + 217 26 GraphicsServices 0x00ffa289 GSEventRun + 115 27 UIKit 0x00022c93 UIApplicationMain + 1160 28 Teste Data Nav 0x000023b9 main + 121 29 Teste Data Nav 0x00002335 start + 53 ) terminate called throwing an exceptionCurrent language: auto; currently objective-c A: Basically, it cannot find a .xib file called "DetailView". Make sure that your initWithNibName: has the correct string name for the .xib file. The important part of that error is: Could not load NIB in bundle: 'NSBundle </.../Teste Data Nav.app> (loaded)' with name 'DetailView' which means that there is no .xib file in your bundle called DetailView. Make sure that you use the correct name of the file: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ItemDetailsView *detailViewController = [[ItemDetailsView alloc] initWithNibName:@"ItemDetailsView" bundle:nil]; // ERROR HERE [self.navigationController pushViewController:detailViewController animated:YES]; [detailViewController release]; } Edit (from comments) connect the view to the File's Owner like so: Make sure that self has a navigationController parent. If this is the main view that appears when the app starts up, you need to add a UINavigationController to the MainWindow.xib and set its rootViewController to the view controller with this table. You can test this out by doing: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSLog("self.navController view controllers: %@", [[[self navigationController] viewControllers] description]); // Or something like this: if (self.parentViewController == self.navigationController) { NSLog(@"I have a nav controller dad!"); } else { NSLog(@"I have no nav controller!"); } // ItemDetailsView *detailViewController = [[ItemDetailsView alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]]; // ERROR HERE // [self.navigationController pushViewController:detailViewController animated:YES]; // [detailViewController release]; } If the NSLog prints out an array of view controllers, then there is another problem, but if it throws an error on the NSLog or it prints out an empty array, then your self does not have a navigationController parent. A: Not sure if it's the same issue but I had an issue where pushing a view was blowing up with a sigabort. In my case I had a typo in the name of Xib I was initing the detail view with. It can also cause the same issue if for some reason the Xib isn't well formed. In both cases, it will return you a non nil object and it doesn't blow up until you try and push it. Here was my question on how to detect it earlier: Detecting problematic XIB views earlier As a test, you can also try to create some other trivial view and push that. If that works then you've narrowed the problem down to a typo in the push, a typo in the name of the view or a non-well formed XIB file. Hope that helps get you on the right track ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7628858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "Load More" with jQuery + AJAX + XML I'm making a website to show a lot of documents (PDFs and JPGs) in one page, and I'm worried about page load times and server load because there are a lot of files. I'm storing the file data in an XML file, and am retrieving the data with jQuery and AJAX. jQuery: $(document).ready(function() { $.ajax({ type: "GET", url: "scripts/imagenes.xml", dataType: "xml", success: function(xml) { $(xml).find('imagen').each(function() { var path = $(this).find('path').text(); var img = $(this).find('img').text(); var thumb = $(this).find('thumb').text(); $('<a rel="lightbox" href="'+path+img+'">').html('<img src="' + path + thumb + '" /></a>').appendTo(".item_aesmr_img_hola"); }); } }); }); XML: <?xml version="1.0" encoding="UTF-8"?> <instituciones> <aesmr> <carnets> <imagen> <path>docs/aesmr/carnets/</path> <img>aesmr-carnet-016b.jpg</img> <thumb>thumbs/aesmr-carnet-016b.jpg</thumb> </imagen> <imagen> <path>docs/aesmr/carnets/</path> <img>aesmr-carnet-025b.jpg</img> <thumb>thumbs/aesmr-carnet-025b.jpg</thumb> </imagen> ...and so on... </carnets> </aesmr> </instituciones> I thought it would be a nice idea to use the typical Load more... button, just to let the user load the images as and when they want, with an increment of 20 images at a time. I load the thumbs with the full image is loaded when the thumbnail is clicked. Is there a way to just load the first 20 results and then use the button to show 20 more? A: one option would be to add counter in the "each" block. so that when you reach 20, you terminate the execution of the script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PowerShell Connect Wirless Adapter PowerShell 3.0 has several built-in NetAdapter cmdlets / functions. Is it possible to connect / disconnect a wireless adapter using this new noun? For example: Enable-NetAdapter or Set-NetAdapter A: You should be able to. I successfully disabled my wired adapter with the following command. Get-NetAdapter | Disable-NetAdapter And then I successfully enabled it using: Get-NetAdapter | Enable-NetAdapter I would imagine as long as the Get-NetAdapter cmdlet returns your wireless adapter you will be able to use the Enable\Disable cmdlets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fourier Transform + emgucv Can anybody tell me what is the problem in this code... Basically I am trying to compute the dft of the image and show it as an image on my screen. Image<Gray, float> GreyOriginalImage = new Image<Gray, float>(strFileName); Matrix<float> imageMat = new Matrix<float>( CvInvoke.cvGetOptimalDFTSize( GreyOriginalImage.Rows ) , CvInvoke.cvGetOptimalDFTSize( GreyOriginalImage.Cols ) ); GreyOriginalImage.CopyTo( imageMat.GetSubRect( GreyOriginalImage.ROI ) ); CvInvoke.cvDFT( imageMat , imageMat , Emgu.CV.CvEnum.CV_DXT.CV_DXT_FORWARD , imageMat.Rows ); GreyFourierImage = new Image<Gray, float>( imageMat.Rows , imageMat.Cols ); imageMat.CopyTo( GreyFourierImage ); ImageBox2.Image = GreyFourierImage; imageBox2.Show(); The problem is that the code hangs up while executing and no image gets shown.... I am using Visual studio 2010 with emgu cv. A: Well I've gone over your code and debugged it the problem line is here: imageMat.CopyTo( GreyFourierImage ); You are trying to copy imageMat which is a float[,] array to an image float[,,*] I'm sure you can figure out that this just doesn't work and is why the program hangs. Here is the code that splits the Imaginary and Real parts from cvDFT: Image<Gray, float> image = new Image<Gray, float>(open.FileName); IntPtr complexImage = CvInvoke.cvCreateImage(image.Size, Emgu.CV.CvEnum.IPL_DEPTH.IPL_DEPTH_32F, 2); CvInvoke.cvSetZero(complexImage); // Initialize all elements to Zero CvInvoke.cvSetImageCOI(complexImage, 1); CvInvoke.cvCopy(image, complexImage, IntPtr.Zero); CvInvoke.cvSetImageCOI(complexImage, 0); Matrix<float> dft = new Matrix<float>(image.Rows, image.Cols, 2); CvInvoke.cvDFT(complexImage, dft, Emgu.CV.CvEnum.CV_DXT.CV_DXT_FORWARD, 0); //The Real part of the Fourier Transform Matrix<float> outReal = new Matrix<float>(image.Size); //The imaginary part of the Fourier Transform Matrix<float> outIm = new Matrix<float>(image.Size); CvInvoke.cvSplit(dft, outReal, outIm, IntPtr.Zero, IntPtr.Zero); //Show The Data CvInvoke.cvShowImage("Real", outReal); CvInvoke.cvShowImage("Imaginary ", outIm); Cheers, Chris
{ "language": "en", "url": "https://stackoverflow.com/questions/7628864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating a Queue in Scala I am trying to create a Queue in Scala by doing: import scala.collection.immutable.Queue val empty = new Queue[Int] However I am getting an error stating that the Queue constructor is protected. If this is the case, am I missing something? All the Queue methods seem to be defined and working. Must I really extend the Queue class for no reason just to use a Queue? A: Use one of the factories: scala.collection.immutable.Queue() scala.collection.immutable.Queue.empty Note that immutable queues are co-variant, so you usually don't need to define a type for it. One exception would be var declarations. A: For empty Queue use companion object: val empty = Queue.empty[Int] A: scala> val empty = Queue [Int]() empty: scala.collection.immutable.Queue[Int] = Queue()
{ "language": "en", "url": "https://stackoverflow.com/questions/7628866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Create KML file with linestring and placemarks I am building a KML file using an app that I have built. Right now I have it nicely drawing a linestring on the map. But, now I want to add a few placemarks inside the same KML file. When trying to do this it will show either the line string or the place mark, but not both. How can I do this inside a KML file? What I currently use: <?xml version="1.0" encoding="UTF-8"?> <kml xsi:schemaLocation="http://earth.google.com/kml/2.1 http://earth.google.com/kml2.1.xsd" xmlns="http://earth.google.com/kml/2.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Placemark> <name>My Name</name> <Style> <LineStyle> <color>FF0000FF</color> <width>3.0</width> </LineStyle> </Style> <LineString> <extrude>false</extrude> <tessellate>true</tessellate> <altitudeMode>clampToGround</altitudeMode> <coordinates>A Ton of coordinates go here</coordinates> </LineString> </Placemark> </kml> A: I figured out what I have to place all of the placemarks into a <Folder> in order to have multiple placemarks show, then it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3.1 escape_javascript doesn't work as expected I have the following Code: def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, h("add_fields(this, '#{association}', '#{escape_javascript(fields)}')")) end When it runs it's supposed to duplicate the previous form field. When i click on my link to add a new field it just renders the HTML inline (it's been completely escaped and viewable). I found a previous question which said this was an issue with Rails 3.1.0rc2 but i'm running the current 3.1.0 release of rails. So i'm not sure if this something with my config or if the issue has reappeared in rails. A: Try changing this line link_to_function(name, h("add_fields(this, '#{association}', '#{escape_javascript(fields)}')")) to this link_to_function(name, "add_fields(this, '#{association}', '#{escape_javascript(fields)}')", :remote => true) I think* rails 3.1.x does the escaping automatically
{ "language": "en", "url": "https://stackoverflow.com/questions/7628869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UILongPressGestureRecognizer not working, but swapping it for a UITapGestureRecognizer works fine. Why? I have a UIImageView with a UILongPressGestureRecognizer attached that never seems to detect a long press gesture no matter how I configure the gesture recognizer. However, if I swap it out for a UITapGestureRecognizer, that works just fine. What could possibly be going on? This is how I'm configuring my UILongPressGestureRecognizer: UIImageView* cellView = (UIImageView*)[view viewWithTag:5]; UILongPressGestureRecognizer* longPressGestureRec = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(cellLongPress:)]; longPressGestureRec.numberOfTapsRequired = 1; longPressGestureRec.numberOfTouchesRequired = 1; longPressGestureRec.minimumPressDuration = 0.4; [cellView addGestureRecognizer:longPressGestureRec]; [longPressGestureRec release]; This is what cellLongPress looks like: -(void)cellLongPress:(UILongPressGestureRecognizer*)recognizer { // This never gets called. NSLog(@"someone long pressed me"); } Pretty straightforward, right? No luck so far getting it to work, though. Any ideas? A: The numberOfTapsRequired is set to 1 which means the user has to tap once before starting the long press (finger down, finger up, finger down for 0.4 seconds, gesture recognized). Change numberOfTapsRequired to 0 (which is the default). For that property, the documentation just says: The number of taps on the view required for the gesture to be recognized. But in the comments in UILongPressGestureRecognizer.h, it says: The number of full taps required before the press for gesture to be recognized
{ "language": "en", "url": "https://stackoverflow.com/questions/7628874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Deleting multiple records(rows) from tables using checkboxes Trying to delete multiple rows using check-boxes. At first i'm generating table of contents with checkbox column. Then posting data to php side. The problem is, php side returning back to the current page. It means that all done successfully and page returned user back. But no success. There is no error in php logs, and MySQL problem. I tried print_r ($_POST['checkbox']); die(); after $delete=$_POST['delete'];. It gave me result something like that Array ( [0] => on [1] => on ) what's wrong with my code? My HTML markup looks like that <?php $result = $db->query("SELECT id, name, showinmenu FROM menu") ; $num=$result->num_rows; if ($num>0) { ?> <form method="post" action="processor/dbdel.php"> <div style="overflow-y: auto; overflow-x: hidden; height:500px"> <table id="list" class="features-table"> <thead> <tr> <th>#</th> <th style="min-width:80px;" class="name">Ad (menyuda işlənən)</th> <th>Sil</th> </tr> </thead> <tbody> <? while ($row = $result->fetch_object()) { echo '<tr> <td>'.$row->id.'</td> <td><a href="'.$wsurl.'admin/?page=edit&id='.$row->id.'">'.$row->name.'</a></td> <td><input type="checkbox" name="checkbox[]" method="post" value"'.$row->id.'" id="checkbox[]" "/></td> </tr>'; } // when the loop is complete, close off the list. echo "</tbody> <tr id='noresults'> <td style='text-align:center' colspan='9'>Nəticə yoxdur</td> </tr></table> </div> <p style='text-align:center;'> <input id='delete' type='submit' name='delete' value='Seçilənləri sil'/> </p> </form>"; } ?> And here is my PHP code <?php require '../../core/includes/common.php'; $delete=$_POST['delete']; if($delete) // from button name="delete" { if (is_array($_POST['checkbox'])) foreach($_POST['checkbox'] as $del_id) { $del_id = (int)$del_id; $result=$db->query ("DELETE FROM menu WHERE id = '$del_id'") or die($db->error); $result2=$db->query ("DELETE FROM pages WHERE id = '$del_id'") or die($db->error); } if($result2) { header("location:".$wsurl."admin/?page=db"); } else { echo "Error: ".$db->error; } } ?> A: Your code is an absolute disaster. 1) Using echo with repeated string concatenation to output html. Look up HEREDOCs, double-quoted strings, or simply breaking out of PHP-mode (?>) to output html. 2) Checking for POST by looking for form fields. If you want to make sure you're in a POST situation, then do if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... } instead. This is 100% reliable, and does not depend on the presence (or absence) of particular form fields. If the data was submitted via post, this statement will evaluate to true, ALWAYS. 3) You are blindly embedding user-provided data into SQL query strings. Read up about SQL injection attacks, then consider what happens if someone hacks your form and submits a checkbox value of ' or 1' - say goodbye to the contents of your checkbox table. 4) You appear to have a stray " in your checkbox output line: [...snip...] method="post" value"'.$row->id.'" id="checkbox[]" "/></td> ^--here which is almost certainly "breaking" your form and causing subsequent tag attributes to be misinterpreted. 5) on the plus side, I'll have to give you this much - you are at least checking for query errors on your two delete queries, which is always nice to see. However, that's a minor plus in a huge field of negatives.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java repaint() and initializing objects I have a class that is supposed to simulate a firework animation using paintComponent and repaint() the problem that I have detected is that a "Firework" is newly initialized each time the method is invoked so the projectileTime field of the firework is reset to zero (as specified in the constructor) each time. Where is the appropriate place to instantiate a firework object so that the projectileTime field is incremented appropriately? (In this class or in another class) see code: public class FireworkComponent extends JComponent { private static final long serialVersionUID = 6733926341300224321L; private double time; public FireworkComponent(){ time=0; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.translate(0, this.getHeight()); Firework f= new Firework(this.getWidth()/2,0,73,90,Color.red,5); f.addFirework(75,35,Color.BLUE,6); f.addFirework(75, 155, Color.green, 6); time+=.1; Point point=f.addTime(.1); g.fillOval(point.x, (-point.y),15,15); try{ Thread.sleep(500); System.out.println("sleep"); } catch (InterruptedException e){ e.printStackTrace(); } this.repaint(); } } A: First of all get rid of the Thread.sleep() from the paintComponent() method. Then you need to define properties of the Firework component that change over time. Finally, you would use a Swing Timer to schedule the animation of the fireworks. Every time the Timer fires you would update the component properties and then invoke repaint() on the component. A: please * *don't add Firework f= new Firework(this.getWidth()/2,0,73,90,Color.red,5); inside Paint Graphics2D, you have to prepare this before *don't delay you paint by using Thread.sleep(int);, for Graphics2D is there javax.swing.Timer, but you have to initialize paintComponent() by using Timer, not stop to painting inside the Paint body *not sure if somehow working Point point=f.addTime(.1); EDIT for animations is there example A: Store the Firework as a class level attribute and instantiate it in the FireworkComponent constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Coloring compiler diagnostics with SCons I am currently using the colorama package to color messages generated by my build scripts. I have also used scolorizer, which replaces the build commands with custom, colored messages using strfunction() in SCons. This sure makes build output less verbose and warnings easier to spot. However, I often prefer to see the full command lines when building. Is there a mechanism in SCons to capture compiler output, giving the opportunity to inject some terminal colors before printing it out? A: You can do this by setting CC and CXX in the environment to a suitable wrapper around your compiler, for example colorgcc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IE 7 Z-Index and IE6 Fixed Positioning I have a vertical scrolling website - It works fine in IE7 aside from a few margin issues and problems rendering some .PNGS - but I have one big problem; I'm using two fixed positioned menus - one that slides out at an anchor point and one that just sticks to the bottom. Essentially - ones always at the top with the scroll and ones always at the bottom. They stick, and work fine - problem is, I'm using z-index in the CSS and it seems IE7 is having some problems with it - with IE7 the sticky menus go behind the content. I read a suggestion trying to position it to 'relative'. But that would destroy the fixed. Any suggestions? Thanks for anything - Sub Question - of less importance, as I'm no longer carrying IE6 - but, is there a way to continue using these menus for IE6 - a way to work around it not reading position: fixed? Here's an image to illustrate the problem better. http://tinypic.com/r/20fqqkp/7 A: Without any code it's tough to know for certain, but most likely the issue you are seeing is the z-index bug in IE. Any element in IE6 or IE7 with position: relative set will generate a new stacking context. This means that the z-index of their elements not in the same stacking context won't necessarily stack as you'd expect. For example, consider this HTML: <div id="parent-1"> <div id="child-1"></div> </div> <div id="parent-2"> <div id="child-2"></div> </div> And this CSS: /* Both parents create their own stacking context */ #parent-1, #parent-2 { position: relative; } #child-1, #child-2 { position: fixed; } /* Should be lower */ #child-1 { z-index: 10; } /* Should be higher */ #child-2 { z-index: 20; } According to the spec, #child-2 should always be stacked higher than #child-1 (and this is what you'll see in sane browsers). But since both parents have position: relative set, IE6-7 will have created 2 stacking contexts and might not do this for you. The fix is to apply z-index to the elements creating the stacking contexts or to make sure all elements are in the same stacking context. As for your IE6 problem, yes, you can emulate it with CSS expressions. Use the following in an IE6 only stylesheet: /* Fixed to the top */ #top-fixed { position: absolute; top: expression(document.documentElement.scrollTop); } /* Fixed to the bottom */ #bottom-fixed { position:absolute; top:expression( document.documentElement.scrollTop + document.documentElement.clientHeight - this.clientHeight ); } A: Try the zindex fix http://www.vancelucas.com/blog/fixing-ie7-z-index-issues-with-jquery/
{ "language": "en", "url": "https://stackoverflow.com/questions/7628885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't get '/foo' work in functional test in Rails 3? Looking at the Rails Guides http://guides.rubyonrails.org/testing.html#integration-testing-examples and this SO question Rails Functional Test of Arbitrary or Custom URLs, the following should work in a test: require 'test_helper' class ApplicationControllerTest < ActionController::TestCase test "test authentication" do get "/dash" assert_response :success end end But I get an error: ActionController::RoutingError: No route matches {:controller=>"application", :action=>"/dash"} My route is set up and works at the following URL: http://localhost:3000/dash This is the route: dash /dash(.:format) {:action=>"population", :controller=>"dashboard"} Why wouldn't a get with a URL work? I am running this test from class ApplicationControllerTest < ActionController::TestCase, which is different from dashboard controller. Do you have to run it from the functional test of the same name as the controller? Working in Rails 3.07 using Test::Unit. A: Yes, you do have to run it from the functional test for that particular controller. Rails is trying to be helpful, so it automatically picks what controller it sends the request to based on the test class's name. You'll probably also need to heed Marian's advice and use the action name rather than the URL: get :population And note that the get / post / etc. helper functions behave completely differently in integration tests (I believe your code would be correct there) - that's probably where you're getting hung up. I find this inconsistency irritating as well... Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7628887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: expression tree instead of using LINQ I have a LIST<T> where T:IComparable<T> I want to write a List<T> GetFirstNElements (IList<T> list, int n) where T :IComparable <T> which returns the first n distinct largest elements ( the list can have dupes) using expression trees. A: In some performance-critical code I wrote recently, I had a very similar requirement - the candidate set was very large, and the number needed very small. To avoid sorting the entire candidate set, I use a custom extension method that simply keeps the n largest items found so far in a linked list. Then I can simply: * *loop once over the candidates *if I haven't yet found "n" items, or the current item is better than the worst already selected, then add it (at the correct position) in the linked-list (inserts are cheap here) * *if we now have more than "n" selected, drop the worst (deletes are cheap here) then we are done; at the end of this, the linked-list contains the best "n" items, already sorted. No need to use expression-trees, and no "sort a huge list" overhead. Something like: public static IEnumerable<T> TakeTopDistinct<T>(this IEnumerable<T> source, int count) { if (source == null) throw new ArgumentNullException("source"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (count == 0) yield break; var comparer = Comparer<T>.Default; LinkedList<T> selected = new LinkedList<T>(); foreach(var value in source) { if(selected.Count < count // need to fill || comparer.Compare(selected.Last.Value, value) < 0 // better candidate ) { var tmp = selected.First; bool add = true; while (tmp != null) { var delta = comparer.Compare(tmp.Value, value); if (delta == 0) { add = false; // not distinct break; } else if (delta < 0) { selected.AddBefore(tmp, value); add = false; if(selected.Count > count) selected.RemoveLast(); break; } tmp = tmp.Next; } if (add && selected.Count < count) selected.AddLast(value); } } foreach (var value in selected) yield return value; } A: If i get the question right, you just want to sort the entries in the list. Wouldn't it be possible for you to implement the IComparable and use the "Sort" Method of the List? The code in "IComparable" can handle the tree compare and everything you want to use to compare and sort so you just can use the Sort mechnism at this point. List<T> GetFirstNElements (IList<T> list, int n) where T :IComparable <T>{ list.Sort(); List<T> returnList = new List<T>(); for(int i = 0; i<n; i++){ returnList.Add(list[i]); } return returnList; } Wouldn't be the fastest code ;-) A: The standard algorithm for doing so, which takes expected time O(list.Length) is in Wikipedia as "quickfindFirstK" on this page: http://en.wikipedia.org/wiki/Selection_algorithm#Selecting_k_smallest_or_largest_elements This improves on @Marc Gravell's answer because the expected running time of it is linear in the length of the input list, regardless of the value of n.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python/C Raw Socket Operations using Django, Mod_WSGI, Apache I'm currently writing a web application using Django, Apache, and mod_wsgi that provides some FreeBSD server management and configuration features, including common firewall operations. My Python/C library uses raw sockets to interact directly with the firewall and works perfectly fine when running as root, but raw socket operations are only allowed for root. At this point, the only thing I can think of is to install and use sudo to explicitly allow the www user access to /sbin/ipfw which isn't ideal since I would prefer to use my raw socket library operations rather than a subprocess call. I suppose another option would be to write (local domain sockets) or use an existing job system (Celery?) that runs as root and handles these requests. Or perhaps there's some WSGI Daemon mode trickery I'm unaware of? I'm sure this issue has been encountered before. Any advice on the best way to handle this? A: Use Celery or some other back end service which runs as root. Having a web application process run as root is a security problem waiting to happen. This is why mod_wsgi blocks you running daemon processes as root. Sure you could hack the code to disable the exclusion, but I am not about to tell you how to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to run an sql query from a link with javascript onclick I have a script in a joomla article that goes through the database and lists all entries by a use. Everything is done in PHP with echo statements in it. At the end of each entry, I added a "delete" button. For example: echo "[a href=\"#\" onclick=\"javascript:(NEED TO RUN QUERY HERE)\"]Delete[/a]"; How can I do this? (please ignore the square brackets, I wasn't sure how to make the code show and the pre tag didnt work that well) A: Ajax, you would make a call from javascript to your php script, return the data in JSON, parse it and append the entries to the dom A: I would recommend looking at this http://www.w3schools.com/php/php_ajax_intro.asp it should lead you through the steps you requested to setup AJAX. The left side has links how you would code it in PHP and also make Database queries. I recommend just taking the sample code and adjusting it to meet your needs. Have fun! A: here is an example on how you would do it using jquery ajax. $('#buttonid').click(function() { $.ajax({ type: "POST", url: "pathtoserversidescipt", data: $("#formid").serialize(), success: function(msg){ ("whatever you want to happen next") } }); }); Also check here to learn more. http://api.jquery.com/category/ajax/ A: You need to post that link by ajax to edit section. In edit section you can get the post id and remove it like if(isset($_GET['delete']) and $_GET['delete'] != '') and remove function remove() { $id = JRequest::getVar('id'); $db =& JFactory::getDBO(); $query = "DELETE FROM #__cd_lend_request WHERE ck_CDid = '$id'"; $db->setQuery($query); $result = $db->query(); $this->setRedirect(JRoute::_('index.php?option=com_cd'), 'CD has been removed from the list!', 'notice'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: create a CCMenuItemLabel with a custom font file I have a CCMenuitemLabel CCMenuItemLabel *startGame = [CCMenuItemLabel itemWithLabel:str target:self selector:@selector(startGamefn)]; and I was wondering how I would load a font file as you would do in CCLabelBMFont (example : CCLabelBMFont *label = [CCLabelBMFont labelWithString:str fntFile:@"good_dog_plain_32.fnt"]; thanks A: CCMenuItemLabel can accept CCLabelBMFont so you can just past the label object in the function call to CCMenuItemLabel: CCLabelBMFont *label = [CCLabelBMFont labelWithString:str fntFile:@"good_dog_plain_32.fnt"]; CCMenuItemLabel *startGame = [CCMenuItemLabel itemWithLabel:label target:self selector:@selector(startGamefn)];
{ "language": "en", "url": "https://stackoverflow.com/questions/7628893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Optimize MySQL UPDATE Query I'm trying to run this query, and the table that's being updated has about 10,000 rows. The query takes so long to execute that I can't even be bothered to wait for the return. In a couple hours this table will have 100,000 rows and so, it's going to take 10 times longer than it does already. Anyone have any ideas to optimize it? UPDATE `wpsapi4`.`product_details` AS `pd`, `r2r`.`partmaster` AS `pm`, `r2r`.`partpriceinv` AS `ppi`, `r2r`.`manufacturer` AS `m` SET `pd`.`product_name`=`pm`.`ItemName`, `pd`.`data_source`='R2R', `pd`.`partmaster`=`pm`.`id`, `pd`.`pu`=``.`ppi`.`DistributorPartNumberShort`, `pd`.`description_raw`=`pm`.`ItemDescription`, `pd`.`dealer_price`=`ppi`.`MSRP`, `pd`.`weight`=`pm`.`Weight`, `pd`.`vendor_name`=`m`.`ManufacturerName` WHERE ( `pm`.`ManufacturerNumberShort`=`pd`.`vendor_number` OR `pm`.`ManufacturerNumberLong`=`pd`.`vendor_number` ) AND `pm`.`id`=`ppi`.`DistributorPartNumberShort` AND `ppi`.`DistributorID`=2 AND `pm`.`ManufacturerID`=`m`.`id` If you think it could be to do with the table structures then please say so, I can't really change the structure at this point but if you know where the indexes should be then that would be great. Indexes are already optimized on the r2r database. A: You are doing an OR on Vendor Number, I would start by making sure that you have an index on vendor number on both tables. Looks to me that the other columns already should have indexes. A: The columns to index are the ones reference in your where clause. Consider adding the following: * *An index on the pm.ManufacturerNumberShort column. *An index on the pm.ManufacturerNumberLong column. *An index on the pm.id column. *An index on the pm.ManufacturerID column. *An index on the ppi.DistributorPartNumberShort column. *An index on the ppi.DistributorID column. Based on input from Darhazer: Consider adding one or more of the following: * *An index on the pm.ManufacturerNumberShort, pm.id, and pm.ManufacturerID columns. *An index on the pm.ManufacturerNumberLong, pm.id, and pm.ManufacturerID columns. *An index on the ppi.DistributorPartNumberShort and ppi.DistributorID columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use vb to add item and change value of second column of listview in wpf This is the xaml of listview <ListView Grid.Column="1" Height="auto" Name="ListView1" Width="auto" AllowDrop ="True" > <ListView.View> <GridView > <GridViewColumn Header="File Name" /> <GridViewColumn Header="Path" /> <GridViewColumn Header="type" /> </GridView> </ListView.View> </ListView> I add a item into the listbox, but it add a row with three same value ListView1.Items.Add("abcd") I have also tried some ways, but still have problem So I would like to know how I can add different value to second column Dim x As ItemCollection x.Add("a") x.Add("b") x.Add("c") ListView1.Items.Add(x) Dim x As New ItemCollection x.Add("a") x.Add("b") x.Add("c") ListView1.Items.Add(x) And How to get the value at second column? I have tried this code, but it just return the second character of first column, I can't find any ways to access the second column ListView1.Items(0)(1) A: I think you need to bind the list for this to work. I made this sample class: Public Class ListViewItemTemplate Public Property FileName As String Public Property FilePath As String Public Property FileType As String End Class Changed the xaml to include DisplayMember bindings: <ListView Name="ListView1" Width="auto" AllowDrop ="True" Margin="0,0,0,41"> <ListView.View> <GridView > <GridViewColumn Header="File Name" DisplayMemberBinding="{Binding Path=FileName}" /> <GridViewColumn Header="Path" DisplayMemberBinding="{Binding Path=FilePath}"/> <GridViewColumn Header="type" DisplayMemberBinding="{Binding Path=FileType}" /> </GridView> </ListView.View> </ListView> And loaded some sample data: Dim itemsList As New List(Of ListViewItemTemplate) Dim item As New ListViewItemTemplate item.FileName = "FileName A" item.FilePath = "FilePath A" item.FileType = "FileType A" itemsList.Add(item) item = New ListViewItemTemplate item.FileName = "FileName B" item.FilePath = "FilePath B" item.FileType = "FileType B" itemsList.Add(item) item = New ListViewItemTemplate item.FileName = "FileName C" item.FilePath = "FilePath C" item.FileType = "FileType C" itemsList.Add(item) ListView1.ItemsSource = itemsList Good luck!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7628896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If url not equals to specific url then add condition I am a template designer and I have some purchasable templates, but more often than not I find people share my template and redistributing them for free. so I would like a Javascript/jQuery to write that if the current url is not equal to specified url (var url = blogurlhere) then hide or remove <body> to prevent people from copying my templates. Please, I really appreciate it. A: I'd suggest: $(function() { var legitimate_url = 'http://blogurlhere.com'; if ((document.location != legitimate_url) && (Math.floor(Math.random()*111) == 1)) { document.location = 'http://yoursite.com/stolen'; } }); Where http://yoursite.com/stolen displays the most embarassing message ever. Which will happen once in 100 times or so. Base64encode that and put it into eval() and base64decode() respectively. But frankly, that'll only keep the most stupid of people from "stealing" your stuff. There's not a whole lot that you can do against "piracy" of that kind. Edit: Depending on what system(s) you are developing your templates for, you could implement some additional server side layer of security: For example, some (rather expensive) WordPress templates I have come across pull vital bits of their functionality from a remote server. The code responsible is somewhat obfuscated (though, again, it's obviously not impossible to decode for someone who knows their bits and bytes, thus enabling the person to simply pull the stuff in question from your server). Also, well-buried killswitches are quite common in expensive Magento extensions. Basically, the underlying PHP polls the developers' server now and then, transmitting the domain it's being run on. This information is then matched against a license database - if no match is detected, the extension deletes a couple of its files and leaves a rather unfriendly message for the admin. If – since you've been asking for a client-side solution, I assume this is the case – you're shipping somewhat pure HTML/CSS/JS to your customers, you're basically out of luck as far as technical solutions are concerned. Everything that happens client-side can (and therefor will) be circumvented by even moderately knowledgeable adversaries. The best thing you can do in this case, is to offer "the pirates" incentives to legalize what they have "stolen" from you, i.e. by * *offering a discount on another theme of yours *providing an hour or two of "free" customization support *offering access to a "premium support" forum *offering next day response on inquiries … for those with a valid receipt number. tl;dr: Some of the world's biggest companies (and industries) have constantly failed at protecting their stuff from "piracy". It is pretty unlikely that you will do any better. Give the customer a reason to buy from you rather than stealing. Or make your themes free in the first place and sell corresponding services. A: I believe you use window.location for this. $(function() { if (window.location != 'http://www.template.com') { $(body).html(''); } }); Insert it on a hidden place. May I suggest somewhere in the jquery file? Noone would bother browsing through that file :) A: Nothing will be 100% safe, but you might want to obfuscate your HTML for a bit of extra protection. Searching for HTML obfuscator on Google should help. There are plenty of code scramblers online. You could also make your templates in just JavaScript/jQuery and obfuscate that. It looks very scary for people with basic knowledge, but like others are saying, you can't protect against ripping in JavaScript alone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In a class that has many instances, is it better to use synchronization, or an atomic variable for fields? I am writing a class of which will be created quite a few instances. Multiple threads will be using these instances, so the getters and setters of the fields of the class have to be concurrent. The fields are mainly floats. Thing is, I don't know what is more resource-hungry; using a synchronized section, or make the variable something like an AtomicInteger? A: You should favor atomic primitives when it is possible to do so. On many architectures, atomic primitives can perform a bit better because the instructions to update them can be executed entirely in user space; I think that synchronized blocks and Locks generally need some support from the operating system kernel to work. Note my caveat: "when it is possible to do so". You can't use atomic primitives if your classes have operations that need to atomically update more than one field at a time. For example, if a class has to modify a collection and update a counter (for example), that can't be accomplished using atomic primitives alone, so you'd have to use synchronized or some Lock. A: The question already has an accepted answer, but as I'm not allowed to write comments yet here we go. My answer is that it depends. If this is critical, measure. The JVM is quite good at optimizing synchronized accesses when there is no (or little) contention, making it much cheaper than if a real kernel mutex had to be used every time. Atomics basically use spin-locks, meaning that they will try to make an atomic change and if they fail they will try again and again until they succeed. This can eat quite a bit of CPU is the resource is heavily contended from many threads. With low contention atomics may well be the way to go, but in order to be sure try both and measure for your intended application. I would probably start out with synchronized methods in order to keep the code simple; then measure and make the change to atomics if it makes a difference. A: It is very important to construct the instances properly before they have been used by multiple threads. Otherwise those threads will get incomplete or wrong data from those partially constructed instances. My personal preference would be to use synchronized block. Or you can also follow the "Lazy initialization holder class idiom" outlined by Brain Goetz in his book "Java concurrency in Practice": @ThreadSafe public class ResourceFactory { private static class ResourceHolder { public static Resource resource = new Resource(); } public static Resource getResource() { return ResourceHolder.resource; } } Here the JVM defers initializing the ResourceHolder class until it is actually used. Moreover Resource is initialized with a static initializer, no additional synchronization is needed. Note: Statically initialized objects require no explicit synchronization either during construction or when being referenced. But if the object is mutable, synchronization is still required by both readers and writers to make subsequent modifications visible and also to avoid data corruption.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Total time elapsed for each day CakePHP & MySQL id track_id start stop created 4 7 2011-09-28 22:22:21 2011-09-28 22:22:30 2011-09-28 22:22:21 3 7 2011-09-28 22:22:07 2011-09-28 22:22:12 2011-09-28 22:22:07 Given the mysql structure and data above and the model name of Lapse. What sort of find/conditions would i use to get the output in array format: 2011-09-28 => 1 minute (or the total calculation of Stops - Starts) So i can output a date and total elapsed time for that day? Thanks A: I'm not sure, but try something along this line: 'fields'=>array('SUM(UNIX_TIMESTAMP(Model.stop) - UNIX_TIMESTAMP(Model.start))') and 'group'=>'DATE_FORMAT(Model.created,"%Y-%m-%d")'
{ "language": "en", "url": "https://stackoverflow.com/questions/7628901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My jquery rendered partial isnt running the javascript inside So Im sending some parameters to my controller (via ajax) in order to retrieve some records, and then displaying the results with javascript by loading a partial. In the partial Im looping through the array of retrieved records and displaying each, but Im also trying to call a javascript function in my page's head tag, and passing data from my array. But the javascript call isnt working, infact, when I use firebug to look at the page the javascript isnt even there. Basically Im trying to update a google map with the retrieved information. Here is my rendered partial: <ol class="shop_list"> <% @shops.each do |s| %> <script type="text/javascript"> shopMarker(<%= s.latLng %>); //This would be a comma separated string containing latitude and longitude </script> <li><%= link_to s.shop_name ,"#" %></li> <% end %> </ol> Here is the jquery calling the partial when the controller responds to the JS: $("#shop_results").html("<%= escape_javascript(render("shop_results")) %>"); and here is the function Im calling in the header: function shopMarker(latLng){ var marker = new google.maps.Marker({ map: map, position:latLng }); map.setCenter(latLng); } What am I missing? A: Could you post your controller response and the link / form you're using to render shop results in the first place? Your controller should look something like: respond_to do |format| format.js end Your response should be called action_name_here.js.erb. Finally, by default on an XHR request your initial call to the controller should be using the JS response, but can you confirm by looking in your logs that it's saying ... responding with JS" format?
{ "language": "en", "url": "https://stackoverflow.com/questions/7628907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove the white "frame" that occurs when the interface flips? I have a view with a black background, when I flip the device and the interface flips with it a white pixelated "frame" appears around the black view during the animation, and then the frame disappears when the interface settles. This "frame" seem to be part of, or a consequence of the animation, is there any known way of solving this issue? A: Solution by Paul Peelen: Setting the UIWindow background color to black, in the AppDelegate, solved the problem :) [[self window] setBackgroundColor:[UIColor blackColor]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7628908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Embedded OS X Bundle Xcode Guidance I'm creating a OS X application that I intend to have a plug-in architecture. The plugins will be loaded dynamically. I wish to have a number of default bundles included in the application package contents but I am at an impasse with Xcode 4.x. Is it the best approach to create another project in the Xcode workspace and deal with it that way or is creating different targets (schemes?) in the application project a better practice? Any opinions, guidance, experience is thanked in advance --Frank A: I would create additional targets in your project for each of the plug-ins. Then, add a copy files build phase in your app the copies the plug-in into your apps's plug-ins folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java JFrame size and centre I'm working on a uni project which is to create a dice face using 2d graphics shapes. I have got that all done but I have a problem: I want my shape to change size when I adjust the window size, instead of just staying still also so that it stays in the middle. I thought I could set the position so that is was center tried this but didn't work. I'm not sure but would I have to write co-ordinates so that its changes size with the window? Any help with both problems would be great. GUI setup code import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JComponent; import javax.swing.JFrame; public class DiceSimulator { public static void main(String[] args) { JFrame frame = new JFrame("DiceSimulator"); frame.setVisible(true); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); draw object = new draw(); frame.add(object); frame.setLocationRelativeTo(null); object.drawing(); } } Painting code import javax.swing.*; import java.awt.*; //import java.util.Random; public class draw extends JComponent { public void drawing() { repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); //Random1 random = new Random1(); Graphics2D g2 = (Graphics2D) g; g.setColor(Color.BLACK); Rectangle box = new Rectangle(115, 60, 150, 150); g2.fill(box); g.setColor(Color.WHITE); g.fillOval(145, 75, 30, 30); g.setColor(Color.WHITE); g.fillOval(205, 75, 30, 30); g.setColor(Color.WHITE); g.fillOval(145, 115, 30, 30); g.setColor(Color.WHITE); g.fillOval(205, 115, 30, 30); g.setColor(Color.WHITE); g.fillOval(145, 155, 30, 30); g.setColor(Color.WHITE); g.fillOval(205, 155, 30, 30); } } A: In the paintComponent() method you need to use int width = getSize().width; int height = getSize().height; to get the current size of the component as it changes size when the frame changes size. Then based on this current size you can draw your components. This means that you can't hardcode the values in your drawing methods. If you want to shift all the drawing coordinates with one command then you can use: g.translate(5, 5); at the top of the method. Then all hardcoded (x, y) values will be adjusted by 5 pixels each. This will allow you to change the centering of the drawing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Change IOaddress of a PCI device I would like to change the IOaddress of a PCI device by writing the new (page aligned) address into BAR0/1. When I did that using a BIOS function I could not access the PCI device at the new address. Is there anything else that needs to be done to get that to work? I am using Assembler in real mode. A: Overwriting the BAR should change the address of the device. (As long as you did it properly.) Is the device behind a bridge? If so, you will also need to update the bridge configuration registers. Also, the chipset/root complex may have it's own bus decode configuration. Check the chipset datasheet. A: if your end point device is behind the bridge then change the Pre-fetchable Base Upper 32 Bit and Pre-fetchable Limit Upper 32 Bit registers appropriately. I dont think you need to worry about root complex.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling member function from other member function in PHP? I'm a little confused about the situation shown in this code... class DirEnt { public function PopulateDirectory($path) { /*... code ...*/ while ($file = readdir($folder)) { is_dir($file) ? $dtype = DType::Folder : $dtype = Dtype::File; $this->push_back(new SomeClass($file, $dtype)); } /*... code ...*/ } //Element inserter. public function push_back($element) { //Insert the element. } } Why do I need to use either $this->push_back(new SomeClass($file, $dtype)) or self::push_back(new SomeClass($file, $dtype)) to call the member function push_back? I can't seem to access it just by doing push_back(new SomeClass($file, $dtype)) like I would have expected. I read When to use self over $this? but it didn't answer why I need one of them at all (or if I do at all, maybe I messed something else up). Why is this specification required when the members are both non-static and in the same class? Shouldn't all member functions be visible and known from other member functions in the same class? PS: It works fine with $this-> and self:: but says the functions unknown when neither is present on the push_back call. A: $this->push_back will call the method as part of the CURRENT object. self::push_back calls the method as a static, which means you can't use $this within push_back. push_back() by itself will attempt to call a push-back function from the global scope, not the push_back in your object. It is not an "object call", it's just a plain-jane function call, just as calling printf or is_readable() within an object calls the usual core PHP functions. A: I cant seem to access it just by doing push_back(new SomeClass($file, $dtype)) like I would have expected. This way you call push_back() as a function. There is no way around $this (for object methods) or self::/static:: (for class methods), because it would result into ambiguity Just remember: PHP is not Java ;) A: You can access like this public static function abc($process_id){ return 1; } public static function xyz(){ $myflag=self::abc(); return $myflag; } output : 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7628921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Is {true} x := y { x = y } a valid Hoare triple? I am not sure that { true } x := y { x = y } is a valid Hoare triple. I am not sure one is allowed to reference a variable (in this case, y), without explicitly defining it first either in the triple program body or in the pre-condition. { y=1 } x := y { x = y } //valid {true} y := 1; x := y { x = y } //valid How is it? A: I am not sure that { true } x := y { x = y } is a valid Hoare triple. The triple should be read as follows:       "Regardless of starting state, after executing x:=y x equals y." and it does hold. The formal argument for why it holds is that * *the weakest precondition of x := y given postcondition { x = y } is { y = y }, and *{ true } implies { y = y }. However, I completely understand why you feel uneasy about this triple, and you're worried for a good reason! The triple is badly formulated because the pre- and post condition do not provide a useful specification. Why? Because (as you've discovered) x := 0; y := 0 also satisfies the spec, since x = y holds after execution. Clearly, x := 0; y := 0 is not a very useful implementation and the reason why it still satisfies the specification, is (according to me) due to a specification bug. How to fix this: The "correct" way of expressing the specification is to make sure the specification is self contained by using some meta variables that the program can't possible access (x₀ and y₀ in this case): { x=x₀ ∧ y=y₀ } x := y { x=y₀ ∧ y=y₀ } Here x := 0; y := 0 no longer satisfies the post condition. A: { true } x := y { x = y } is a valid Hoare triple. The reason is as follows: x := y is an assignment, therefore, replace that in the precondition. The precondition stands as {y=y}, which implies {true}. In other words, {y=y} => {true}. A: * If x:=y, then Q. Q.E.D. _*
{ "language": "en", "url": "https://stackoverflow.com/questions/7628925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Trying to add ads to my app but its not working? I am trying to ad apps but I'm getting this error and i don't know what to do. The app works but the ads don't come up and i think it might have to do with the issue. I am really new to making apps/programming so any help would be much appreciated! Thank you. Here's the issue that comes up: Apple Mach-O Linker (ID) Warning Ld "/Users/ANavarro/Library/Developer/Xcode/DerivedData/Animal_Sounds_Plus_App-edacugxnhvpqgxblqwcanzgnwdrc/Build/Products/Debug-iphonesimulator/Animal Sounds Plus App.app/Animal Sounds Plus App" normal i386 cd "/Users/ANavarro/Desktop/Animal Sounds Plus App" setenv MACOSX_DEPLOYMENT_TARGET 10.6 setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/ANavarro/Library/Developer/Xcode/DerivedData/Animal_Sounds_Plus_App-edacugxnhvpqgxblqwcanzgnwdrc/Build/Products/Debug-iphonesimulator "-L/Users/ANavarro/Desktop/Animal Sounds Plus App/GoogleAdMobAdsSDK" "-L/Users/ANavarro/Desktop/Animal Sounds Plus App" -F/Users/ANavarro/Library/Developer/Xcode/DerivedData/Animal_Sounds_Plus_App-edacugxnhvpqgxblqwcanzgnwdrc/Build/Products/Debug-iphonesimulator -filelist "/Users/ANavarro/Library/Developer/Xcode/DerivedData/Animal_Sounds_Plus_App-edacugxnhvpqgxblqwcanzgnwdrc/Build/Intermediates/Animal Sounds Plus App.build/Debug-iphonesimulator/Animal Sounds Plus App.build/Objects-normal/i386/Animal Sounds Plus App.LinkFileList" -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework MessageUI -framework SystemConfiguration -framework AVFoundation -framework AudioToolbox -framework UIKit -framework Foundation -framework CoreGraphics -lGoogleAdMobAds -o "/Users/ANavarro/Library/Developer/Xcode/DerivedData/Animal_Sounds_Plus_App-edacugxnhvpqgxblqwcanzgnwdrc/Build/Products/Debug-iphonesimulator/Animal Sounds Plus App.app/Animal Sounds Plus App" ld: warning: directory not found for option '-L/Users/ANavarro/Desktop/Animal Sounds Plus App/GoogleAdMobAdsSDK'
{ "language": "en", "url": "https://stackoverflow.com/questions/7628928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Update a div tag using Jquery I want to update a div tag(Holder) which contains a pie chart, I send values to the pie chart everytime the page loads (ResponseMetric.aspx). I am using jQuery for that purpose to update only the div tag(holder) but nothing happens, I change the value in the DB so that on page load a new value is passed. It doesnt do any page load. the values in the pie chart remains the same, where I am going wrong. <script type="text/javascript" src="scripts/jquery.js"/> <script type="text/javascript"> function getRandom() { $("#holder").hide("slow"); $("#holder").load("ResponseMetric.aspx", '', callback); } function callback() { $("#holder").show("slow"); setTimeout("getRandom();", 4000); } $(document).ready(getRandom); </script> On page load I pass the values to the pie chart which is inside the Holder (Div) tag. the data for the pie chart changes every second so basically the pie chart has to be updated every 4 seconds, but it does not A: I tried your code and did only slight modifications in a jsfiddle $(function() { function getRandom() { alert("getRandom"); $("#holder").hide("slow"); $("#holder").load("/echo/html/", 'text', callback); } function callback() { $("#holder").show("slow"); alert("callback"); setTimeout(getRandom, 4000); } $(document).ready(getRandom); }); And this worked for me, notice the only difference really being not string-encapsulating the function call in setTimeout
{ "language": "en", "url": "https://stackoverflow.com/questions/7628929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: getting finding a variable in a string I currently have some code that goes to a URL, fetches the source code, and I'm trying to get it to return a variable from the string. So I created: changetime = refreshsource.find('VARIABLE pm NST') But it wouldn't find the area in the string because the word is not VARIABLE, it is something else. How would I retrieve the constantly changing VARIABLE from that string? A: A regular expression will be able to achieve this for you. I'd you give some examples of what variable will be the we could come up with a strict expression. To match what you have above something like the following will do: import re # this will match 01:23, 11:34, 12:00, etc. timex = re.compile('.*(\d{2}:\d{2})[ ]?pm NST') match = timex.match(text, re.M|re.S) variable = match.groups(0) Edit: this code will actually work (unlike that first attempt :) ): import re # this will match 01:23, 11:34, 12:00, etc. timex = re.compile('(\d{2}:\d{2})[ ]?pm NST') match = timex.search(text) if match: variable = match.groups(0) A: If the pattern is really that simple, then this seems a typical case where regular expressions comes quite handy. Note: if you are new to regular expressions, you may want to use some introduction, like the http://www.regular-expressions.info. On the other hand, if the pattern is more complex, then you may want to use an HTML parser, like for instance BeautifulSoup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the best way to integrate an event-dispatcher in a PHP library? I need to integrate an event dispatcher in my own codebase (custom PHP library), so I looked at what both Symfony2 and Zend Framework 2 are doing. Obviously, there's no shared interface for dispatching events, because both frameworks have different needs and decided to implement their own code... so I am a bit lost: I don't want to reinvent my personal wheel. Probably the SPL interfaces for implementing the observer pattern are a bit naive, so I'm here asking you: what would you do? EDIT Since it's not clear... I want to re-use an existing ED, letting the developer inject it in my library. Let's say you develop a lib with a dispatcher and you know that your lib is gonna be a part of a Symfony Bundle and also re-used in ZF projects: you surely want to re-use Symfony's and ZF dispatchers, instead of your own. Therefore I was looking for shared interfaces for existing dispatchers implemented in mainstream libraries, but sounds like there's no solution. A: You could define an interface for your needs and then implements it with differents adapters for each framework. A: I think your first instinct to pick one of the widely used components is the way to go. Those two are the options I would be considering as well. You should simply take a look at both of them and pick the one you feel will work best for you. Shameless plug: If you want something really, really lightweight, you can take a look at Événement. A: You need to implement observer pattern by implementing PHP interface SplObserver , SplSubject. Not just Zend , Symphony does that to support hooks but generally every event dispatcher work this way by implementing observer pattern . Here is an article to know more http://devzone.zend.com/article/4284 A: Old post that has already been accepted but there is a solution for a drop in EDP solution in PHP for those that come across this as I have. http://prggmr.org The functionality is much different than that of Symfony's and Zend's implementation as their is no interface or classes that need extending to use the library, rather you simply call typical php functions to handle to the event dispatching. // Subscribe to dispatched events subscribe(callback, signal) // Dispatch an event fire(signal)
{ "language": "en", "url": "https://stackoverflow.com/questions/7628936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Filter all entities based on common property in DynamicData application I have dynamic data site based on EF CodeFirst context (using DynamicData.EFCodeFirstProvider library). Everything works, but all my entities inherit from one "common" entity that has (among others) a "IsDeleted" property. I want to filter items in dynamic data site based on this property (show only ones where IsDeleted == false). I have tried setting Where parameter of asp:EntityDataSource to item.IsDeleted, item.IsDeleted == false, item.IsDeleted = 0 and IsDeleted == false, but all I get is exception like this: 'item.IsDeleted' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. As I figured out, this "Where" property accepts sql filter, and I don't know how to pass this argument. Resources I found online all use this property in combination with strongly typed asp:EntityDataSource and I'm wondering how to filter this thata and if this is the right place to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change table background image upon mouseover of another link I have this for changing the background image of div.fullscreen: <div id="swatches"> <a href="http://www-03.ibm.com/ibm/history/exhibits/storage/images/PH3380A.jpg"> <img src="http://www.wmagency.co.uk/wp-content/uploads/2011/04/test.jpg" onmouseover="document.images['bigPic'].src='http://josefsipek.net/docs/s390- linux/hercules-s390/ssh-dasd1.png';" width="72" height="54" alt="Item ksc1" /> </a> </div> However, is there a way to change the background image of a table on hover of another image link? A: Sure, look at an example here. This is done by giving the img an id and the table an id. Then we listen for when the mouse is over the img and when it does, change the background-image of the table. Only want to use inline JavaScript? Use this: <div id="swatches"> <a href="http://www-03.ibm.com/ibm/history/exhibits/storage/images/PH3380A.jpg"> <img src="http://www.wmagency.co.uk/wp-content/uploads/2011/04/test.jpg" onmouseover='document.getElementById("table_id_here").style["background-image"]="url(\'http://www.gravatar.com/avatar/\');' width="72" height="54" alt="Item ksc1" /> </a> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7628942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on Rails assets:precompile ownership I have a Ruby on Rails based site, in which I need to run rake assets:precompile to get the correct pre-compiled assets. Whenever I run this command, however, everything in the tmp directory of my application goes back to being owned by root (which is a Very Bad Thing™ as my application requires ownership by the www-data user). How can I get Rails to quit changing the permissions? A: If you run rake assets:precompile as root, all files generated by this task will belong to root. you should run it as www-data (e.g. with sudo -u www-data), as well as any other task / ruby script / rails console on your production server, to prevent messing up the file permissions. to get things right for now, you should chown -R your application dir, before continuing
{ "language": "en", "url": "https://stackoverflow.com/questions/7628947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL Query to find customers who registered and purchased on the same day I would like to get all the customers who registered and purchased on the same day given a startdate and enddate. Below is the schema : Users --CustId --PostedDate Order --OrderId --CustId --PostedDate How do i write a query to pull same day registered and purchased orders within a specific date period? A: SELECT DISTINCT Users.CustId FROM Users JOIN Order ON Users.CustId = Order.CustId WHERE DATE(Users.PostedDate) = DATE(Order.PostedDate) AND Users.PostedDate BETWEEN @start_date AND @end_date` This is assuming PostedDate is a datetime and not date field. If it is in fact a date field, DATE(Users.PostedDate) = DATE(Order.PostedDate) can be shortened to Users.PostedDate = Order.PostedDate, and then that part of the WHERE clause can be a candidate for index usage. A: How about SELECT u.CustId FROM Users AS u INNER JOIN Orders AS o ON u.CustId = o.CustId AND u.Posted Date = o.PostedDate WHERE u.PostedDate BETWEEN @Date1 AND @Date2 Hope this helps. A: SELECT * FROM Users, Order WHERE Users.CustId = Order.CustId AND Users.PostedDate = Order.PostedDate A: SELECT u1.CustId FROM Users u1, Order o1 WHERE u1.CustId = o1.CustId AND u1.PostedDate = o1.PostedDate and o1.PostedDate between to_date('<startdate>','<oracleformat>') and to_date('fromdate','<>')+1
{ "language": "en", "url": "https://stackoverflow.com/questions/7628950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OmniAuth Facebook expired token error I am using OmniAuth to get access to Facebook in my app. I am using the fb_graph gem: https://github.com/nov/fb_graph to post to Facebook. I am running omniauth-0.3.0 on Heroku for this app. The token that I save when the user is created is changed when the user logs in sometime later. Code for creating user class SessionsController < ApplicationController def create auth = request.env["omniauth.auth"] user = User.find_by_provider_and_uid(auth["provider"], auth["uid"])|| User.create_with_omniauth(auth) session[:user_id] = user.id redirect_to root_url, :notice => "Signed in!" end The User model is: def self.create_with_omniauth(auth) create! do |user| user.provider = auth["provider"] user.uid = auth["uid"] user.name = auth["user_info"]["name"] user.token = auth["credentials"]["token"] end end I am now seeing this error on about 30% users- FbGraph::InvalidToken (OAuthException :: Error validating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons.) I saw that the expired token issue has been recently fixed in OmniAuth: https://github.com/soopa/omniauth/commit/67bdea962e3b601b8ee70e21aedf5e6ce1c2b780 I used this code which tries to refresh the access token. However, I still get the same error. Can someone point to what I am missing? Is there some other way I could update the token every time the user logs in? The only solution which has worked is to create a new User everytime the User logs in (I don't like this solution at all): def create auth = request.env["omniauth.auth"] user = User.create_with_omniauth(auth) session[:user_id] = user.id redirect_to root_url, :notice => "Signed in!" end Thanks! A: You can simply update the token when you create the session. class SessionsController < ApplicationController def create auth = request.env["omniauth.auth"] user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]).tap do |u| u.update_attributes(:token => auth["credentials"]["token"]) if u end || User.create_with_omniauth(auth) session[:user_id] = user.id redirect_to root_url, :notice => "Signed in!" end A: I was using similar solution before you answered this question- class SessionsController < ApplicationController def create auth = request.env["omniauth.auth"] user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth) user.update_attributes(:token => auth["credentials"]["token"]) session[:user_id] = user.id redirect_to root_url, :notice => "Signed in!" end A: Can't we refresh the token using FBGraph gem with follwing method in such case? auth = FbGraph::Auth.new(CLIENT_ID, CLIENT_SECRET) auth.exchange_token! access_token # Needs fb_graph 2.3.1+ auth.access_token # => new token However, This will not extend token's expiry but will replace token with new one. Expiry time will remain same. Checked it with FB, They may not allow to extend FB token expiry more than 60 days. Maximum token validity is 60-days. reference: https://github.com/nov/fb_graph/wiki/Authentication#wiki-extend-token-expiry
{ "language": "en", "url": "https://stackoverflow.com/questions/7628952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does Task.Factory.FromAsync(BeginRead, EndRead) read the entire data block before completing? In my code right now I have something like this: state.BytesRead += readPacket.Result; if (state.BytesRead < state.Data.Length) { Read(state); } else { nextRead(state); } However, I noticed that the first if statement never runs. I tried doing something like this to see if I could even get the conditional to ever run: tcpClient.SendBufferSize = 16; tcpClient.ReceiveBufferSize = 16; But still it never runs. I am sending a lot of data (strings of over >1000 characters in length) between the client and the server but still, the conditional never runs. It looks like it just always just reads in all the bytes at once. Is this because I am using Task.Factory.FromAsync and that it only completes upon reading in all the bytes? Here is the line of code that invokes the code snippet at the top of my post: Task<int>.Factory.FromAsync(state.Stream.BeginRead, state.Stream.EndRead, state.Data, state.BytesRead, state.Data.Length - state.BytesRead, state); I was using asynchronous callbacks before FromAsync and all the tutorials for that required checking if all the bytes were read before continuing on with the next read. Is this no longer necessary with FromAsync? Does it handle that automatically now? A: Task.Factory.FromAsync merely creates a bit of scaffold around pre-existing async BeginXXX/EndXXX pairs. As the methods are merely wrapped and invoked by framework rather than being explicitly invoked by you, the method by which they operate will remain unchanged.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery add delay to animation I am trying to add a delay to my Jquery so that once the mouse leaves my div id=test it will wait 3000 ms before closing back up. It doesnt seem to be working however? I am using Jquery 1.6.min Thank you in advance for your help and code snippets $("#test").hover(function() { $(this).css({'z-index' : '10'}); $(this).addClass("hover").stop() .animate({ height: '60px' }, 1500); } , function() { $(this).css({'z-index' : '0'}); $(this).delay(3000); $(this).removeClass("hover").stop() .animate({ height: '20px' }, 1500); }); A: I think you need to just chain the calls together in the second block, or they run asynchronously : $("#test").hover(function() { $(this).css({'z-index' : '10'}); $(this).addClass("hover").stop() .animate({ height: '60px' }, 1500); } , function() { $(this).css({'z-index' : '0'}) .delay(3000) .removeClass("hover") .stop() .animate({ height: '20px' }, 1500); }); A: wild guess is that you should be using chaining in order to make delay effective alternatively, in "leave handler", you could use something like this: function(){ setTimeout(function(){ .. perform what you need}, 3000);} A: You had .delay in the wrong spot. Here is the documentation: http://api.jquery.com/delay/ You should have used the code: $(this).removeClass("hover").stop().delay(3000) .animate({ height: '20px' }, 1500); And here is my example: http://jsfiddle.net/MarkKramer/7NrPA/3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7628958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to get two column values in a single query using linq to entities I have a member table with columns memberid Firstname( values like john,pop...) secondname(values like ..david ,rambo..) i want to get the firstname and secondname in a single query i want something like this.. john david pop rambo i know how to do in mysql like this.. string sql = select (Firstname,'',secondname) as fullname from members... but i dont know how to get the full name using linq to entities ... my entity name is dbcontext would any one help on this.. Many thanks In advance.. A: You can simply use C# string manipulation: List<string> names = from m in ctx.members select m.firstname + ' ' + m.secondname; Or use a more elaborate function to handle missing names etc. A: from m in member select new { FULLNAME = String.Concat(m.Firstname+" ", m.secondname) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Limiting the attributes returned in an LDAP query How do I limit the attributes that are returned in an LDAP query through System.DirectoryServices? I have been using a DirectorySearcher and adding the properties that I want to DirectorySearcher.PropertiesToLoad. The problem is that this just makes sure that the added properties are included in the DirectoryEntry.Properties as well as some default list. Is there any way to specify the only properties that you want returned? DirectoryEntry base = new DiectoryEntry(rootPath, null, null, AuthenticationTypes.FastBind); DirectorySearcher groupSearcher = new DirectorySearcher(base); groupSearcher.Filter = "(objectClass=group)"; groupSearcher.PropertiesToLoad.Add("distinguishedName"); groupSearcher.PropertiesToLoad.Add("description"); foreach (SearchResult groupSr in groupDs.FindAll()) ... Inside the foreach loop when I get the group DirectoryEntry there are about 16 different properties that I can access not just the two that I specified (distinguishedName, description) A: The thing you're limiting there are the properties that will be available / filled in your SearchResult objects - which you can access directly in your foreach loop: DirectoryEntry baseEntry = new DirectoryEntry(rootPath, null, null, AuthenticationTypes.FastBind); DirectorySearcher groupSearcher = new DirectorySearcher(baseEntry); groupSearcher.Filter = "(objectClass=group)"; groupSearcher.PropertiesToLoad.Add("distinguishedName"); groupSearcher.PropertiesToLoad.Add("description"); foreach (SearchResult groupSr in groupSearcher.FindAll()) { if(groupSr.Properties["description"] != null && groupSr.Properties["description"].Count > 0) { string description = groupSr.Properties["description"][0].ToString(); } ..... } You cannot limit the properties on the actual DirectoryEntry - so if you go grab the directory entry for each SearchResult - you have full access to everything. But the whole point is that you can define what properties you need, and access those directly on the SearchResult, without having to go back to the underlying DirectoryEntry A: The original answer is correct, but if you really need to use the DirectoryEntry and want to access a specific property make sure to load it via RefreshCache before accessing the value: dirEntry.RefreshCache(new [] { "mail", "displayName" }); var email = (string) dirEntry.Properties["mail"]?.Value; var displayName = (string) dirEntry.Properties["displayName"]?.Value; This way only "mail" and "displayName" is loaded from this entry. More information here
{ "language": "en", "url": "https://stackoverflow.com/questions/7628977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Charting solutions for Yesod Currently I am using hs-gchart do build charts to embed charts in my web application. I have seen that tkyprof uses d3.js. What other charting solutions are being used with yesod? What are the pros and cons of these solutions? A: hledger-web uses flot. Pro: very easy, featureful, supported, no dependence on google or net access, offloads rendering work to clients, probably makes your haskell build life much easier (no need for GTK). Con: not as well integrated with your app as a haskell solution would be. There is also HighCharts which is probably the flashiest js charting lib and free for non-commercial use. A: I think d3.js should also be mentioned. There is a DSL approach to d3js in Haskell.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: cURL in php - I have 2 functions that work seperatly but when combined the second one outputs the results from the 1st cURL call I am trying to get the fastspring subscription payment processing set up. I have the following file which contains 2 functions. the first calls their API via cURL and gets basic order information. the second pases in the subscription reference returned by the order functions and gets some subscription info. BOTH these functions work correctly when run separately. But when run together, the second function is NOT working and is outputting the results of the first cURL call ? <?php //order reference.. $OrderReference = 'QUI110930-3371-94207B'; //UNCOMMENT THIS IF JUST WANT TO TEST getSubscriber function on its own.. //$SubscriptionReference1 = 'QUI110926-3371-68125S'; getOrder ( $OrderReference ); getSubscription ( $SubscriptionReference1 ); //test our variaables for getOrder.. echo '<br/>1:' . $OrderReferrer; echo '<br/>2:' . $beginDate; echo '<br/>3:' . $display; echo '<br/>4:' . $value; echo '<br/>5:' . $productDisplay; echo '<br/>7:' . $SubscriptionReference; echo '<br/><br/><br/>'; //test our variaables for getSubscriber echo '<br/>1:' . $nextPeriodDate; echo '<br/>2:' . $subscriptionUrlDetail; echo '<br/><br/><br/>'; print_r ( $test ); function getOrder($OrderReference) { $username = 'my_username'; $pass = 'my_password'; //Initialize handle and set options $payload = '-i -X GET -u ' . $username . ':' . $pass; $requrl = 'https://api.fastspring.com/company/quizba/order/' . $OrderReference; define ( 'XML_PAYLOAD', $payload ); define ( 'XML_POST_URL', $requrl ); $ch = curl_init (); curl_setopt ( $ch, CURLOPT_URL, XML_POST_URL ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 ); curl_setopt ( $ch, CURLOPT_USERPWD, $username . ':' . $pass ); curl_setopt ( $ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ); curl_setopt ( $ch, CURLOPT_HTTPHEADER, array ('Content-type: Application/xml' ) ); curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 ); curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); //Execute the request and also time the transaction $result = curl_exec ( $ch ); if ($result == '') { $result = curl_exec ( $ch ); } //Check for errors if (curl_errno ( $ch )) { $resultMsg = 'ERROR -> ' . curl_errno ( $ch ) . ': ' . curl_error ( $ch ); } else { $returnCode = ( int ) curl_getinfo ( $ch, CURLINFO_HTTP_CODE ); switch ($returnCode) { case 404 : $resultMsg = 'ERROR -> 404 Not Found'; break; case 200 : break; default : $resultMsg = 'HTTP ERROR -> ' . $returnCode; break; } } //Assign the variables.. $resultArray = simplexml_load_string ( $result ); global $OrderReferrer; $OrderReferrer = $resultArray->referrer [0]; global $beginDate; $beginDate = $resultArray->statusChanged [0]; //needs to be modified.. global $display; $display = $resultArray->status [0]; global $productDisplay; $productDisplay = $resultArray->orderItems->orderItem [0]->productDisplay [0]; global $value; $value = $resultArray->total [0]; global $SubscriptionReference; $SubscriptionReference = $resultArray->orderItems->orderItem [0]->subscriptionReference [0]; //Close the handle curl_close ( $ch ); } //get the subscription details function getSubscription($SubscriptionReference) { $username = 'my_username'; $pass = 'my_password'; $payload = '-i -X GET -u ' . $username . ':' . $pass; $requrl = 'https://api.fastspring.com/company/quizba/subscription/' . $SubscriptionReference; define ( 'XML_PAYLOAD', $payload ); define ( 'XML_POST_URL', $requrl ); $newCh = curl_init (); curl_setopt ( $newCh, CURLOPT_URL, XML_POST_URL ); curl_setopt ( $newCh, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt ( $newCh, CURLOPT_TIMEOUT, 10 ); curl_setopt ( $newCh, CURLOPT_USERPWD, $username . ':' . $pass ); curl_setopt ( $newCh, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ); curl_setopt ( $newCh, CURLOPT_HTTPHEADER, array ('Content-type: Application/xml' ) ); curl_setopt ( $newCh, CURLOPT_SSL_VERIFYHOST, 0 ); curl_setopt ( $newCh, CURLOPT_SSL_VERIFYPEER, 0 ); //Execute the request and also time the transaction $newResult = curl_exec ( $newCh ); if ($newResult == '') { $newResult = curl_exec ( $newCh ); } //Check for errors if (curl_errno ( $newCh )) { $newResultMsg = 'ERROR -> ' . curl_errno ( $newCh ) . ': ' . curl_error ( $newCh ); } else { $returnCode = ( int ) curl_getinfo ( $newCh, CURLINFO_HTTP_CODE ); switch ($returnCode) { case 404 : $newResultMsg = 'ERROR -> 404 Not Found'; break; case 200 : break; default : $newResultMsg = 'HTTP ERROR -> ' . $returnCode; break; } } //Assign the variables.. global $test; $test = $newResult; //$newResultArray = new SimpleXMLElement($newResult, NULL, FALSE); $newResultArray = simplexml_load_string ( $newResult ); global $nextPeriodDate; $nextPeriodDate = $newResultArray->nextPeriodDate [0]; //needs to be modified.. global $subscriptionUrlDetail; $subscriptionUrlDetail = $newResultArray->customerUrl [0]; //Close the handle curl_close ( $newCh ); } A: Because you use define ( 'XML_POST_URL', $requrl ); you are unable to do 2 request using that. You cannot overwrite using a define, it will always keep the first value. Unless you are using it somewhere out of this script (and are unable to transfer the variables with regular variables) you should not be using define. define() is a good function for using in (for example) a config file, where you set a URL you need to use on a lot of other places. These variables should be constants, and should not be changing. Note: You should not be using globals, but return the value of the function in an array or variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does a web.config substitute app.config? I wrote a dll project in c#. I added a service reference. A app.config was automatically generated. In the same solution I have an asp.net project. If I copy paste the relevant configuration from the app.config to the web.config and change the client url - will it override the service url in the app.config? The funny thing is that everything works OK even without copying this section to the web.config. How come? TIA A: Yes. The config schema is the same for web and app.config. There are some sections that will only make sense for web apps, but generally not the other way around. You should be just fine copy-pasting your configuration. The web project only looks at Web.config, so you will need to copy the configuration to your web.config.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala or Java Library for fixing malformed URIs Does anyone know of a good Scala or Java library that can fix common problems in malformed URIs, such as containing characters that should be escaped but aren't? A: I've tested a few libraries, including the now legacy URIUtil of HTTPClient without feeling I found any viable solution. Typically, I've had enough success with this type of java.net.URI construct though: /** * Tries to construct an url by breaking it up into its smallest elements * and encode each component individually using the full URI constructor: * * foo://example.com:8042/over/there?name=ferret#nose * \_/ \______________/\_________/ \_________/ \__/ * | | | | | * scheme authority path query fragment */ public URI parseUrl(String s) throws Exception { URL u = new URL(s); return new URI( u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()); } which may be used combination with the following routine. It repeatedly decodes an URL until the decoded string doesn't change, which can be useful against e.g., double encoding. Note, to keep it simple, this sample doesn't feature any failsafe etc. public String urlDecode(String url, String encoding) throws UnsupportedEncodingException, IllegalArgumentException { String result = URLDecoder.decode(url, encoding); return result.equals(url) ? result : urlDecode(result, encoding); } A: I would advise against using java.net.URLEncoder for percent encoding URIs. Despite the name, it is not great for encoding URLs as it does not follow the rfc3986 standard and instead encodes to the application/x-www-form-urlencoded MIME format (read more here) For encoding URIs in Scala I would recommend the Uri class from spray-http. scala-uri is an alternative (disclaimer: I'm the author).
{ "language": "en", "url": "https://stackoverflow.com/questions/7628989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Easy to Program WebSocket Server I'm starting to read about websockets, but I can't find a good WebSocket server and easy to program some examples... I'm a complete beginner, and I don't need a server that supports a big concurrency, I just want something to try some examples... Any Help?? Thanks!! A: Keep in mind that websockets are new technology. The most recent draft protocol has just been submitted to become the actual standard. Opera doesn't even support the latest protocol yet and Microsoft is far behind (a partial implementation said to become available in version 10 MSIE). Chrome supports it in a development version. Firefox very recently released their version 7 that supports it. Don't be surprised if you need to become part of the "development community" as an early adopter: i.e. boot-strapping your way along as tools become mature and tutorials more plentiful. You can follow my blog. I'm creating something that seems like it's just what you're looking for and it will be distributed free to developers. Timing might be good, even though it's not ready for distribution yet. It will be integrated with parts of what's called the HLL framework that will make applications easier to develop. I'd also like to make it possible to develop back-end application components using script, including JavaScript. I've already done some work on that in the HLL framework. There's a working demonstration and you can download the dhtml / javascript client and soon a non-browser client that you can also use to build application components. The server, built in pure Sun (Oracle) Java, runs equally well on both Linux and Windows. Since it would also provide the scripting engine, application components written in script would also be portable. The websocket server supports the latest version of the proposed protocol, which has now been submitted to become the actual websocket standard. The demo will run on Chrome dev-channel (also known as Chromium) 14 or later. Also, Firefox 7 which has now been released (no longer in Beta). A: The most popular server side JavaScript framework is NodeJS, it runs best on Linux currently with a windows version in development. http://nodejs.org/ Follow the directions for installation here: https://github.com/joyent/node/wiki/Installation Once you've installed Node and NPM install the socket.io package: npm install socket.io Then visit http://socket.io/ for am introduction to the API where you can view the server side JavaScript and the client side JavaScript. A: If you are wanting a WebSocket server written in JavaScript than I suggest you look at Socket.IO. It is very simple to use, and there is lots of documentation and examples that you can find online. If you wanting to play with a low-level WebSocket server and JavaScript is not a requirement, you might check out my python based websockify project. The websocket.py module is a generic WebSocket server framework. There are some simple examples of using it in the tests directory. Websockify itself is built on websocket.py to create a fairly sophisticated websocket to raw socket bridge/proxy. A: I've had good results with node.ws.js. Do note though that it's (temporarily) incompatible with Chrome 14, because Chrome has now implemented the latest version of the IETF Hybi specification, and node.ws.js didn't catch up yet. It works well with all version of Safari, though, including Mobile Safari.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Upper bound vs lower bound for worst case running time of an algorithm I am learning about analysis of algorithms. I understand the concept of the worst case running time of an algorithm. However, what are upper and lower bounds on the worst case running time of an algorithm? What can be an example where an upper bound for the worst case running time of an algorithm is different from the lower bound for the worst case running time of the same algorithm? A: First, let's talk about cases. A case of input for an algorithm is associated with an instance of a problem. For the sorting problem (where we want to find a permutation of a set in a specific order), I can look at an instance like the set of numbers {1, 5, 4, 2, 6}. This set of numbers would be the input to a sorting algorithm that purports to solve the sorting problem, like Selection Sort, or one of the other sorting algorithms out there.  The same sets of inputs can be given to any algorithm that wants to solve a problem. It doesn't matter what sorting algorithm I use, the set of inputs is always the same (because, by definition, they're all instances of the same problem). However, a given case can be better or worse for a given algorithm. Some algorithms always perform the same no matter what the inputs are, but some algorithms might do worse on some inputs. However, this means that every algorithm has some best case and some worst case; we also sometimes talk about the average case (by taking the average of all the cases) or the expected case (when we have some reason to expect that one case will be more common than others). Algorithm Case Examples The problem of "find the minimum of an unsorted list" always works the same for every possible input. No matter what clever algorithm you write, you have to check every element. It doesn't matter if you have a list of zeros or a list of random numbers or a list where the first element is the minimum, you don't know until you get to the end. Every case is the same for that algorithm, so the best case is the worst case, and also the average case and the expected case. If the list was sorted, we could do better, but that's a different problem. The problem of "find a given element in a list" is different. Assuming you were using an algorithm that does a linear walk through the list, it might turn out that the given element was the first element of the list and you're done immediately. However, it might also be the last element of the list, in which case you have to walk the whole thing before you find it. So there you had a best case and a worst case. Algorithms as Functions of Input Size When we want to analyze an algorithm, us algorists think about every possible case we could throw at the algorithm. Usually, the two most interesting cases are the best case and the worst case. If you think of the algorithms runtime as a function of its input, the best case is the input that minimizes the function and the worst case is the input that maximizes the function. I'm using "function" in the Algebra math sense here: a series of x/y pairs (input/output pairs, or in this case "input size/number of execution steps") that draw a line. Because algorithms' runtime is a function of its input, we have a different best case (and worst case) for each possible input size. So sometimes we treat the best case as a single input, but it's really a set of inputs (one for each input size). The best case and worst case are very concrete things with respect to a given algorithm. Bounds Now what about bounds? Bounds are functions that we use to compare against a given algorithm's function. There are an infinite number of boundary functions we could consider. How many possible kinds of lines can you draw on a graph? That's how many boundary functions there are. Most algorists are usually only interested in a few specific functions: things like the constant function, the linear function, the logarthmic function, the exponential function, etc. An upper bound is a function that sits on top of another function. A lower bound is a function that sits under the other function. When we talk about Big O and Big Omega, we don't care if the bounds are ALWAYS above or below the other function, just that after a certain point they always are (because sometimes algorithms get weird for small input sizes).  There are an infinite number of possible upper bounds for any given function, and an infinite number of possible lower bounds for any given function. But this is one of those weird times when we're talking about different sizes of infinities. To be an upper bound, the function must not be below the other function, so we rule out the infinite number of functions below the other function (so it's smaller than the set of all possible functions). Of course, just because there are infinite upper bounds, doesn't mean they're all useful. The function f(∞) is an upper bound for every function, but that's like saying "I have less than an infinite number of dollars" - not particularly useful for figuring out if I'm penniless or a millionaire. So we are often interested in an upper bound that is "tight" (also known as a "least upper bound" or "supremum"), for which there is no better upper bound. Best/Worst Case + Lower/Upper Bound We have best/worst cases that represent the upper and lower functions of an algorithms' runtime function. We have upper and lower bounds that represent other functions that could be on top or below (respectively) any other function. They can be combined to articulate key ideas about algorithms. Worst Case Lower Bound: A function that is a boundary below the algorithms' runtime function, when that algorithm is given the inputs that maximize the algorithm's run time. Worst Case Upper Bound: A function that is a boundary above the algorithms' runtime function, when that algorithm is given the inputs that maximize the algorithm's run time. Best Case Lower Bound: A function that is a boundary below the algorithms' runtime function, when that algorithm is given the inputs that minimize the algorithm's run time. Best Case Upper Bound: A function that is a boundary above the algorithms' runtime function, when that algorithm is given the inputs that minimize the algorithm's run time. Examples of Case Bounds Let's give concrete examples of when we might care about each of these: Worst Case Lower Bound: The classic example here is comparison-based sorting, which is famously known to be Ω(n log(n)) in the worst case. No matter what algorithm you devise, I can pick a set of worst-case inputs whereby the tightest lower bound function is log-linear. You cannot make an algorithm that beats that bound for the worst case, and you shouldn't bother trying. It's the basement of sorting. Of course, there are many lower bounds for the worst case: constant, linear, and sublinear are all lower bounds. But they are not useful lower bounds, because there the log-linear lower bound is the tightest one. Best Case Lower Bound: Insertion Sort works by walking through the list, and inserting any out-of-order it comes across in the right place. If the list is sorted, it will only need to walk through the list once without doing any inserts. This means that the tightest lower bound of the best case is Ω(n). You cannot do better than that without sacrificing correctness, because you still need to be able to walk through the list (linear time). However, the lower bound for the best case is better than the lower bound for the worst case! Worst Case Upper Bound: We are often interested in finding a tight upper bound on the worst case, because then we know how poorly our algorithm can run in the worst of times. Insertion sort's worst case is a list that is completely out of order (i.e. completely reversed from its correct order). Every time we see a new item, we have to move it to the start of the list, pushing all subsequent items forward (which is a linear time operation, and doing it a linear number of times leads to quadratic behavior). However, we still know that this insertion behavior will be O(n2) in the worst case, acting as a tight upper bound for the worst case. It's not great, but it's better than an upper bound of, say, exponential or factorial! Of course, those are valid upper bounds for the worst case, but again that's not as useful as knowing that quadratic is a tight upper bound. Best Case Upper Bound: What's the worst our algorithm can do in the best of times? In example before of finding an element in a list, where the first element was our desired element, the upper bound is O(1). In the worst case it was linear, but in the best case, the worst that can happen is that it's still constant. This particular idea isn't usually as important as Worst Case Upper Bound, in my opinion, because we're usually more concerned with dealing with the worst case, not the best case. Some of these examples are actually Ө, not just O and Ω. In other cases, I could have picked lower or upper bound functions that weren't tight, but were still approximate enough to be useful (remember, if we're not being tight, I have an infinite well to draw from!). Note that it can be difficult to find compelling examples of different case/bound combinations, because the combinations have different utility. Misconceptions and Terminology Frequently, you'll see people with misconceptions about these definitions. In fact, many perfectly good Computer Scientists will use these terms loosely and interchangeably. However, the idea of cases and bounds ARE distinct, and you would do well to make sure you understand them. Does this mean the difference will come up in your day-to-day? No. But when you are choosing between a few different algorithms, you want to read the fine print about the cases and bounds. Someone telling you that their algorithm has a Best Case Upper Bound of O(1) is probably trying to pull the wool over your eyes - make sure you ask them what the Worst Case Upper Bound is! A: Let me illustrate this by an example: The worst-case running time for quicksort is Theta(n^2). So a valid lower bound would be Omega(n) and an upper bound would be O(n^3). This says that in the worst case scenario, quicksort will take at least linear time and at most cubic time. Now that isn't a very precise statement, but for more complex algorithms, such statements are the best that we can do. A: For a function f(n), g(n) is an upper bound (big O) if for "big enough n", f(n)<=c*g(n), for a constant c. [g dominates f] g(n) is lower bound (big Omega) if for "big enough n", f(n) >= c*g(n), for a constant c. [f dominates g] If g(n) is both upper bound and lower bound of f(n) [with different c's], we say g(n) is a tight bound for f(n) [Big theta] Use example for upper bound instead of tight one: Sometimes, it is hard to find tight bound, such as the fibonacci recursive algorithm. So we find an easy upper bound of O(2^n) easily. more info is found in answers in this post. How does it related to worst/base/... cases? (as requested by comments): Worst case/average case (or any other case) affects what the complexity function is, but big-O, big-Omega, and big-Theta can be applied to each of these cases. For example, a HashTable insert is Θ(1) average case insertion, and Θ(n) worst case insertion. It is also O(n) average case insertion (bound is not tight), and Ω(1) worst case insertion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: A Very, Very Basic JavaScript Button in Django I know a bunch of Django, HTML, and CSS, but I somehow never got around to do anything in JavaScript (only did a little jQuery). I want to use this on a simple website for the time being for pressed buttons whose look and relevant database changes without reloading the page. I would like a simple example using Django and maybe some jQuery to start learning it. Let’s just use a Favorite/Like button known from, say, Twitter as an example. The button has to * *Let a user * *favorite a post *save the choice (i.e. store it in the related MySQL DB) *Change the text and look of the button without loading a new page How would I go about this? Here is the boilerplate code to start it off: Django ### models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): likes = ManyToManyField(User, null=True, blank=True, related_name="likes") ### views.py def post(request, post_id): if request.method != 'POST': render(request, 'mytemplate.html', {'post': get_object_or_404(Post, pk=post_id)}) else: # ...? HTML Template <a class="favorite" href="#" title="Like this post">Like?<a> A: This isn't really "very, very basic". For a start, it's Ajax, rather than simple Javascript. Javascript on its own can alter anything on the page, but you want to send something to the server and get a response, which is more complicated - not massively, but enough. Note that you really need something in your markup to identify the post being liked: <a class="favorite" id="{{ post.id }}" title="Like this post">Like?</a> $.ready(function() { $('.favorite').click(function() { var $this = $(this); var post_id = this.id; $.post('/like/' + id + '/', function() { $this.replaceWith("<span class='liked'>Liked</span>"); }); }); }); ... if request.is_ajax(): post.likes.add(request.user) A: If you were doing this without JavaScript, your favourite button would be a submit button in a form, that submitted to a URL handled by a Django view function that made the required database changes. To do this via JavaScript, you replace the form submission with some JavaScript code that uses XMLHTTPRequest to do the POST instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can SimpleXML load only a partial of a XML? Is there a way not to load the whole feed but only the first 10 <item></item> tag? $feed = 'rss file'; $xml = simplexml_load_file($feed); //not the entire feed though A: No. A DOM parser (such as SimpleXML) can only load the entire document. But you can use XPath to filter the relevant parts: $xml = simplexml_load_file($feed); $top10 = $xml->xpath('/rss/channel/item[position() <= 10]'); foreach($top10 as $item) { // output $item; } A: With use of the XMLReader you can achieve this. This avoids the consumption of large amount of RAM. $xmlr = new XMLReader(); $xmlr->open('path/to/file'); // ... // move the pointer with $xmlr->read(), $xmlr->next(), etc. to the required // elements and read them with simplexml_load_string($xmlr->readOuterXML()), etc. // ... $xmlr->close();
{ "language": "en", "url": "https://stackoverflow.com/questions/7628999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to use if statement in jQuery I want to change background color each time when my_div recive class 'selected'. So far I've got this: $(document).ready(function() { if ($('#my_div').hasClass('selected')) { $("body").css({backgroundColor: '#111'}); } }); but it don't work. What's wrong? A: I want to change background color each time when my_div recive class 'selected'. There is a piece of code which is giving your element the selected class. This piece of code effectively changes your element's class to be class = "whatever classes previously existed insertednewclass". One way to do what you're trying to do, is to find the function which is adding/removing the class, and hook into it, for example: myFunction = function(...) { $('#my_div').addClass('selected'); // add more code $('#my_div').css({backgroundColor:...}); } I assume your case is not as simple as this. However this is possible even if the function is in an external library, though it's risky if the library changes its internal behavior. // some.function is the function which adds the "selected" class var oldFunction = some.function; some.function = function() { return oldFunction.apply(this, arguments); } If you cannot do that and MUST reactively detect a class attribute modification, you can use the deprecated DOM Level 2 mutation events http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents which are vaguely supported in non-IE browsers. You can see if it is supported via $.bind in jQuery; if it isn't supported in jQuery, you can use your_element.addEventListener(...) which is the native way to do things (which is basically all that jQuery is using under the covers). A: You can create a custom event that will be triggered when the selected class is set or removed. e.g. $(document).ready(function() { $('#my_div').live('myDivChangedState', function(event) { if($(event.target).hasClass('selected')) { ... } }); }); And than just trigger the event: $('#my_div').addClass('selected').trigger('myDivChangedState'); -- OR -- $('#my_div').removeClass('selected').trigger('myDivChangedState');
{ "language": "en", "url": "https://stackoverflow.com/questions/7629000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress issue..CSS nav shifts under a different page When its the homepage, the nav is aligned but when I click to another page, I shifts and only the nav section shifts. Please help!! Thank you!! Homepage: http://guntherkoo.com/ Page: http://guntherkoo.com/portfolio/ Thank you again!! A: The url for reset.css is local, so it's only found at the web root. <link rel="stylesheet" href="css/reset.css" type="text/css" media="screen"> Change it to this: <link rel="stylesheet" href="/css/reset.css" type="text/css" media="screen"> Note that there are several links included there with the same problem (your js).
{ "language": "en", "url": "https://stackoverflow.com/questions/7629003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How would I convert C# delegate function to VB.Net? Here there's an old question about this code. xmpp.OnLogin += delegate(object o) { xmpp.Send( new Message( new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?" ) ); }; I want to use it in vb.net (version 10) but I couldn't figure out how to convert it. A: The delegate is an anonymous function. The syntax is a bit different for VB .NET, as expected. Without having the VB compiler at hand, I would say you need something like: AddHandler xmpp.OnLogin, Sub(o As Object) xmpp.Send( new Message( new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?" ) End Sub A: I don't know how to declare an anonymous delegate in VB.NET and I'm too lazy to Google it, but something like this should work (warning: not tested): AddHandler xmpp.OnLogin, AddressOf Me.HandleSendMessage Private Sub HandleSendMessage(ByVal o As Object) xmpp.Send( new Message( new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?" ) ) End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7629004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Should data that is the same across all class instantiations be held in a separate, static class? If I have a class that will be instantiated that needs to reference data and/or functions that will be the same for each class. How should this be handled to follow proper programming practices Example (in PHP): class Column { $_type = null; $_validTypes = /* Large array of type choices */; public function __construct( $type ) { if( type_is_valid( $type ) ) { $_type = $type; } } public function type_is_valid( $type ) { return in_array( $type, $_validTypes ); } } Then every time a Column is created, it will hold the $_validTypes variable. This variable only really needs to be defined once in memory where all Columns created could refer to a static function type_is_valid for a static class which would hold the $_validTypes variable, declared only once. Is the idea of a static class, say ColumnHelper or ColumnHandler a good way to handle this? Or is there a way to hold static data and methods within this class? Or is this redefining of $_validTypes for each Column an okay way to do things? A: One option would be create a new model for the column configuration e.g. class ColumnConfig { private $validTypes; public isValid($type){ return isset($this->validType($type))?true:false; } } then either add it once to API if you have one, or create one global instance e.g. $cc = new ColumnConfig(); class Column { private $cc; function __construct($type){ $this->cc = $this->api->getCC(); // if you have api global $cc; // assuming you have no api, an you create a global $cc instance once. $this->cc = $cc; // <-- this would pass only reference to $cc not a copy of $cc itself. if ($this->cc->isValid($type)){ .... } } } Sounds like way to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a reference to the view at the top of the NavigationController I am in a some UIViewControlle and need to go back to the previous one, I use this code: NSLog(@"%@", [self.navigationController popViewControllerAnimated:YES]); // Here I need to reference to the view I am going go to to call some function before this view is being displayed NSLog(@"Done button pressed"); But (as written in the comment), I need to get a reference to the view that will be displayed after the pop function executed (the previous viewController. A: You can use the UINavigationController property topViewController which gives you the view controller at the top of the stack. Just call this before poping it, or it will be set to the next one :) You can also access the viewControllers property to get all the viewcontrollers the navigation controller stack contains. A: Have a look at the viewControllers property in the online docs. It will give you an array of view controllers in the navigation stack: The root view controller is at index 0 in the array, the back view controller is at index n-2, and the top controller is at index n-1, where n is the number of items in the array. So the view controller you want will be at index n-2. A: Besides what @Geoffroy and @Maurice Kelly said.. I should get reference to the object before calling the popViewControllerAnimated: function // I should get reference to the object here before calling the popViewControllerAnimated: function NSLog(@"%@", [self.navigationController popViewControllerAnimated:YES]); NSLog(@"Done button pressed");
{ "language": "en", "url": "https://stackoverflow.com/questions/7629009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SSI navigation bar, highlight selected option I have a navigation bar that I include using SSI in every page of a small site. Something like this: <ul> <li><a href="option1.shtml">option 1</a></li> <li><a href="option2.shtml">option 2</a></li> <li><a href="option3.shtml">option 3</a></li> </ul> In each page I want to highlight the selected option (maybe with bold) and disable the "self" link. As I'm not using any Server Side technology as PHP or .NET, I think this could be achieve using JavaScript. Many thanks. A: What's interesting about the example that you list is that the options are actually links! Are the links handled in Javascript? This is somewhat important to determine the answer to the question, so my answer will inherently be a bit general. The following method I'm describing assumes that there are a tags with href attributes in the list items. First use document.URL to grab the current page's URL. Store that in a variable url. Then use url.substr(url.search('www.beginning.com/of/URL/before/links/start/')) to get the part of the URL that would be in the link-, e.g. index.html. Finally, find the link with href="index.html" and use removeAttribute("href") to remove its href attribute. In addition add a class called thisPage to the element so that in CSS you can highlight it and remove the pointer cursor: .thisPage { cursor: default; font-weight: bold; } Please tell me if this was helpful and whether you have any questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hooking Disk Write Operations ? Win32/64 Is there any way to hook all disk writes going thru the system, and receive the file names of whatever's being modified, using the Win32 API? Or is this something that would require writing a driver? A: You can't do this in user mode, it needs to be kernel mode and so that means a driver. You need a File System Filter Driver. A: If you don't care about intercepting the actual data, and only want to know which files are being modified/created/deleted then you can use the ReadDirectoryChangesW API to get that info from userland. Note however that it's one of the hardest functions to use effectively and efficiently, and you should be familiar with IOCP to use it correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Button Count I'm just wondering how to count a unique click - to check the IP (not one person make 1k clicks). I viewed some scripts here and in other websites, but they aren't the specific thing I search for. I search only for script to count the clicks (without connecting to the DB) and than write them in HTML. Thanks! A: If you don't want a connection with a DB, you got other solutions like: * *log all the clicks to a text file (very bad way, example here: http://www.totallyphp.co.uk/text-file-hit-counter ) *search for some site that offers to you this service. I do not even know if you can find something like this out there (google is your friend).
{ "language": "en", "url": "https://stackoverflow.com/questions/7629014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Bash on cygwin: No such file or directory commonMongo=s:/programs/mongodb/ dbpath=$commonMongo"data/" logFile=$commonMongo"log.txt" mongoProg=s:/programs/mongodb/mongodb/ mongoBin=$mongoProg"bin/" mongod=$mongoBin"mongod.exe" a=$1 if [ "$a" == "start" ];then "${mongod} --logpath ${logFile} --logappend --dbpath ${dbpath} &" elif [ "$a" == "repair" ];then "${mongod} --dbpath ${dbpath} --repair" else echo "Incorrect usage" fi ./init.sh: line 11: s:/programs/mongodb/mongodb/bin/mongod.exe --dbpath s:/programs/mongodb/data/ --repair: No such file or directory Calling the printed command works fine: s:/programs/mongodb/mongodb/bin/mongod.exe --dbpath s:/programs/mongodb/data/ --repair A: Cygwin will actually do magic for you if you put your DOS paths in quotes, for example cd "C:\Program Files\" A: Cygwin does not recognize Windows drive letters such as s:, use /cygdrive/s instead. Your cygwin command should look like this: /cygdrive/s/programs/mongodb/mongodb/bin/mongod.exe --dbpath s:/programs/mongodb/data/ --repair Notice that the path like parameters you pass to the executable are in windows format as mongod.exe is not a Cygwin binary. To make it easier, you could add mongod.exe your path, then you do not need to specify the directory it is in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: javascript placed inside an usercontrol loads but does not execute inside a user control I have placed: <script type="text/javascript"> $(function () { alert("foooo"); }; </script> This javascript loads into the browser fine, but does not executes. What is the proper way to add javascript code to a user control in ASP.NET MVC. A: I have no experience with asp.net but the above is invalid JavaScript (no closing right parenthesis). Have you tried some very simple code like this: <script type="text/javascript"> alert("foo"); </script> A: Be sure that you have JQuery library referenced. Check it like with below code : <script type="text/javascript"> if(JQuery == "undefined") { alert("you didn't referenced the JQuery properly!") } $(function () { alert("foooo"); }); </script> A: You're missing a close paren at the end of your function. It should be like this: });
{ "language": "en", "url": "https://stackoverflow.com/questions/7629019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JQuery .get and generated PHP. How to bind events? Although I have research this topic I don't really seem to understand how to make it work. Situation: The following code is used to show the new_comments Div on my page. <script type="text/javascript"> $(function(){ $('#lnk_comment').click(function() { //alert('Handler for .click() called.'); $("#comment_new").show(); $('#new_comment').focus(); }); }); </script> This code works great when these div tags are generated by PHP. The Problem: If I instead query this PHP page through JQuery using the .get Method outputting the result using JQuery instead, it seems that the function above no longer works. It seems as though the click() event doesn't seem to bind to the lnk_comment tag. My Guess is that the DOM is loading first and the JQuery data is loading after. The Question: How do you add/bind a Click event to tags that have been generated through JQuery/JavaScript during run time? Other Thoughts: I have found something in regards to a .delegate function in JQuery but after numerous attempts, I don't really seem to get it. Thank you for any examples. A: Use live() instead: <script type="text/javascript"> $(function(){ $('#lnk_comment').live('click', function() { //alert('Handler for .click() called.'); $("#comment_new").show(); $('#new_comment').focus(); }); }); }); </script> This will automatically bind the events to newly added DOM members that match the selector (in this case #lnk_comment).
{ "language": "en", "url": "https://stackoverflow.com/questions/7629020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python: calling java program I have a tag cloud generator that I would like to call from my python program. How can I do it? I run it in a batch file java -jar ibm-word-cloud.jar -C configure.txt input.txt output.png thanks for your help. A: The subprocess module is now preferred over os.system(). A simple example, assuming run_prog.bat contains the command you need: import subprocess cmd = "run_prog.bat" proc = subprocess.Popen(cmd) A: You can use the os module: import os os.system('mybatchfile.bat') or use the subprocess module
{ "language": "en", "url": "https://stackoverflow.com/questions/7629023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IIS 7 & php big files upload problems I've been trying to upload some avi files by using several methods. First I've tried using ADOBE's ADDT "UPLOAD FILE" to upload *.avi files, everything was ok, until I've tried to upload a 131.5M video. When the size of the video is less than 40M, there's no problem, but when the video is bigger is where the problem starts. So tried different methods, jquery plugins, etc, with the same result. The server in which the movies should upload is running under IIS7. Making some search over the internet, I've found that the php.ini should be changed, so I have the following related values changed: max_file_uploads:20 max_input_time:240 memory_limit:256M post_max_size:256M upload_max_filesize:256M Also in the SNAPIN of IIS under "REQUEST FILTERING" I've changed the value to 300000000 (300M). I think it has something to do with the time the upload is taking, because sometimes I can see in the temp folder a parcial upload of something between 25 and 47M I don't think that the php upload scripts are the problem, but something on the server side. A: I finally discoverd which was the problem. In php.ini was the "*max_file_uploads*". First, I double it's value, from 20 to 40, which gave me 40 minutes timeout for an upload. Then I put in 200 which gave all the time needed to complete a 131.5 MB avi upload. After finding this (I was moving all the related parameters to see what would happen if...) I decided to check on php.net to see what was the official definition for "*max_file_uploads*" which is: "The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.". I'm completely confused why this worked, but my php.ini values are now this: max_file_uploads:200 max_input_time:14400 memory_limit:1.01G post_max_size:1G upload_max_filesize:999M Beside, moved in the IIS in Request Filtering in the IIS section of the server (using IIS 7 manager), the value for max allowed content length to 1GB. Want to thank Alykhalid for the time and advices. A: Did you increase the value of the max_input_time, what is the new value? Also try to increase the value of the CGI Time Out. Also look at this blog post for PHP time out issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What specific data being sent via HTTP POST could result in an HTTP 504 Error? I've got a site that uses an order entry form and sends a rather decently sized POST request when the form is submitted. However, when a particular value is passed in one of our form variables (OrderDetail), every time without fail, it gets an error page in the browser and a 504 error via Fiddler. Here are a couple examples of tests I ran last night sending POST requests through Fiddler. When the "OrderDetail=" value is changed to the below it will either submit successfully or return a 504 error after a few seconds: These ones FAIL: * *&OrderDetail=Deliver+Writ+of+Execution%3B+and+Application+for+Earnings+Withholding+Order+to+Los+Angeles+County+Sheriff+DASH+Court+Services+Division+per+instructions *&OrderDetail=Deliver+Execution+Earnings+Withholding+Order+to+Los+Angeles+County+Sheriff+DASH+Court+Services+Division+per+instructions *&OrderDetail=Deliver+Writ+of+Execution%3B+and+Application+for+Earnings+Withholding+Order+to+Los+Angeles+County+Sheriff *&OrderDetail=Deliver+Writ+of+Execution%3B+Application+for+Earnings+Withholding+Order+to+Los+Angeles+County+Sheriff *&OrderDetail=Writ+of+Withholding+Execution+Order+Los+Angeles+County+Sheriff *&OrderDetail=writ+Execution+adsfsdfsdfsd+Order+County *&OrderDetail=wd+Execution+adsfsdfsdfsd+Order+Count This got me thinking that perhaps it has to do with the words "Exec" ('Exec' and 'Execution' throw errors, 'Exe' does not) and "Count" ('County' and 'Count' throw errors, 'Cont' does not) However, I haven't seen anything this specific mentioned in google searches regarding the 504 error. Regarding the Coldfusion code around this, there is nothing fancy for this page. Just a standard form post. I added a cfmail test in the Application file and on these failures it is never ran, so this seems to be between the browser and IIS. We're on a shared server, so I can't see too much there, though. Oddly enough, when the &OrderDetail= param is changed to one of these values (very similar to the above), the result is success: * *&OrderDetail=wd+Execution+adsfsdfsdfsd+Order+Coun *&OrderDetail=wd+Execution+adsfsdfsdfsd+Order+Conty *&OrderDetail=Writ+of+Withholding+Order+Execution+Los+Angeles+County+Sheriff *&OrderDetail=Writ+of+Withholding+ExecutionOrder+Los+Angeles+County+Sheriff In the 3rd one, I put 'Order' BEFORE 'Execution' and it works.. The total length of this POST request is about 4720 characters. I've increased the length of this one field to 5-6 times its length and they passed, so it almost seems tied to the value of the "&OrderDetail" param in the POST. Any ideas on why this specific data could be an issue for a web server? I've never seen this before and it doesn't continue to be a problem for nearly any other request going through. One interesting note as well: In the POST request, this variable is pretty close to the start of the param list. If I delete everything after it, it goes with no problem. Although I haven't been able to nail down what in the subsequent lines could be causing it. I can post the entire request if it will help. More importantly though, I just want to know what could qualify as "reserved" or "illegal" for FORM data. Everything appears to be escaped properly so I'm not sure what else can be done here except for some pre-processing javascript to further escape any such words. Thanks! A: Given that EXEC and COUNT are causing the error, whilst putting ORDER before EXEC is preventing the error, this sounds like something is making a flawed attempt at protecting from SQL injection attacks. If you have any software in place that claims to do that, I would see if (temporarily) disabling it stops the problem from occurring. (This software might be at the firewall level, so you may need to talk to your sys admins.) Importantly, I would also check your codebase for where OrderDetail is used, and make sure that it is using cfqueryparam whenever it is used inside a query - and the same goes for all other user-supplied data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change the property of component in wpf? This is a very simple case I want to click on the button, then change the itself position the visual studio prompt me that is a public property, and the type is double. Why I cannot change the value? And it does not provide any method let me change the top property, so how I can change the property? <Button Content="Button" Grid.Column="1" Height="23" HorizontalAlignment="Left" Margin="0,0,0,0" Name="Button1" VerticalAlignment="Top" Width="75" Grid.Row="1" /> MsgBox(Button1.Margin.Top) Button1.Margin.Top = 10 A: You can't set each margin individually, but you can set the button margin to a new thickness and hardcode 10 as the top margin while leaving the other values untouched: Button1.Margin = New Thickness(Button1.Margin.Left, 10, Button1.Margin.Right, Button1.Margin.Bottom) A: If you want to move the button around don't use Margin, it's not made for that intent. Instead, place your button in a Canvas, then you can set Canvas.Top/Bottom/Left/Right to move your button around (they are attached properties).
{ "language": "en", "url": "https://stackoverflow.com/questions/7629033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Really basic C# array/loop confusion I'm doing a basic 2D array in C# and I've got a bit of confusion. I'm a lot more used to working with 1-based arrays, so 0-based arrays kind of mess up my head if you know what I mean. blocks = new Block[15, 999]; for (int x = 0; x <= 15; x++) { for (int y = 0; y <= 999; y++) { blocks[x, y] = new Dirt(terrainTexture, new Vector2(x * 16, y * 16)); } } So it's telling me I'm out of bounds of the array? If the array is from 0-15, 0-999 Shouldn't a loop from 0-15, 0-999 work? A: You have 15 and 999 elements, but since arrays are 0-indexed, that means they run from 0-14 and 0-998, respectively. A: It's not. 999 is the length of the array. Thusly, it's from 0-998, and when you loop over it, you should be in the habit of using "less than" rather than "less than or equal" -- then it will tend to come out right.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding my flex project to github What to commit and what to ignore when adding a flex project to github? Keep in mind that I want to share it with others and accept pull requests. A: I don't use flex, but here are some general rules for all source control: Commit: * *Human written code *Configuration files *Referenced 3rd party libraries (that are not typically part of the standard environment) *In some cases tools needed to build and run that are not standard (save people hunting and downloading if you can) Ignore: * *Generated code, that can be easily regenerated using a scripts, tools * *Generated CSS files if you write SASS/SCSS/LESS instead *Generated JS files if you write Coffeescript instead *Build artifacts, build folders, *Temporary files (e.g., some editors creating working files) As an addendum for Git, I prefer to keep some non-code artifacts in submodules to avoid polluting the code repository. This can include: * *Large assets, images and videos in some cases *Tools and executables (very handy if you reuse these tools for multiple projects) This is not an exhaustive list and your environment probably dictates some deviation or adjustments here. The first rules in
{ "language": "en", "url": "https://stackoverflow.com/questions/7629042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: class design - improving a view_html class This class provides user created content to the page. The call is made from html like this: <?php new route('tweets'); ?> or <?php new route('bookmarks'); ?> Route instantiates view_html and passes the paramter along. What improvments that can be made? /*view_html*/ class view_html extends database { function __construct($type) { parent::__construct(); switch ($type) { case "bookmraks": $this->bookmarks(); break; case "tweets": $this->tweets(); break; default: echo "Invalid View Type"; break; } } private function bookmarks() { $email = $_SESSION['email']; $query_return = database::query("SELECT * FROM bo WHERE email='$email' ORDER BY name ASC"); while ($ass_array = mysqli_fetch_assoc($query_return)) { $fav=$this->fav($ass_array['url']); echo "<img name=\"bo_im\" class=\"c\" src=\"$fav\"/ onerror=\"i_bm_err(this)\"><a target=\"_blank\" name = \"a1\" class = \"b\" href = \"$ass_array[url]\">$ass_array[name]</a>"; } } private function tweets() { $query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7"); $time = time(); while ($a = mysqli_fetch_assoc($query_return)) { echo "<div class=\"Bb2b\"><img class=\"a\" src=\"p/$a[email].jpg\" alt=\"\"/><a class=\"a\" href=\"javascript:void(0)\">$a[fname] posted <script type=\"text/javascript\">document.write(v0($a[time],$time))</script></a><br/><p class=\"c\">$a[message]</p></div>"; } } private function fav($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if(preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $pieces['scheme'] . '://www.' . $regs['domain'] . '/favicon.ico'; } return false; } } A: This isn't a code review site, you'd be better off taking this question here https://codereview.stackexchange.com/ However, you may want to consider using a switch block instead of if statements in case you want to expand the number of possible types later. http://php.net/manual/en/control-structures.switch.php A: For the type, you could use a switch case construct in your constructor. The default case could be throwing an InvalidArgumentException.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery change of checkbox I'm not sure if the change method is the correct to use. What i want is if the checkbox is clicked(checked) the html of the textarea is var two and if the checkbox is unchecked the html of the textarea is var one. How do i accomplish this? <script type="text/javascript"> $(function() { $('.image').change(function() { var one='type information here'; var two='type url here'; if($('.information').html=='type information here') { $('.information').html('type url here'); } else { $('.information').html('type information here'); } }); }); </script> <input type="checkbox" class="image"/> <textarea class="information">type information here</textarea> A: Use .val() instead of .html(). Also, notice that you've forgot the parentheses in your if-condition. $(function() { $('.image').change(function() { var one='type information here'; var two='type url here'; if($('.information').val() == one) { $('.information').val(two); } else { $('.information').val(one); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7629053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to deploy an app that I coded for Android to iOS? I'm using Eclipse to build my Android app using XML and JavaScript. Is it possible to deploy it to the App store without rewriting all the code? A: If you have coded your app to be substantially made up of a webview, then you can transfer all that part of the code over by several methods - the one that I think would be easiest would be phonegap. In the future, you can think about using Titanium Studio which allows you to code in Javascript (and a tiny bit of XML for configuration) and compiles to native code for both Android and iOS - so has native performance. A: If you written your app in something like Sencha or PhoneGap - then you can run that code on every platform these frameworks support. But it's in Java (not JavaScript), then there's no way run it on iOS I'm afraid.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to Use UISearchBar for Custom Cells in UITableView I'm populating my tableview from an array. And this array is created by SQLite query. So in my array, I have objects from my user-defined class. And I use custom cells in my table. Like object.name in one layer, object.id near this layer. So far everything's good. But if I try to use UISearchBar, how will I re-populate my table? This is the code I create my table. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"SpeakersCell"; SpeakersCell *cell = (SpeakersCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SpeakersCell" owner:self options:nil]; for (id currentObject in topLevelObjects) { if ([currentObject isKindOfClass:[SpeakersCell class]]) { cell = (SpeakersCell *) currentObject; break; } } } // Set up the cell ProjectAppDelegate *appDelegate = (ProjectAppDelegate *)[[UIApplication sharedApplication] delegate]; Speaker *speakerObject = (Speaker *)[appDelegate.speakers objectAtIndex:indexPath.row]; cell.lblSpeakerName.text = speaker.speakerName; cell.lblSpeakerCity.text = speaker.speakerCity; return cell; } When I add a search bar and define searchBar textDidChange event, I successfully get items that contains the key letters. But I can't re-populate my table because I only have searched items' names. Tutorials I got help from are built on default cells and the datasource of tableview is NSString array. But my array is NSObject array, this is my problem. I consider getting indexes of searched items but how can I use these values either? Do you have any idea or any related link? A: I think you should take a look at Bobgreen's blog, his tutorial helped me quite a lot. http://www.cocoabob.net/?p=67 Check his delegeate function for UISearchDisplayController (which I guess you might want to use?) - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { [self.filteredListContent removeAllObjects]; for (Product *product in listContent) { if ([scope isEqualToString:@"All"] || [product.type isEqualToString:scope]) { NSComparisonResult result = [product.name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])]; if (result == NSOrderedSame) { [self.filteredListContent addObject:product]; } } } } He has an array of NSObject's (product) there which he loops thru. Each time a result matches the search string he puts the value in an second array called filteredListContent and he'll show upp the filtered content. Works like a charm for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Checking if there is an active internet connection iPhone situation I would like to check to see if the user has an active internet connection. This is how I have implemented it. It seems to work fine but the problem is it ALWAYS shows that there is no connection on my iPhone simulator (uialert comes up) even when my wifi is turned on or off. Does any know what I am doing wrong? Thanks for your help! Reachability *r= [Reachability reachabilityWithHostName:@"http://www.google.com"]; NetworkStatus internetStatus= [r currentReachabilityStatus]; if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) { UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"No internet" message:@"No internet connection found. Please try again later" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } else { // execute code in app } A: This is how I have done it in my apps: Reachability *reachability = [Reachability reachabilityForInternetConnection]; NetworkStatus internetStatus = [reachability currentReachabilityStatus]; if(internetStatus == NotReachable) { UIAlertView *errorView; errorView = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Network error", @"Network error") message: NSLocalizedString(@"No internet connection found, this application requires an internet connection to gather the data required.", @"Network error") delegate: self cancelButtonTitle: NSLocalizedString(@"Close", @"Network error") otherButtonTitles: nil]; [errorView show]; [errorView autorelease]; } What is does is that it checks for an internetconnection, not if it can reach a domain. If no internet connection (wifi or celluar) it will show an UIAlertView message (localized). A: Don't check. The radio often starts turning on and establishing a connection just after reachability reports no network (the reachability reporting that there is no network may be what starts this process and thus renders it's own answer to be false a few seconds later.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: UITabBar Action in a loop I have created a view loading to it toolbar with few 7 buttons. I want to add action for each - thus each one will perform different action all of them will load view but according to the user selection of the button I will load to the view different screen i.e buttons etc.. Here is my loop: int i =0; for (NSString *items in array) { //Set button style [barButton setStyle:UIBarButtonItemStyleBordered]; //Set the button title [barButton setTitle:[array objectAtIndex:i]]; [barButton setAction:@selector(tmp:)]; //Add the bar button to the array - later will load the array to the tool bar items list. [itemsArray insertObject:barButton atIndex:i]; i++; } As you see setAction is now activate tmp method - I want to take it from the name of the method from the NSString value of the array - ideas? A: You can use NSSelectorFromString function. See here : http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSelectorFromString
{ "language": "en", "url": "https://stackoverflow.com/questions/7629081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql total elapsed times from two dates If i have two rows id created start stop 1 28-01-2011 23:00 28-01-2011 23:00 28-01-2011 23:01 2 28-01-2011 23:10 28-01-2011 23:10 28-01-2011 23:11 What query can i run to get the total elapsed time for one date, so for 28-01-2011 the total time was 2 minutes. Is this possible? A: well one option is straight forward: select sum(unix_timestamp(stop) - unix_timestamp(start))/60 from table where date(created) = '28-01-2011'; mysql> select now(), date_add(now(), interval 10 minute); +---------------------+-------------------------------------+ | now() | date_add(now(), interval 10 minute) | +---------------------+-------------------------------------+ | 2011-10-04 13:29:56 | 2011-10-04 13:39:56 | +---------------------+-------------------------------------+ 1 row in set (0.01 sec) mysql> select sum(unix_timestamp(now()) - unix_timestamp(date_add(now(), interval 10 minute))); +----------------------------------------------------------------------------------+ | sum(unix_timestamp(now()) - unix_timestamp(date_add(now(), interval 10 minute))) | +----------------------------------------------------------------------------------+ | -600 | +----------------------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql> select sum(unix_timestamp(now()) - unix_timestamp(date_add(now(), interval 10 minute))) / 60 ; +---------------------------------------------------------------------------------------+ | sum(unix_timestamp(now()) - unix_timestamp(date_add(now(), interval 10 minute))) / 60 | +---------------------------------------------------------------------------------------+ | -10.0000 | +---------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Return a Pretty Zero Value with the Count Property from Get-Process? Compare the three scripts below: Sample 1 $a = GPS | Where {$_.ProcessName -Match 'AcroRd32'} $a $a.Count If ($a.Count -Eq 0) { Echo "Adobe Reader is Off" } Else { Echo "Adobe Reader is On" } # If Adobe Reader is not running, how come 0 (zero) is not returned? # This is prettier, should I use it? Or does it slow down performance? Sample 2 $a = GPS AcroRd32 $a $a.Count If ($a.Count -Eq 0) { Echo "Adobe Reader is Off" } Else { Echo "Adobe Reader is On" } # If Adobe Reader is not running, how come 0 (zero) is not returned? # This is uglier, but it doesn't have to pipe any output, so does it have any performance gains? Sample 3 GPS AcroRd32 | Measure | Select -Expand Count # 0 (zero) is returned, but with an ugly Error I guess part of my problem is that I'm treating PowerShell like it's VBS; writing code in this manner/style would usually yield me an integer value of zero and not throw any errors (if Adobe Reader was off, of course). What's the correct PowerShell way of checking that an instance of a program is not running? The performance questions in the comments are secondary to the "PowerShell Way" question. P.S. To be honest, the Error Message returned by the 3rd Sample wouldn't break anything, it's just ugly, so it's not beyond practical use, so I guess the real problem is that I'm just a sucker for aesthetics =^D A: This is a common PowerShell gotcha. A command can return: * *Nothing ~ null (does not have the property Count, getting it either gets null or fails) *A single object (it may have its own property Count property, the most confusing case -- can return anything; or may not have it, then getting Count gets null or fails) *2+ object array which has the property Count. The solution is simple. When you really need the count of returned objects use the @() operator. The result is always an array which has the property Count. # this is always an array $result = @(<command returning something or nothing>) # this is always a number: $result.Count A: I would suggest you to do something like this: $count = @(get-process | ?{$_.ProcessName -eq "AcroRd32"}).count if($count -eq 0){ write-host "Adobe Reader is Off" } else{ write-host "Adobe Reader is On" } What the above does is that it forces the returned objects into an array, so if there are no reader processes running, you will get an empty array and hence its count will be zero. And when you do have processes, you have them in the array, and you get the non-zero count and the above code will work as expected. Alternative based on Sample2 / Sample3: $acrobat = gps AcroRd32 -ErrorAction SilentlyContinue if($acrobat){ write-host "Adobe Reader is On" } else{ write-host "Adobe Reader is Off" } In the above, we suppress the error if the reader is not running. Then, if $acrobat is set, you know that the reader is running. Observations on your code: When the reader is not running, $a gets assigned nothing and hence $a.Count -eq 0 will be false. When reader is running, $a gets assigned those process objects and you get $a.Count as 1 or more and hence again false. So you will always get that the reader is on. A: you mention the error in the third example - you can hide the message by using the SilentlyContinue ErrorAction: GPS -ea silentlycontinue AcroRd32 | Measure | Select -Expand Count
{ "language": "en", "url": "https://stackoverflow.com/questions/7629087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: .NET IoC: Register type instance created during actual program execution I'm still trying to get to grips with IoC, and I suppose I'm actually on the completely wrong track here concerning the way program flow/type resolution needs to be structured. I have a WinForms application written pretty much "the old way" which I want to convert to an IoC structure using Autofac for practice purposes. It consists of a main form from which a logon dialog can be opened, and after successfully connecting to a server, various functions can be performed against the server from the UI using a web service. I have started configuring the Autofac container by registering the MainForm and LogonDialog classes, so my code in Program.cs looks like this: [STAThread] private static void Main() { Autofac.IContainer container = buildContainer(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(container.Resolve<Form>()); } private static Autofac.IContainer buildContainer() { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<MainForm>().As<Form>().SingleInstance(); builder.Register(c => new LogonDialog()); IContainer container = builder.Build(); return container; } The MainForm constructor takes a Func<LogonDialog> which is later used to instantiate the logon dialog in a using clause. This works. I am now stuck at the following point: After successful logon, the LogonDialog returns a Connection object that holds various information about the connection made to the server. One of its properties is a reference to the web service (IBackendWebservice) which is then passed to other objects that implement the various functionalities of the application (vaguely in a ViewModel/Controller manner). So I might have a constructor like FindRecordController(IBackendWebservice dbservice). The next step in my conversion would probably be wiring up those controller types in the container, and along with those, I would of course like to have the IBackendWebservice instance registered so it can be automatically resolved whenever the interface is referenced. The problem now is obviously that at the point when I finally have the IBackendWebservice object, the container has already been built and can't accept any new registrations (and I don't have a reference to it anyway in my MainForm). One thing that came to my mind right now is that I probably have to wire up a factory delegate for the Connection class and pass it to the LogonDialog, so the container has a reference to the Connection object I'm working with. But how would I then have to register the IBackendWebservice interface as a property of that Connection instance ? And how would I make sure the Connection instance can and will be replaced when a new connection is made through the logon dialog, but not in any other place the Connection type is being resolved ? Does this thought make any sense at all ? Thanks for any *pointers. A: You can communicate your intent through your design by letting LogonDialog take a dependency on a ConnectionContainer, which has a Connection property. Only types that may set the connection will take a dependency on it. Other types will take a dependency on Connection as they always did, but you can resolve it directly from the container: builder.RegiserType<ConnectionContainer>(); builder.Register(c => c.Resolve<ConnectionContainer>().Connection).AsSelf(); (with scpoing modified as needed).
{ "language": "en", "url": "https://stackoverflow.com/questions/7629094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing the results from a nested loop into another vector in R I'm pretty new to R, and am struggling a bit with it. I have the following code: repeat { if (t > 1000) break else { y1 <- rpois(50, 15) y2 <- rpois(50, 15) y <- c(y1, y2) p_0y <- matrix(nrow = max(y) - min(y), ncol = 1) i = min(y) while (i <= max(y)) { p_0y[i - min(y), ] = (length(which(y1 == i))/50) i <- i + 1 } p_y <- matrix(nrow = max(y) - min(y), ncol = 1) j = min(y) while (j <= max(y)) { p_y[j - min(y), ] = (length(which(y == j))/100) j <- j + 1 } p_0yx <- p_0y[rowSums(p_0y == 0) == 0] p_yx <- p_y[rowSums(p_0y == 0) == 0] g = 0 logvect <- matrix(nrow = (length(p_yx)), ncol = 1) while (g <= (length(p_yx))) { logvect[g, ] = (p_0yx[g])/(p_yx[g]) g <- g + 1 } p_0yx %*% (log2(logvect)) print(p_0yx %*% (log2(logvect))) t <- t + 1 } } i am happy with everything up to the last line, but instead of printing the value of p_0yx%*%(log2(logvect)) to the screen i would like to store this as another vector. any ideas? i have tried doing it a similar way as in the nested loop but doesnt seem to work. Thanks A: The brief answer is to first declare a variable. Put it before everything you've posted here. I'm going to call it temp. It will hold all of the values. temp <- numeric(1000) Then, instead of your print line use temp[t] <- p_0yx %*% log2(logvect) As an aside, your code is doing some weird things. Look at the first index of p_0y. It is effectively an index to item 0, in that matrix. R starts indexing at 1. When you create the number of rows in that matrix you use max(y) - min(y). If the max is 10 and the min is 1 then there's only 9 rows. I'm betting you really wanted to add one. Also, your code is very un R-like with all of the unnecessary while loops. For example, your whole last loop (and the initialization of logvect) can be replaced with: logvect = (p_0yx)/(p_yx) But back to the errors.. and some more Rness... could the following code... p_0y <- matrix(nrow = max(y) - min(y), ncol = 1) i = min(y) while (i <= max(y)) { p_0y[i - min(y), ] = (length(which(y1 == i))/50) i <- i + 1 } maybe be replaced more correctly with? p_0y <- numeric(max(y) - min(y) + 1) p_0y[sort(unique(y1)) - min(y1) + 1] = table(y1)/50 p_0y <- matrix(p_0y, ncol = 1) (similar rethinking of the rest of your code could eliminate the rest of the loops as well)
{ "language": "en", "url": "https://stackoverflow.com/questions/7629097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Chart my Y axis dont show right numbers? chs=800x300 &chxl=1:|10:00|11:00|19:30|2:|Tidspunkt|3:|Kcal| &chxt=y,x,x,y &cht=lc &chco=3072F3 &chds=3735.6 &chd=t:1198,2663,3396 &chxr=0,599,3429.96 &chdl=Energi &chdlp=b &chls=1|1|1 &chma=5,5,5,25 &chm=o,000000,0,-1,5|o,000000,1,-1,5|o,000000,2,-1,5 Is what i have.. test it here: http://code.google.com/intl/sv-SE/apis/chart/image/docs/chart_playground.html 10:00 should be 1198 11:00 should be 2663 19::30 should be 3396 Which it is, but in the chart it is not displaying right. Look at the 10:00 dot its above 2500, but the value is only 1198? What should be fixed here? This has a bounty of 250 and is relatively easy for those who know about Google charts A: I changed the following values to this and it seems to work: &chds=599,3429.96 You had a problem where the axis was scaled differently than your data. The chxr should have the same range as chds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Interacting with the database using layers of separation (PHP and WordPress) I quite often see in PHP, WordPress plugins specifically, that people write SQL directly in their plugins... The way I learnt things, everything should be handled in layers... So that if one day the requirements of a given layer change, I only have to worry about changing the layer that everything interfaces. Right now I'm writing a layer to interface the database so that, if something ever changes in the way I interact with databases, all I have to do is change one layer, not X number of plugins I've created. I feel as though this is something that other people may have come across in the past, and that my approach my be inefficient. I'm writing classes such as Table Column Row That allow me to create database tables, columns, and rows using given objects with specific methods to handle all their functions: $column = new \Namespace\Data\Column ( /* name, type, null/non-null, etc... */ ); $myTable = new \Namespace\Data\Table( /* name, column objects, and indexes */ ); \Namespace\TableModel.create($myTable); My questions are... Has someone else already written something to provide some separation between different layers? If not, is my approach going to help at all in the long run or am I wasting my time; should I break down and hard-code the sql like everyone else? If it is going to help writing this myself, is there any approach I could take to handle it more efficiently? A: You seem to be looking for an ORM. Here is one : http://www.doctrine-project.org/docs/orm/2.0/en/tutorials/getting-started-xml-edition.html A: To be honest, I'd just hard-code the SQL, because: * *Everyone else does so too. Big parts of WordPress would need to be rewritten, if they would ever wish to change from MySQL to something else. It would just be a waste of time to write your perfect layer for your plugin, if the rest of the whole system still only works with hard-coded SQL. *We don't live in a perfect world. Too much abstraction will - soon or late - end up in performance and other issues, which I don't even think of yet. Keep it simple. Also, using SQL you can benefit from some performance "hacks", which maybe won't work for other systems. *SQL is a widely accepted standard and can already be seen as abstraction layer. for example there's even the possibility to access Facebook's Graph via SQL-like syntax (see FQL). If you want to change to another data-source, you'll probably find some layer wich supports SQL-syntax anyways! In that sense, you could even say SQL already is some kind of abstraction layer. But: if you decide to use SQL, be sure to use WordPress' $wpdb. Using that, you're on the safe side, as WordPress takes care of connecting to the database, forming the queries, etc. If, one day, WordPress will decide to change from databases to something else, they'll need to create a $wpdb-layer to that new source - for backwards compatibility. Also, many general requests already are in $wpdb as functions (such as $wpdb->insert()), so there's no direct need to hard-code SQL. If however, you decide to use such an abstraction layer: Wikipedia has more information. Update: I just found out that the CMS Drupal uses a database abstraction layer - but they still use SQL to form their queries, for all the different databases! I think that shows pretty clearly, how SQL can already be used as an abstraction layer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set streetView in my mapview android application? I have another same questions on Stackoverflow, but the don't show any accepted answers ! How do I set streetView in my mapview ? I am using Google API platform 2.2 ? A: You can use the setStreetView method and give on as an argument to it. Check this out: Street View A: public class StreetDetail extends FragmentActivity implements OnStreetViewPanoramaReadyCallback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_street_detail); StreetViewPanoramaFragment streetViewPanoramaFragment = (StreetViewPanoramaFragment) getFragmentManager().findFragmentById(R.id.streetviewpanorama); streetViewPanoramaFragment.getStreetViewPanoramaAsync(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { return super.onContextItemSelected(item); } @Override public void onStreetViewPanoramaReady(StreetViewPanorama streetViewPanorama) { streetViewPanorama.setPosition(new LatLng(37.4083836,-122.1472079)); } } Add a fragment like this to your activity. <fragment android:name="com.google.android.gms.maps.StreetViewPanoramaFragment" android:id="@+id/streetviewpanorama" android:layout_width="match_parent" android:layout_height="300dp" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7629106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customizing an image gallery in android I swear, this control has been the bane of my existance this week. Just FYI, I have pretty basic OO/Java skills, I've mainly been using xml to create layouts, but I need to use the gallery control. I've finally got the sample code working from the sdk, but one thing remains a mystery despite looking here, googling elsewhere, etc., there seems to be no clear answer on how you exactly manipulate the attributes of individual images within the gallery. I keep looking for an example of a template that I could implement, but see nothing. Really, I'm not looking for anything fancy, I just want the images to scale properly within a fixed height gallery control, and surround each image with a 1dip light border, and keep each of them about 4dip apart from one another, that's about it. But for the life of me I'm just not seeing how to make these customizations, and I'm starting to tear my hair out! :-/ Any help or reference to how to do this with some actual examples would be priceless! A: Yeah, just to continue on your own answer. The getView() method of the adapter is the place where you'll do anything you want with the images, i.e. set up borders, layout params, lazy loading, etc. As long as the method returns the View you've made changes to, it should work just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Working with 1bpp images I have a "performance critical" operation where I need to work with 1bpp images. Actually I'm using the Bitmap class and I'm doing, each iteration of a graphic update cycle, a copy of the bitmap inside the byte array. Watching my task manager, this is not that I can keep doing: it uses 2% cpu all time, I think it's quite a lot for something like an utility program. I need to waste less memory as possible and almost 0 cpu. The image is 160x43, quite small. Why I am not using directly the byte array? Easy: I would like to write over it, do some common operations which I don't want to rewrite by myself. I can use obviusly a different image class (from wpf for example, I don't know). I need the possibility to work with a 1bpp image. Offtopic: I have the same "problem" with a 32bpp image, I need a way to work with it as an image while it is a byte array, I can't make a copy of my bytes each time!!! I'm wasting cpu in this way. A: You should use Bitmap.LockBits to get the underlying memory of the bitmap pinned (so the friendly garbage collector won't move it around for you). As an example, this small program loads a png, sets a simple pixel pattern, and saves the resulting image: unsafe void Main() { Bitmap bm = (Bitmap)Image.FromFile("D:\\word.png"); var locked = bm.LockBits(new Rectangle(0,0,bm.Width, bm.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format1bppIndexed); try { byte v = 0xaa; byte* pBuffer = (byte*)locked.Scan0; for(int r = 0 ; r < locked.Height ; r++) { byte* row = pBuffer + r*locked.Stride; for(int c = 0 ; c < locked.Stride ; c++) row[c] = v; } } finally { bm.UnlockBits(locked); } bm.Save("D:\\generated.png"); } LockBits will have an overhead depending on whether it needs to convert the internal memory representation to what you request (so it might matter where you get it from). As alwyas with performance, measure and profile to find your bottlenecks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Conditional link display in rails I have a filter bar on my page. The bar should always be in place, however only when I'm on the detail page I want to show a link <- back to list inside of it. Otherwise the filter bar should be empty. What is the most elegant way of doing this in rails 3 or 3.1? Thanks Thomas A: To return to previous page you can use link_to "Back", :back To show or hide the link you can use the controller_name and action_name methods with a if/unless conditional. A: From your question and the comment, you have the following structure: application.html.erb: ... <section id="filter-bar"> <section id="filter"></section> </section> I see there two different options how to include your link conditionally: * *By doing an if-then in your file application.html.erb *By including a yield with a symbol that denotes the context. Here is the pseudo-code for that: * *solution application.html.erb: ... <section id="filter-bar"> <section id="filter"> <% if controller_name == 'user' && action_name == 'show' %> <%= link_to "Back", :index %> <% end %> </section> </section> *solution application.html.erb: ... <section id="filter-bar"> <section id="filter"> <%= yield(:filter) %> </section> </section> view.html.erb: <%- content_for :filter do %> <%= link_to "Back", :index %> <% end %> ... index.html.erb: // No content_for section in the file, so it will be empty here. The first solution is simpler, much more condensed, but all the information if something is included or not is in one file. If that is changed a lot, that may be a hotspot in your application. The second is more object-oriented, but perhaps more to change and think about. But both will working for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7629109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }