text
stringlengths
8
267k
meta
dict
Q: Why doesn't this Java enum code compile? enum itProfs { private int sal; DEVELOPER(30), ANALYST(20); itProfs(int sal){ this.sal = sal; } public int getSal(){ return sal; } } What is the reason? A: You should put enumeration values first. enum itProfs { DEVELOPER(30), ANALYST(20); private int sal; itProfs(int sal){ this.sal = sal; } public int getSal(){ return sal; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular expression to match everything between first occurrences of two words, both of which appear more than once I want to parse this json and pull out everything that appears between the first occurrence of the word feed and the first instance of the word widget_standard. I figure that this should be easy enough but my regex actually matches everything between the first occurrence of feed and the second occurrence of widget_standard. What do I have to do to my regex /(feed=http.*widget_standard)/i to only match up to (and including) the end of the first occurrence of the word widget_standard? A: Use the lazy star match .*? like this: /(feed=http.*?widget_standard)/i
{ "language": "en", "url": "https://stackoverflow.com/questions/7509325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Repeat output x amount of times to the right and down I am almost on track here. I need to output if the user enters 5 or any number, the program should display the following: xxxxx xxxxx xxxxx xxxxx xxxxx 5 to the right going down 5 times. I have the right idea so far. But i am not sure how to specifiy it to repeat the the xxxxx going down 5 times as well. I tried making a forloop but it didnt work as well as this. #include <iostream> using namespace std; int main() { int inputInteger = 0; char letterX = 'x'; cout << "input a integer" << endl; cin >> inputInteger; for (int i=0; i<=inputInteger; i++) { cout << letterX; if ( i == inputInteger) { cout << endl; i = 0; } } return 0; } A: Use two loops: for (int i=0; i!=inputInteger; ++i) { for (int j=0; j!=inputInteger; ++j) { cout << letterX; } cout << endl; } A: Use a loop within a loop, the outer one looping over the lines to be printed and the inner one looping over the characters. Don't get fancy here; there's no need for getting fancy here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Differences b/w Intent dispatch system and Foreground dispatch system Can anyone tell the differences between Foreground dispatch system and Intent dispatch system? when should i go for Foreground dispatch system? A: The intent dispatch system is to launch a program from scratch. For instance, you turn your phone on and hover it over a tag. The phone launches an intent, identifying it as a Mifare card. Your app has an intent dispatch for Mifare cards, so it is one of the apps that can be selected. If your intent dispatch is specific enough(compared to other apps), it will be the only app to select, and will run at that point. Foreground dispatch is used by your app while it is running. This way, your app won't be turned off if another app has a similar intent dispatch setup. Now with your app running, it can discover a tag and handle the intent over other apps on the phone, and the phone will not prompt you to select from a bunch of apps that have a similar intent dispatch. I hope that was not to confusing!
{ "language": "en", "url": "https://stackoverflow.com/questions/7509340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: document.write() and Ajax - Doesn't work, looking for an alternative I recently asked a question here, and received a great response (which I will shortly be accepting the most active answer of, barring better alternatives arise) but unfortunately it seems the of the two options suggested, neither will be compatible with Ajax (or any dynamically added content that includes such "inline-relative jQuery") Anyways, my question pertains to good ole' document.write(). While a page is still rendering, it works great; not so much when an appended snippet contains it. Are there any alternatives that won't destroy the existing page content, yet still append a string inline, as in where the call is occurring? In other words, is there a way/alternative to document.write() that when called post-render, doesn't destroy existing page content? An Ajax friendly version so to speak? This is where I'm going: var _inline_relative_index = 0; function $_inlineRelative(){ // i hate non-dedicated string concatenation operators var inline_relative_id = ('_inline_relative_{index}').replace('{index}', (++_inline_relative_index).toString()); document.write(('<br id="{id}" />').replace('{id}', inline_relative_id)); return $(document.getElementById(inline_relative_id)).remove().prev('script'); } And then: <div> <script type="text/javascript"> (function($script){ // the container <div> background is now red. $script.parent().css({ 'background-color': '#f00' }); })($_inlineRelative()); </script> </div> A: you have access to the innerHTML property of each DOM node. If you set it straight out you might destroy elements, but if you append more HTML to it, it'll preserve the existing HTML. document.body.innerHTML += '<div id="foo">bar baz</div>'; There are all sorts of nuances to the sledgehammer that is innerHTML, so I highly recommend using a library such as jQuery to normalize everything for you. A: You can assign id to the script tag and replace it with the new node. <p>Foo</p> <script type="text/javascript" id="placeholder"> var newElement = document.createElement('div'); newElement.id='bar'; var oldElement = document.getElementById('placeholder'); oldElement.parentNode.replaceChild(newElement, oldElement); </script> <p>Baz</p> And if you need to insert html from string, than you can do it like so: var div = document.createElement('div'); div.innerHTML = '<div id="bar"></div>'; var placeholder = document.getElementById('placeholder'), container = placeholder.parentNode, elems = div.childNodes, el; while (el = elems[0]) { div.removeChild(el); container.insertBefore(el, placeholder); } container.removeChild(placeholder);
{ "language": "en", "url": "https://stackoverflow.com/questions/7509341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Performance tuning-Should i use loop or 'OR' to query a bunch of stuff For example, I have a table with 2 columns (int)id and (varchar)name. And I have 10 id to get each one's name. Considering performance, Shall I query them one by one in a loop or query them with statement like WHERE ID= N OR ID= M... OR...? A: You should definitely batch the queries into one call. A general rule of thumb for efficiency is to minimize the number of queries you make to MySQL. One query for this is way faster than ten. But you don't have to use OR for this, there is a special syntax for it: SELECT ... WHERE id IN (1,2,3,4,5) This means the same thing as SELECT ... WHERE id=1 OR id=2 OR id=3 OR id=4 OR id=5
{ "language": "en", "url": "https://stackoverflow.com/questions/7509344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Making a non-child div appear as a child div I want to place 2 divs on my page such it looks that the 2nd div is inside the 1st one. Also the 1st div should react to the growing size of 1st second. But in the code they shouldn't have parent-child relationship(i.e, 2nd div not really inside the 1st div tags). I don't want 2nd div to be placed inside 1st because I am updating the 1st div via ajax and the second should remain intact. Would prefer a pure CSS solution if there exists any.. A: Use position:absolute; on the 2nd div. A: Try this HTML : <div id="container"> <div id="div1">Div 1</div> <div id="div2">Div 2</div> </div> CSS : #div1 { min-height:200px; border:3px solid black; } #div2 { min-height:100px; border:3px solid black; position: relative; top: -150px; left: 1%; width:97%; } Example : http://jsfiddle.net/kkJZR/
{ "language": "en", "url": "https://stackoverflow.com/questions/7509347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to draw an oval speech bubble programmatically on iPhone? The technique shown in a similar question is a rectangular bubble. How to draw one in an oval shape? i.e.:     A: I would do it in two iterations. First get the context and begin a path. Fill an ellipse and then a custom path that encloses a triangle with three lines. I assumed the following dimensions: 70 width, 62 height. Override draw rect in a subclass of UIView and instantiate in a subclassed UIViewController: -(void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(ctx, 0.0, 0.0, 1.0, 1.0); CGContextFillEllipseInRect(ctx, CGRectMake(0.0, 0.0, 70.0, 50.0)); //oval shape CGContextBeginPath(ctx); CGContextMoveToPoint(ctx, 8.0, 40.0); CGContextAddLineToPoint(ctx, 6.0, 50.0); CGContextAddLineToPoint(ctx, 18.0, 45.0); CGContextClosePath(ctx); CGContextFillPath(ctx); } Produces this in the iPhone simulator when added against a gray backdrop: This second code example will almost duplicate what you produced above. I implemented this using flexible sizes that could be supplied to the UIView frame when you instantiate it. Essentially, the white portion of the speech bubble is drawn with a black stroke over lay to follow. -(void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGRect aRect = CGRectMake(2.0, 2.0, (self.bounds.size.width * 0.95f), (self.bounds.size.width * 0.60f)); // set the rect with inset. CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0); //white fill CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0); //black stroke CGContextSetLineWidth(ctx, 2.0); CGContextFillEllipseInRect(ctx, aRect); CGContextStrokeEllipseInRect(ctx, aRect); CGContextBeginPath(ctx); CGContextMoveToPoint(ctx, (self.bounds.size.width * 0.10), (self.bounds.size.width * 0.48f)); CGContextAddLineToPoint(ctx, 3.0, (self.bounds.size.height *0.80f)); CGContextAddLineToPoint(ctx, 20.0, (self.bounds.size.height *0.70f)); CGContextClosePath(ctx); CGContextFillPath(ctx); CGContextBeginPath(ctx); CGContextMoveToPoint(ctx, (self.bounds.size.width * 0.10), (self.bounds.size.width * 0.48f)); CGContextAddLineToPoint(ctx, 3.0, (self.bounds.size.height *0.80f)); CGContextStrokePath(ctx); CGContextBeginPath(ctx); CGContextMoveToPoint(ctx, 3.0, (self.bounds.size.height *0.80f)); CGContextAddLineToPoint(ctx, 20.0, (self.bounds.size.height *0.70f)); CGContextStrokePath(ctx); } A: I have another way - however I dont have any time to properly explain it. However, my example was written in .NET for use in a Windows application. My version creates the entire speach bubble as 2D Polygon Mesh and is partially customizable. It is a single drawn path instead of multiple parts. While our platforms are not the same - the technique uses common math routines and procedural loop. I believe the technique could be translated to other programming languages or platforms. Private Sub Generate(ByVal Resolution As Integer, Optional ByVal SpeachPointerAngle As Integer = (45 * 3), Optional ByVal PointerBend As Decimal = 15) 'Generated the same way we create vector (wireframe) mesh for an Ellipse but... '... at a predefined defined angle we create 'the size of the Pointer TIP/Corner portion of the speach bubble 'in relation to the EDGE of the ELLIPSE (average) Dim SpeachPointerSize As Integer = 30 If PointerBend > 10 Then PointerBend = 10 If PointerBend < -10 Then PointerBend = -10 'as a variable offset that should be limited to max +/- -15 to 15 degrees relative to current angle as a safe range '- were speach pointer angle determins which side the the pointer appears Dim PointerOffsetValue As Decimal = PointerBend Dim ActualPointerAngle As Decimal 'SpeachPointerAngle = 360 - SpeachPointerAngle ' adjust orientation so that 0 degrees is SOUTH 'Ellipse Size: Dim Size_X As Decimal = 80 Dim Size_Y As Decimal = 50 If Resolution < 30 Then Resolution = 30 Dim Result As Vector2() 'size of each angle step based on resolution (number of vectors ) - Mesh Quality in otherwords. Dim _Step As Decimal = 360 / Resolution 'Our current angle as we step through the loop Dim _CurrentAngle As Decimal = 0 'rounded values Dim _LastAngle As Decimal = 0 Dim _NextAngle As Decimal = _Step Dim SpeachDrawn As Boolean = False ' prevent creating more than 1 point to be safe Dim I2 As Integer = 0 'need a stepper because of skipped IDS 'build the ellipse mesh For i = 0 To Resolution - 1 _LastAngle = _CurrentAngle - 15 _NextAngle = _CurrentAngle + 15 ActualPointerAngle = _CurrentAngle 'side ActualPointerAngle += PointerOffsetValue ' acual angle of point Dim EX As Decimal = System.Math.Cos(Math.Deg2Rad(_CurrentAngle)) * Size_X Dim EY As Decimal = System.Math.Sin(Math.Deg2Rad(_CurrentAngle)) * Size_Y 'Point extrusion size ( trying to be even size all around ) Dim ExtrudeX As Decimal = System.Math.Cos(Math.Deg2Rad(_CurrentAngle)) * (Size_X + SpeachPointerSize) Dim ExtrudeY As Decimal = System.Math.Sin(Math.Deg2Rad(_CurrentAngle)) * (Size_Y + SpeachPointerSize) 'is Pointer angle between Last and Next? If SpeachPointerAngle > _LastAngle And SpeachPointerAngle < _NextAngle Then If (SpeachDrawn = False) Then ' the point for the speachbubble tip Array.Resize(Result, I2 + 1) Result(I2) = New Vector2(ExtrudeX, ExtrudeY) SpeachDrawn = True I2 += 1 Else 'skip End If Else 'normal ellipse vector Array.Resize(Result, I2 + 1) Result(I2) = New Vector2(EX, EY) I2 += 1 End If _CurrentAngle += _Step Next _Vectors = Result End Sub The above code generated this - drawn to a bitmap using GDI+ [DrawPolygon/FillPolygon]: https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/380262_10151202393414692_590995900_n.jpg (Sorry - I can't post the image here directly as I have never posted here before. I don't have the reputation yet ) This is a Primitive in a Graphics Assembly I am developing for .NET which uses my own Vector2. This speach bubble supports transparency when drawn - as it is a single polygon shape instead of multiple shapes. Basically we draw an ellipse programatically and then extrude a speach point out on a desired side of the ellipse. A similar approach could be applied using PointF structures instead. All shapes in the code are generated around Origin 0,0. Arrays are also resized incrementally as vectors are added prevent gaps in the array. EG - the center of the speach bubble is Origin 0.0. I apologize for not explaining my code properly - I just don't have the time. But it probably isnt too hard to understand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: IClassFactory failed due to the following error: 8001010a This is working fine with Visual Studio's server but when the server is changed to IIS, it throws: Creating an instance of the COM component with CLSID {00020906-0000-0000-C000-000000000046} from the IClassFactory failed due to the following error: 8001010a. object initial_limits = 0; object missing = System.Reflection.Missing.Value; object Visible = true; object openfilename = @"C:\letters\Templates\" + template_src_dropdown.SelectedValue + ".doc"; current_date = DateTime.Now.Date.ToString("dd/MM/yyyy"); object savefilename = @"C:\letters\Letters\" + reference_id + ".doc"; ApplicationClass WordApp = new ApplicationClass(); Document WordDoc = new Document(); Document docActive = null; WordDoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing); //Document //WordDoc = WordApp.Documents.Open(ref openfilename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); /* if (new_file_chkbox.Checked == true) { WordDoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing); } else { WordDoc = WordApp.Documents.Open(ref openfilename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } */ try { docActive = WordApp.ActiveDocument; Bookmark bookmark1; bookmark1 = docActive.Bookmarks.Add("word_content", ref missing); Range rng_bookmark1 = bookmark1.Range; rng_bookmark1.Text = reference_id + "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + current_date; rng_bookmark1.Text += employee_list_word + vendor_list_word; rng_bookmark1.Text += "\n" + subject_txtbox.Text + "\n\n"; rng_bookmark1.Text += "\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + designation_dropdown.SelectedValue + "\n"; rng_bookmark1.Text += "\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + department_dropdown.SelectedValue + "\n"; rng_bookmark1.Text += cc_employee_list_word + cc_vendor_list_word; try { WordDoc.SaveAs(ref savefilename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); WordApp.Visible = true; } catch (Exception ex) { Label1.Text = ex.Message; //MessageBox.Show(ex.Message); } finally { WordApp.Quit(ref missing, ref missing, ref missing); } A: VS server is development server and IIS is deployment server. This is simple to understand that in web application you cant get the features of desktop application because if that happens then no one gonna get a licenced version of MS Word. It ll becum multicuser then... Better USE OpenXml ... Good examples of openXml are provided in Code project.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7509349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Need help with implementing Railscast 198 in Rails 3 I have been trying to implement Ryan Bates Railscast 198 into rails 3 for like 4 days... at least at night if you know what I mean. Anyway, here is the code I have right now: User controller actions (Devise setup to show the different states of approved): def index if params[:approved] == "false" @users = User.find_all_by_approved(false) elsif @users = User.find_all_by_approved(true) else @users = User.all end end def update @user = User.find(params[:id]) respond_to do |format| if @user.update_attributes(params[:user]) format.html { redirect_to root_path flash[:notice] = "User was successfully updated." } else format.html { render :action => "edit" } end end end def edit_individual @users = User.find(params[:user_ids]) end def update_individual @users = User.update(params[:users].keys, params[:users].values).reject { |p| p.errors.empty? } if @users.empty? flash[:notice] = "Users updated" redirect_to users_url else render :action => "edit_individual" end end end My User#index <h1> Users</h1> <%= link_to "All Users", :action => "index" %> | <%= link_to "Users awaiting approval", :action => "index", :approved => "false"%> | <%= link_to "Approved Users", :action => "index", :approved => "true" %> <%= form_tag edit_individual_users_path, :method => :put do %> <table> <tr> <th>Email Address</th> <th>Approved</th> <th></th> </tr> <% for user in @users %> <tr> <td> <%= user.email %></td> <td><%= check_box_tag user.id %></td> <td> <%= link_to "Edit", edit_user_path(user) %></td> </tr> <% end %> <p><%= submit_tag "Edit Checked" %></p> </table> <% end %> And the User#edit_individual <%= form_tag update_individual_users_path, :method => :put do %> <% for user in @users %> <%= fields_for "users[]", user do |f| %> <h2><%=h user.name %></h2> <p><%= check_box_tag user.id %></p> <% end %> <% end %> <p><%= submit_tag "Submit" %></p> <% end %> routes.rb devise_for :users resources :users do collection do post :edit_individual put :update_individual end end end So I handled the basic by googling: fields_for needs an "=" stuff like that. #index shows fine but if I check a checkbox and then hit the edit checked button I get the following error: ActiveRecord::RecordNotFound in UsersController#update Couldn't find User with id=edit_individual Any ideas??? thanks so much A: Please check your routes.rb and controller code, as it's quite a bit off from the code on Railscast 198's page: http://railscasts.com/episodes/198-edit-multiple-individually It's best to just copy it in if you're new to rails and adjust for using users instead of products. Then go through it to try to understand what it does.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Mainform Button Navigation childform filled in panel mainform I have a main form with main panel and filling child form in the main panel. I want some buttons in toolbar to navigate records based on Data Table created in the child form. Problem is I do not know how to accomplish this. Any code or guide to would be helpful. Thanks in advance. So far I have done following: Main form: Tree list: click link to show child form which is added in the panel in mainform Child form: Form load event Datatable dt = new Datatable(); dt = DataAccess.GetStaff(); //Recieve data from class with query executed gridStaff.DataSource = dt; How can I pass "dt" to public method then code the "Next" button in toolbar in the main form navigate. Next record is based on "dt" datatable (Is it possible?) or can I pass grid to public to navigate it. (I used extragrid devexpress). Or Show way to accomplish that issue. Thank you very much. A: Read this link to learn a bit about datagrids and navigators: BindSourceBindingNavCS You can also watch this video SmartClient: Data GridView Getting Started After that article and that movie you should have a basic understanding about which controls and objects to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use cluster and node.js to run both an HTTP and HTTPS server So I have the following code in my app.js file: http.createServer(function(request, response) { // code }).listen(80); // var options = ... https.createServer(options, function (request, response) { // code }).listen(443); How do I use cluster to run in a single process both the server objects? Thanks A: Cluster API will actually run 2 servers as 2 processes. There question should sound "how to configure connect or express to listen to 2 ports"
{ "language": "en", "url": "https://stackoverflow.com/questions/7509372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Maintaining state between pages in seam I have a xhtml page with Search criteria and search results. Clicking on search button will dynamically update the results on the same page. I have a controller for search/results xhtml in Page Scope. There is an edit button in every record in the search results. Clicking on the edit button will open a new page(new controller in Page scope). Once I edit and save I want to come back to the search criteria page with search resutls. I can store the search criteria in session and requery and display the results. I looked at conversation and I am not sure if I can use it in this scenario? Any ideas other than dumping the data in session for this scenario? A: Pass the search criteria to the edit view as well (but don't display them or something) and then let the edit view pass it back to the search view once editing is finished. A: If you want to persist data between two pages, you have many ways: 1) String parameters 2) Session data 3) Long running Conversation 4) Serialize your data elsewhere (DB or other). Since you are talking about "saving" I may think you are saving your data in a database. If you have persisted your data in the second page in some way you can just query for them. Otherwise you can use session and conversation, the second has a "smaller" and defined scope. You can decide when to create one and to create destroy. Simply put a in the first page pages.xml and create a bean with conversation scope. The session scope will keep your data in your session scoped component until you close your browser. Hope this helps. A: I would go with the session scoped bean. If you use a search bean you can go anywhere in your application and maintain your search state, also it lends itself to saving searches in the database (so users can save searches between sessions). @Scope(ScopeType.SESSION) @Name("someRandomSearch") public class SomeRandomSearch { private SearchObj1 userSelection1; private List<SearchObj1> searchCriteriaList1; private SearchObj2 userSelection2; private List<SearchObj2> searchCriteriaList2; private String randomUserInput; // getters/setters, some helper classes, cascade dropdown stuff, etc..... // clear search criteria public void reset(){ this.userSelection1 = null; this.userSelection2 = null; this.randomUserInput = null; } } Just make sure to implement equals method in your model classes - maybe that's obvious, but when I first started using Seam I missed this little tidbit and it took forever to figure out why we couldn't hold onto dropdown selections in our search pages. A: If when you say "open a new page", you mean navigate to another page in the same browser window/tab, then a Conversation is the ideal method for storing the search state. Depending on your detailed use case, you might prefer to setup nested conversations (when you click on the edit). You might also want to setup a pageflow to manage that particular navigation logic. See the official documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: database for google type searches We need to be able to perform fast searches against 10 million tweets we have stored off. Any suggestions for a good database to use for this? We'd prefer to be able to do regular expressions searches but it's sufficient to be able to find all entries that contain a given word. thanks - dave A: Answer at Microsoft MSDN forum - database for bing type searches Full-Text queries perform a linguistic search against this data, operating on words and phrases based on rules of a particular language. A LIKE query against millions of rows of text data can take minutes to return; whereas a full-text query can take only seconds or less against the same data, depending on the number of rows that are returned. We can use Full-Text Search to perform a fuzzy search and then use LIKE clause to return the records that have an exact match of our search conditions. For more information, please refer to the following links: Full-Text Search Overview: http://msdn.microsoft.com/en-us/library/ms142571.aspx SQL Server 2008 Full-Text Search: Internals and Enhancements http://technet.microsoft.com/en-us/library/cc721269(SQL.100).aspx A: You could use http://incubator.apache.org/lucene.net/ which is used by stackoverflow and RavenDB.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Test email piping locally I'm using email piping to parse messages and handle them appropriately in my app. I'd like to figure out a way to test this locally on my Macbook Pro. I use MAMP for development. Any ideas how I can send an email to my local machine that gets piped to a script? Thanks! A: If the thing you need to test is just a pipeline, yourscript <samplemessage.txt does the same thing. A: unless you really want to install a mail server on your local machine, you can't. shouldn't really be hard to set up a test environment on your hosted site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Identifying sequences of repeated numbers in R I have a long time series where I need to identify and flag sequences of repeated values. Here's some data: DATETIME WDIR 1 40360.04 22 2 40360.08 23 3 40360.12 126 4 40360.17 126 5 40360.21 126 6 40360.25 126 7 40360.29 25 8 40360.33 26 9 40360.38 132 10 40360.42 132 11 40360.46 132 12 40360.50 30 13 40360.54 132 14 40360.58 35 So if I need to note when a value is repeated three or more times, I have a sequence of four '126' and a sequence of three '132' that need to be flagged. I'm very new to R. I expect I use cbind to create a new column in this array with a "T" in the corresponding rows, but how to populate the column correctly is a mystery. Any pointers please? Thanks a bunch. A: Use rle to do the job!! It is an amazing function that calculates the number of successive repetitions of numbers in a sequence. Here is some example code on how you can use rle to flag the miscreants in your data. This will return all rows from the data frame which have WDIR that are repeated 3 or more times successively. runs = rle(mydf$WDIR) subset(mydf, WDIR %in% runs$values[runs$lengths >= 3]) A: As Ramnath says, you can use rle. rle(dat$WDIR) Run Length Encoding lengths: int [1:9] 1 1 4 1 1 3 1 1 1 values : int [1:9] 22 23 126 25 26 132 30 132 35 rle returns an object with two components, lengths and values. We can use the lengths piece to build a new column that identifies which values are repeated more than three times. tmp <- rle(dat$WDIR) rep(tmp$lengths >= 3,times = tmp$lengths) [1] FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE This will be our new column. newCol <- rep(tmp$lengths > 1,times = tmp$lengths) cbind(dat,newCol) DATETIME WDIR newCol 1 40360.04 22 FALSE 2 40360.08 23 FALSE 3 40360.12 126 TRUE 4 40360.17 126 TRUE 5 40360.21 126 TRUE 6 40360.25 126 TRUE 7 40360.29 25 FALSE 8 40360.33 26 FALSE 9 40360.38 132 TRUE 10 40360.42 132 TRUE 11 40360.46 132 TRUE 12 40360.50 30 FALSE 13 40360.54 132 FALSE 14 40360.58 35 FALSE A: Two options for you. Assuming the data is loaded: dat <- read.table(textConnection(" DATETIME WDIR 40360.04 22 40360.08 23 40360.12 126 40360.17 126 40360.21 126 40360.25 126 40360.29 25 40360.33 26 40360.38 132 40360.42 132 40360.46 132 40360.50 30 40360.54 132 40360.58 35"), header=T) Option 1: Sorting dat <- dat[order(dat$WDIR),] # needed for the 'repeats' to be pasted into the correct rows in next step dat$count <- rep(table(dat$WDIR),table(dat$WDIR)) dat$more4 <- ifelse(dat$count < 4, F, T) dat <- dat[order(dat$DATETIME),] # sort back to original order dat Option 2: Oneliner dat$more4 <- ifelse(dat$WDIR %in% names(which(table(dat$WDIR)>3)),T,F) dat I thought being a new user that option 1 might be an easier step by step approach although the rep(table(), table()) may not be intuitive initially.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Insert image into SQL Server 2008 Express database without front end application I am working with test data in Visual Studio's server explorer. How would I put images into the database just as test images? I have no front end component built to take care of image uploading. A: You can upload an image into a db (and retrieve it) using byte[] as data type, assuming that in your db corresponding column is a BLOB. So if you load your image with byte[] img = File.ReadAllBytes(your_file) then you can use a query like this INSERT INTO table SET image_col = @par, where par is a parameter whose value is img. A: It will work for SQL server 2008r2...but first u have to create a filestream database. //create databse CREATE DATABASE Archive ON PRIMARY ( NAME = Arch1,FILENAME = 'c:\data\archdat1.mdf'), FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM( NAME = Arch3,FILENAME = 'c:\data\filestream1') LOG ON ( NAME = Archlog1,FILENAME = 'c:\data\archlog1.ldf') GO //table creation Use Archive GO CREATE TABLE [FileStreamDataStorage] ( [ID] [INT] IDENTITY(1,1) NOT NULL, [FileStreamData] VARBINARY(MAX) FILESTREAM NULL, [FileStreamDataGUID] UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE DEFAULT NEWSEQUENTIALID(), [DateTime] DATETIME DEFAULT GETDATE() ) ON [PRIMARY] FILESTREAM_ON FileStreamGroup1 GO //inserting value Use Archive GO INSERT INTO [FileStreamDataStorage] (FileStreamData) SELECT * FROM OPENROWSET(BULK N'C:\Users\Public\Pictures\Sample Pictures\image1.jpg' ,SINGLE_BLOB) AS Document GO
{ "language": "en", "url": "https://stackoverflow.com/questions/7509384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sweave doesn't seem to get .Rnw file encoding right This question arose out of the following question on tex.sx: Sweave generating invalid LaTeX. The problem seems to be that Sweave is not recognizing the encoding of the file, despite the locale being set to UTF-8, and the .Rnw file being saved as UTF-8. The end result is that any .Rnw file that contains non-ASCII characters ends up producing NA in the resultant .tex file. As you can read in the comments to that question, another user doesn't show the problem, with what is apparently an identical setup. (R 2.13.1 on a Mac) Here's a minimal document that fails. Update Based on Aaron's suggestions, I've added sessionInfo to the .Rnw file, and now the real problem reveals itself. When Sweave processes the file, it seems to change the locale. .Rnw file \documentclass{article} \usepackage[utf8]{inputenc} \begin{document} Some non-ascii text: éüáî <<>>= sessionInfo() @ \end{document} Running this through Sweave, produces the following .tex file. The line containing the non-ASCII characters has been converted into NA by Sweave. It seems also that the locale has been changed: Resultant .tex file \documentclass{article} \usepackage[utf8]{inputenc} \usepackage{Sweave} \begin{document} NA \begin{Schunk} \begin{Sinput} > sessionInfo() \end{Sinput} \begin{Soutput} R version 2.13.1 (2011-07-08) Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit) locale: [1] C attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] tools_2.13.1 \end{Soutput} \end{Schunk} \end{document} sessionInfo() from within R.app returns: > sessionInfo() R version 2.13.1 (2011-07-08) Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit) locale: [1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8 Update (Response to Aaron) > text <- readLines("sweave-enc-test.Rnw", warn = FALSE) > enc <- tools:::.getVignetteEncoding(text, convert = TRUE) > > text [1] "\\documentclass{article}" "\\usepackage[utf8]{inputenc}" "\\begin{document}" [4] "Some non-ascii text: éüáî" "\\end{document}" > enc [1] "UTF-8" > iconv(text, enc, "") [1] "\\documentclass{article}" "\\usepackage[utf8]{inputenc}" "\\begin{document}" [4] "Some non-ascii text: éüáî" "\\end{document}" (This is the output from within the R console in R.app.) A: Potential fix: Try putting export LANG=en_US.UTF-8 in your TeXShop script. (Original idea was in the ~/.bashrc file, but apparently TeXShop doesn't load that.) EARLIER: What happens when you put sessionInfo() in the Rnw file? \documentclass{article} \usepackage[utf8]{inputenc} \begin{document} Some non-ascii text: éüáî <<>>= sessionInfo() @ \end{document}
{ "language": "en", "url": "https://stackoverflow.com/questions/7509395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to I make my custom mySQL query to in rails 3? Im trying to display recently added comments from tattoos a user has posted. So If I posted a tattoo, and then user_b posted "hey I like your tattoo" then Im trying to get just the comment. First of all Im using the acts_as_commentable_with_threading gem which doesnt create a foreign key for the table im trying to join. So my controller cant look for tattoo_id, it has to look for commentable_id In the controller I would have to call the Comment model and then pass some SQL stuff into it but apparently I have no clue how to pass custom SQL queries into ruby because even tho my query string works in terminal, I get all sorts of nonsense when trying to use it in rails. Im basically trying to do this: SELECT comments.id FROM comments,tattoos WHERE commentable_id = tattoos.id AND tattoos.member_id = #{current_user} where #{current_user} will be the current_user passed in. A: You don't have to jump through so many hoops to accomplish this. acts_as_commentable assigns a polymorphic association, so you should set it up like this: class Comment < ActiveRecord::Base belongs_to :user belongs_to :commentable, :polymorphic => true end class Tattoo < ActiveRecord::Base has_many :comments, :as => :commentable end class User has_many comments end Then you can access the association as usual: Tattoo.where(:member_id => current_user).first.comments See http://railscasts.com/episodes/154-polymorphic-association for a general tutorial on how polymorphic associations work. It just so happens that this railscast uses exactly :commentable as the polymorphic example, so you should be able to follow along directly if you want. A: I think Ben's approach is best but for future reference if you do come across something more complicated you can always use sql for example: Comment.find_by_sql("SELECT comments.* FROM comments,tattoos WHERE commentable_id = tattoos.id AND tattoos.member_id = ?", current_user)
{ "language": "en", "url": "https://stackoverflow.com/questions/7509397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I get the arguments for any python method? Normally I would use inspect.getargspec, however how do I get the arguments of a method that has been bound? Eg, how do I get the argument names for the method 'foo' as follows: class Foo(object): @memoized def foo(self, arg1, arg2): pass Note that Foo().foo is a memoized object, http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize This means that it is really a functools.partial instance. How do I get the original function or alternatively, obtain the arguments somehow? If I can't, does this indicate a design flaw of the PythonDecoratorLibrary? A: You could add a _wrapped attribute to the partial, which may be what you did already: def __get__(self, obj, objtype): """Support instance methods.""" f = functools.partial(self.__call__, obj) f._wrapped = self.func return f Or you could return self.func instead of the partial if obj is None (i.e. if it's accessed from the class instead of an instance): def __get__(self, obj, objtype): """Support instance methods.""" if obj is None: return self.func else: return functools.partial(self.__call__, obj) The partial's func attribute is the memoized object's __call__ method. If you call it from a Foo instance, then the first argument is set to the instance obj by the partial (see this in Foo().foo.args). Then in memoized.__call__, self.func(*args) works like a poor man's bound method. For the lru_cache, Raymond Hettinger has Python 2 compatible implementations available as ActiveState Code Recipes. There's also a version for least frequently used, in addition to least recently used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to optimize my sql query I want to optimize my sql query which i have written earlier (please see below attached sql query). This query is straight forward and very simple but this needs to be modified as it is failing at performance test, and I know the query is slow. My team lead did mention to me to use 'Pivoting' in the query but i didn't catch his point how to pivot. Please can some one help me in this regard. Declare @tempTable Table( DataSourceColumID int, fDataSourceID int, seqNum int, ColName varchar(50), HeaderName varchar(50) ) Insert into @tempTable (DataSourceColumID, fDataSourceID,seqNum, ColName,HeaderName) Select 101,1,2,'col1', 'column 1' Union ALL Select 102,1,1,'col2', 'column 2' Union All Select 103,1,3,'col6', 'column 6' Union All Select 104,1,4,'col50', 'column 50' select * From @tempTable Declare @ColumnOrderTable table (col_A varchar(10),col_B varchar(10),col_C varchar(10),col_D varchar(10),col_E varchar(10),col_F varchar(10),col_G varchar(10)) Insert into @ColumnOrderTable (col_A ,col_B ,col_C ,col_D ,col_E ,col_F ,col_G ) select Case When seqNum=1 then HeaderName else '' end as col_A, Case When seqNum=2 then HeaderName else '' end as col_B , Case When seqNum=3 then HeaderName else '' end as col_C , Case When seqNum=4 then HeaderName else '' end as col_D , Case When seqNum=5 then HeaderName else '' end as col_E , Case When seqNum=6 then HeaderName else '' end as col_F, Case When seqNum=7 then HeaderName else '' end as col_G from @tempTable select max(col_A) as col_A ,max(col_B) col_B,max(col_C) col_C,max(col_D) col_D,max(col_E) col_E,max(col_F) col_F,max(col_G) col_G From @ColumnOrderTable A: Instead of selecting into a @ColumnOrderTable, you can ommit that step and use a subselect. Simplified original statement SELECT MAX(col_A) , MAX(col_B) , MAX(col_C) , MAX(col_D) , MAX(col_E) , MAX(col_F) , MAX(col_G) FROM ( SELECT Case When seqNum=1 then HeaderName else '' end as col_A, Case When seqNum=2 then HeaderName else '' end as col_B , Case When seqNum=3 then HeaderName else '' end as col_C , Case When seqNum=4 then HeaderName else '' end as col_D , Case When seqNum=5 then HeaderName else '' end as col_E , Case When seqNum=6 then HeaderName else '' end as col_F, Case When seqNum=7 then HeaderName else '' end as col_G FROM @tempTable ) t The subselect itself can be ommitted by converting this statement using the PIVOT function. Using PIVOT SELECT col_A = [1] , col_B = [2] , col_C = [3] , col_D = [4] , col_E = [5] , col_F = [6] , col_G = [7] FROM (SELECT seqNum, HeaderName FROM @tempTable) t PIVOT (MAX(HeaderName) FOR seqNum IN ([1], [2], [3], [4], [5], [6], [7])) pt A: Your approach sucks on many ways: * *First you do a select into a temp table. This means all data has to be copied before the second step stops. *Then you copy again into another temp table *And then finally you make a max. This is a beginner nonono. * *Eliminate BOTH temp tables. Just get rid of them. Even without using pivot or something there simply is no need for that. You can select (max) directly on the pass through SQL. Temp tables are BAD as they mean ALL data must be processed first - in your case you process all data THREE Times. The optimizer can not optimize that away. Second, check Pivot. There is documentation ;) Look it up, come back with specific questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Help with user defined sort function function sort_searches($a, $b) { return ( (isset($b['Class_ID']) && !isset($a['Class_ID'])) || ($b['Results'] && !$a['Results']) || (is_array($a['Results']) && !$a['Results'] && !is_array($b['Results'])) ); } I'm using this function in usort(). The intended effect is that a list of searches will be sorted first by whether they have Class_IDs, and then second by results (with a non-empty array of results > results === false > results === empty array(). So a sorted set of searches would look like: Class_ID with results Class_ID with results === false Class_ID with results === array() No Class_ID with results No Class_ID with results === false No Class_ID with results === array() Currently the functions sorts on results completely fine, but not on whether a search has a Class_ID. usort($searches, 'sort_searches') A: From the PHP docs: The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Your function is not returning an integer. To spell it out, let's say we wanted to write a sorting function for numbers (totally unnecessary, but for the exercise): function sort_nums($a, $b) { if ($a < $b) return -1; // $a is less than $b if ($a > $b) return 1; // $a is greater than $b return 0; // $a is equal to $b }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails helpers causing input placeholder to not work I have some jQuery in my app that removes/shows a placeholder depending on the presence of input in the input field. Here it is below: $(document).ready(function() { $('input').keyup(function() { if ($(this).val().length) { $('label[for='+$(this).attr('name')+']').hide(); } else { $('label[for='+$(this).attr('name')+']').show(); } }); }); However this doesn't work due to my label and text_field form helpers. The HTML below is how the jQuery is set up to work: <label for="user_email">Email</label> <input id="user_email" name="user_email" size="38" type="text" /> Here's the HTML rendered using helpers: <label for="user_email">Email</label> <input id="user_email" name="user[email]" size="38" type="text" /> As you can see, the helpers make it so the HTML for label for and input id don't match up with the HTML for input name. Can anyone help me fix this? A: If you have special characters in attribute values (like [ and ]) then just enclose the value in quotation marks. I.e. instead of the selector label[for=user[email]] (which is broken) use label[for="user[email]"]. The equivalent change in your code would be: $(document).ready(function() { $('input').keyup(function() { if ($(this).val().length) { $('label[for="' + $(this).attr('name') + '"]').hide(); } else { $('label[for="' + $(this).attr('name') + '"]').show(); } }); }); A: I realize that this doesn't answer the rails question, but if you are considering using different code on the jQuery side: I wrote a jQuery plugin for placeholders awhile back. It does 3 color states on the text (placeholder blurred, placeholder focused, user input), custom placeholder text, as well as some mehods to be used for vaidation and form submission (i.e., is the placeholder active, or is it a user input). It provides you with a CSS hook-in as well. Maybe it could help? Project Home Syntax wise you just attach it to a text field or a div and specify the placeholder text. Examples available in the docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parse SQL field into multiple rows How can I take a SQL table that looks like this: MemberNumber JoinDate Associate 1234 1/1/2011 A1 free A2 upgrade A31 5678 3/15/2011 A4 9012 5/10/2011 free And output (using a view or writing to another table or whatever is easiest) this: MemberNumber Date 1234-P 1/1/2011 1234-A1 1/1/2011 1234-A2 1/1/2011 1234-A31 1/1/2011 5678-P 3/15/2011 5678-A4 3/15/2011 9012-P 5/10/2011 Where each row results in a "-P" (primary) output line as well as any A# (associate) lines. The Associate field can contain a number of different non-"A#" values, but the "A#"s are all I'm interested in (# is from 1 to 99). There can be many "A#"s in that one field too. A: Of course a table redesign would greatly simplify this query but sometimes we just need to get it done. I wrote the below query using multiple CTEs; I find its easier to follow and see exactly whats going on, but you could simplify this further once you grasp the technique. To inject your "P" primary row you will see that I simply jammed it into Associate column but it might be better placed in a simple UNION outside the CTEs. In addition, if you do choose to refactor your schema the below technique can be used to "split" your Associate column into rows. ;with Split (MemberNumber, JoinDate, AssociateItem) as ( select MemberNumber, JoinDate, p.n.value('(./text())[1]','varchar(25)') from ( select MemberNumber, JoinDate, n=cast('<n>'+replace(Associate + ' P',' ','</n><n>')+'</n>' as xml).query('.') from @t ) a cross apply n.nodes('n') p(n) ) select MemberNumber + '-' + AssociateItem, JoinDate from Split where left(AssociateItem, 1) in ('A','P') order by MemberNumber; The XML method is not a great option performance-wise, as its speed degrades as the number of items in the "array" increases. If you have long arrays the follow approach might be of use to you: --* should be physical table, but use this cte if needed --;with --number (n) --as ( select top(50) row_number() over(order by number) as n -- from master..spt_values -- ) select MemberNumber + '-' + substring(Associate, n, isnull(nullif(charindex(' ', Associate + ' P', n)-1, -1), len(Associate)) - n+1), JoinDate from ( select MemberNumber, JoinDate, Associate + ' P' from @t ) t (MemberNumber, JoinDate, Associate) cross apply number n where n <= convert(int, len(Associate)) and substring(' ' + Associate, n, 1) = ' ' and left(substring(Associate, n, isnull(nullif(charindex(' ', Associate, n)-1, -1), len(Associate)) - n+1), 1) in ('A', 'P'); A: Try this new version declare @t table (MemberNumber varchar(8), JoinDate date, Associate varchar(50)) insert into @t values ('1234', '1/1/2011', 'A1 free A2 upgrade A31'),('5678', '3/15/2011', 'A4'),('9012', '5/10/2011', 'free') ;with b(f, t, membernumber, joindate, associate) as ( select 1, 0, membernumber, joindate, Associate from @t union all select t+1, charindex(' ',Associate + ' ', t+1), membernumber, joindate, Associate from b where t < len(Associate) ) select MemberNumber + case when t = 0 then '-P' else '-'+substring(Associate, f,t-f) end NewMemberNumber, JoinDate from b where t = 0 or substring(Associate, f,1) = 'A' --where t = 0 or substring(Associate, f,2) like 'A[1-9]' -- order by MemberNumber, t Result is the same as the requested output. A: I would recommend altering your database structure by adding a link table instead of the "Associate" column. A link table would consist of two or more columns like this: MemberNumber Associate Details ----------------------------------- 1234 A1 free 1234 A2 upgrade 1234 A31 5678 A4 Then the desired result can be obtained with a simple JOIN: SELECT CONCAT(m.`MemberNumber`, '-', 'P'), m.`JoinDate` FROM `members` m UNION SELECT CONCAT(m.`MemberNumber`, '-', IFNULL(a.`Associate`, 'P')), m.`JoinDate` FROM `members` m RIGHT JOIN `members_associates` a ON m.`MemberNumber` = a.`MemberNumber`
{ "language": "en", "url": "https://stackoverflow.com/questions/7509406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using MediaPlayer and AVFoundation Framework simultaniously in XCode I'm an inexperienced XCode use and programmer in general so keep that in mind. I'm trying to use the microphone on the iPhone while at the same time allowing the user to play audio while using the "iPod music picker", but when the user selects music and plays it the recorder stops working? I have no idea what is going on here? Also, on a side note, how do you implement forward and back iPod buttons? Thanks so much! A: Sounds like this is an Audio Session issue - you're probably in a mode where you can either play or record, but not both at the same time. Check out the Audio Session Programming Guide which should explain how to configure your session. AVAudioSessionCategoryPlayAndRecord — Use this category for an application that inputs and outputs audio. The input and output need not occur simultaneously, but can if needed. This is the category to use for audio chat applications. AVAudioSessionCategoryAmbient - This category allows audio from the iPod, Safari, and other built-in applications to play while your application is playing audio. You could, for example, use this category for an application that provides a virtual musical instrument that a user plays along to iPod audio.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why can you not throw and catch an Object in Java? Possible Duplicate: What can you throw in Java? Why can't I take an Exception in a reference of Object. I mean consider the following code: try{.......} catch(Object ex){.......} It shows an error, where as we knows that it's possible for all the objects of any class to be referenced by Object. A: The Java Language specification says that only Throwables can be thrown. http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#44043 Every exception is represented by an instance of the class Throwable or one of its subclasses; such an object can be used to carry information from the point at which an exception occurs to the handler that catches it. The language could have been defined differently, but Java tends to define a base type for any kind of thing that is intended to be used in a particular way and defines methods in that base class to support common patterns. Throwable in particular supports chaining and stack trace printing. It would not be possible to chain exceptions as easily if the only thing you knew about an exception was that it was a reference type. A: You can assign a reference of an Exception to an Object without a problem. But Objects can't be thrown or catched. That only works for Throwables. A: So that in catch block you can be sure to get some details on exception like getCause(), getMessage(), getStackTrace(). If its generic Object, you wont have access to these methods without explicit casting, and you wont be still sure that these method actually exist. As its instance of Throwable, you are sure that you can retrieve these details from exception (the object in the catch). A: You can't because only subclasses of Throwable can be thrown. I suppose it would be possible for them to have allowed you to use Object in a catch block, instead -- the only superclass of Throwable -- but what would be the point, since the variable would always refer to a Throwable instance. A: Maybe you are coming from C++ where anything can be thrown, even an int. Java exceptions extend Throwable. Object does not extend it (of course).
{ "language": "en", "url": "https://stackoverflow.com/questions/7509410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to get the AM/PM from the date picker iphone Hi all im using a date picker and priting the time taken from picker in a label.It is working fine.and i want to print the AM/PM selected from picker.is it possible.Can anyone help me..Thanks in advance I used the code below: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"hh-mm"]; selected = [datePicker date]; NSLog(@"saaa%@",selected); NSString *dateString = [dateFormatter stringFromDate:selected]; NSString *message = [[NSString alloc] initWithFormat:@"Daily Reminder: %@", dateString]; [dateFormatter release]; label.text=message; A: Yes, change this: [dateFormatter setDateFormat:@"hh-mm"]; to this: [dateFormatter setDateFormat:@"hh-mm a"]; A: set dateformat like this [dateFormatter setDateFormat:@"hh-mm a"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7509411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Specifying DTD to be used by DocumentBuilders for XML parsing? I am currently writing a tool, using Java 1.6, that brings together a number of XML files. All of the files validate to the DocBook 4.5 DTD (I have checked this using xmllint and specifying the DocBook 4.5 DTD as the --dtdvalid parameter), but not all of them include the DOCTYPE declaration. I load each XML file into the DOM to perform the required manipulation like so: private Document fileToDocument( File input ) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setIgnoringElementContentWhitespace(false); factory.setIgnoringComments(false); factory.setValidating(false); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse( input ); } For the most part this has worked quite well, I can use he returned object to navigate the tree and perform the required manipulations and then write the document back out. Where I am encountering problems is with files which: * *Do not include the DOCTYPE declaration, and *Do include entities defined in the DTD (for example &mdash; / —). Where this is the case an exception is thrown from the builder.parse(...) call with the message: [Fatal Error] :5:15: The entity "mdash" was referenced, but not declared. Fair enough, it isn't declared. What I would ideally do in this instance is set the DocumentBuilderFactory to always use the DocBook 4.5 DTD regardless of whether one is specified in the file. I did try validation using the DocBook 4.5 schema but found that this produced a number of unrelated errors with the XML. It seems like the schema might not be functionally equivalent to the DTD, at least for this version of the DocBook specification. The other option I can think of is to read the file in, try and detect whether a doctype was set or not, and then set one if none was found prior to actually parsing the XML into the DOM. So, my question is, is there a smarter way that I have not seen to tell the parser to use a specific DTD or ensure that parsing proceeds despite the entities not resolving (not just the &emdash; example but any entities in the XML - there are a large number of potentials)? A: Could using an EntityResolver2 and implementing EntityResolver2.getExternalSubset() help? ... This method can also be used with documents that have no DOCTYPE declaration. When the root element is encountered, but no DOCTYPE declaration has been seen, this method is invoked. If it returns a value for the external subset, that root element is declared to be the root element, giving the effect of splicing a DOCTYPE declaration at the end the prolog of a document that could not otherwise be valid. ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7509418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Objective-C - Directly call method from array of objects I'm new to Objective C, and I'm trying to call a method on an array (NSArray) of objects directly like this: [[myPeople objectAtIndex: 0] setName: @"Shane"]; But this doesn't seem to work, and returns a warning saying "Multiple methods named 'setName' found" I can successfully perform the operation in this manner: Person* person = [myPeople objectAtIndex: 0]; [person setName: @"Shane"]; Is my syntax simply incorrect in the first case, or should the second piece of code be used? Or is there a better way that I'm not aware of? Thanks, any help is greatly appreciated A: You can do it to all objects in the array like this: [myPeople makeObjectsPerformSelector:@selector(setName:) withObject:@"Shane"]; A: The first syntax is correct and will work correctly, despite the warning. The compiler is warning you because it can't verify the type of object that you're calling setName: on. The method objectAtIndex: of the NSArray class returns the type id, which is a generic pointer to an Objective-C object of unknown type. So, when you call setName: on the id that is returned, the compiler doesn't know what the actual class of the object is. In your code, there are multiple classes that define the setName: method (possibly as a synthesized setter for a property named name), so it issues a warning. The second code snippet compiles without warning because the id type can be implicitly cast to any other Objective-C pointer type. When you say Person* person = [myPeople objectAtIndex: 0];, you're taking the id returned by objectAtIndex: and casting it (implicitly) to Person*. Then, when you call setName: on that Person, the compiler knows what type you have, so it can verify that the class Person does in fact implement the setName: method. A: if you want to bypass the compiler warning. There are two other approaches then the one you demonstrated. you can call performSelector:withObject on it. [[myPeople objectAtIndex: 0] performSelector:@selector(setName:) withObject: @"Shane"]; usually with this method, you want to make sure it responds to the selector. if ([[myPeople objectAtIndex: 0] respondsToSelector:@selector(setName:)]) another option is to cast the result [(Person*)[myPeople objectAtIndex: 0] setName: @"Shane"]; these should eliminate the compiler warnings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Need help getting sbt 0.10 to choose a local copy of scala 2.9.1.final on Ubuntu What I have so far: .bashrc 2 PATH=/opt/scala-2.9.1.final/bin:$PATH 3 PATH=/opt/sbt:$PATH So my scala-2.9.1.final version is in the /opt folder. The same goes with sbt 0.10. I'm trying to get it to pick my 2.9.1.final instead of 2.8 whatever. I've tried looking. What i've done so far is putting symbolic links in projectname/boot/ directory. ln -s /opt/scala-2.9.1.final scala-2.9.1.final But it doesn't seem to work? I've also tried this build.sbt (https://github.com/VonC/xsbt-template/blob/master/build.sbt) and change the version to 2.9.1.final. How do I get sbt>console to use 2.9.1.final? And how does it build using 2.9.1.final? This is what I get when I type sbt: user@acomputer:~/project/sbt$ sbt [info] Set current project to default-295917 (in build file:/home/user/project/sbt/) > Thank you for your time. A: I'm not experienced sbt user and may only suggest. Seems sbt 0.10.x use scala 2.8.1 itself, so I think sbt console is working by default with this version. But you can build project with targetting on 2.9.1 by specify scala version in you build.sbt file: `scalaVersion := "2.9.1"' (see https://github.com/harrah/xsbt/wiki/Setup "ConfigureBuild") And also you can switch scala version used by sbt console by typing "++ 2.9.1" in sbt prompt. (see https://github.com/harrah/xsbt/wiki/Running) A: Here's an example of an build.sbt in one of my projects. organization := "com.andyczerwonka" name := "esi.intelligence" version := "0.1" scalaVersion := "2.9.1" retrieveManaged := false logLevel := Level.Info jettyScanDirs := Nil seq(webSettings :_*) temporaryWarPath <<= (sourceDirectory in Compile)(_ / "webapp") libraryDependencies ++= { val liftVersion = "2.4-M4" Seq( "net.liftweb" %% "lift-webkit" % liftVersion % "compile->default", "net.liftweb" %% "lift-mapper" % liftVersion % "compile", "org.eclipse.jetty" % "jetty-webapp" % "7.3.0.v20110203" % "provided,jetty", "junit" % "junit" % "4.8" % "test", "ch.qos.logback" % "logback-classic" % "0.9.26", "org.specs2" %% "specs2" % "1.6.1" % "test", "net.databinder" %% "dispatch-http" % "0.8.5", "com.h2database" % "h2" % "1.2.138" ) } Notice the 4th line. This tells sbt that I want to use 2.9.1. sbt will bring it down for me and use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: String encodiing Conversation in JSON response I have a problem of string encoding. Actually I have a application, which is in 5 languages swedish, norwegian, english, finnish and danish. In one of section of my app, I get the review of user so it's possible to come in different language format like the word in swedish nämndes. Now the problem is i get the response of review in JSOn format and the swedish character ä came as &a and it print as &a. i want to print as ä format. same in all language character problem. Please help me... A: I do something like this when Im requesting xml data from myserver. NSString *responseString = [request responseString]; //Pass request text from server over to NSString NSData *capturedResponseData = [responseString dataUsingEncoding:NSUTF8StringEncoding]; Hope it helps. A: Solution finally i change the web service character encoding. The web service Change the special word into UTF8 style encoding like /U00.. When we display in text or label it automatically converted and display specific word.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tab output behavior within a JTextArea I try to be as punctilious as possible in researching before I ask a question, especially one so simple, so bear with me. I have a String that's tab delimited, and when I output it to a JTextArea in Java, I get behavior that looks like this: FirstName LastName PhoneNumber BirthDate Linewrap is turned off with horizontal scrolling enabled. After toiling over the documentation and SA, I'm missing something obvious as to why it's exhibiting this behavior. A: As @kleopatra comments, this is not unexpected. As alternatives, consider JTable or How to Use HTML in Swing Components. Addendum: I previously overlooked setTabSize(). import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; /** @see https://stackoverflow.com/questions/7509429 */ public class TextAreaTabs extends JPanel { public TextAreaTabs() { JTextArea jta = new JTextArea("FirstName\tLastName\tPhoneNumber\tBirthDate"); jta.setTabSize(10); this.add(jta); } private void display() { JFrame f = new JFrame("TextAreaTabs"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(this); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new TextAreaTabs().display(); } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue with Django template 'ifequal' The Below code: {% ifequal username AnonymousUser %} <p>Welcome</p> {% else %} <p> Welcome {{ username }}. Thanks for logging in.</p> {% endifequal %} Shows This: Welcome AnonymousUser. Thanks for logging in. What the? I'm more than a little miffed. I'm pretty sure i don't need to supply extra code for you to understand my problem. I dont think it's an ifequal problem. I have a pretty good handle on that. Username comes from: username = request.user Does this mean username at this point in the code is not a string. Do i have to convert it to a string. A: You need to compare to a string. Use this: {% ifequal smart_str(username).strip() "AnonymousUser" %} Here's the Django documentation on checking equality with ifequal. Ensure your variable is a string, and one that's trimmed of leading and trailing whitespaces as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Rails 3 Devise - Getting " No route matches "/users/sign_out" " No route matches "/users/sign_out" When I am logged in. I just followed ryan bates tutorial to get devise working. My rake routes looks like this. new_user_session GET /users/sign_in(.:format) {:action=>"new", :controller=>"devise/sessions"} user_session POST /users/sign_in(.:format) {:action=>"create", :controller=>"devise/sessions"} destroy_user_session DELETE /users/sign_out(.:format) {:action=>"destroy", :controller=>"devise/sessions"} user_password POST /users/password(.:format) {:action=>"create", :controller=>"devise/passwords"} new_user_password GET /users/password/new(.:format) {:action=>"new", :controller=>"devise/passwords"} edit_user_password GET /users/password/edit(.:format) {:action=>"edit", :controller=>"devise/passwords"} PUT /users/password(.:format) {:action=>"update", :controller=>"devise/passwords"} cancel_user_registration GET /users/cancel(.:format) {:action=>"cancel", :controller=>"devise/registrations"} user_registration POST /users(.:format) {:action=>"create", :controller=>"devise/registrations"} new_user_registration GET /users/sign_up(.:format) {:action=>"new", :controller=>"devise/registrations"} edit_user_registration GET /users/edit(.:format) {:action=>"edit", :controller=>"devise/registrations"} PUT /users(.:format) {:action=>"update", :controller=>"devise/registrations"} DELETE /users(.:format) {:action=>"destroy", :controller=>"devise/registrations"} root /(.:format) {:controller=>"welcome", :action=>"index"} Thanks in advance. A: Routes look correct. Your sign out link should look like this: <%= link_to('Logout', destroy_user_session_path, :method => :delete) %> A: I assume the other answer solved your problem. If you want to know why, check out the section in this setup guide for rails 3.1 with devise. Basically, when you try to HTTP GET the sign out route, it doesn't exist because it's only setup for HTTP DELETE. You can see this in the second column of the routes you pasted in the question. Probably your links were missing the :method => :delete Also in that tutorial, you can see how to setup devise to use the GET method when it is in test mode. Change /config/initializers/devise.rb as follows: # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = Rails.env.test? ? :get : :delete
{ "language": "en", "url": "https://stackoverflow.com/questions/7509437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++: placing an array randomly inside a 2D array I am making a Battleships-like game and need to place a battleship objects into a battlemap array randomly. Except when I do this, the ships are never placed in the bottom right quadrant (but they are successfully placed in the other 3 quadrants), and I don't know why. Basically, I get a random integer between 0 and the length and height of the map and a random direction, then check if the ship will fit there, if it can, place it on the map. But it never places them in the bottom right. void BattleMap::placeRandomly(BattleShip& ship) { bool correct = true; int x_start,y_start,dir; // size_x, size_y denote the length and height of the array respectively int length = ship.getLength(); do{ correct = true; x_start = abs(rand()%(size_x-length)); if(x_start+length > size_x) x_start -= length; y_start = abs(rand()%(size_y-length)); if(y_start+length > size_y) y_start -= length; dir = rand()%2; // 0 for vertical, 1 for horizontal; for ( int i = 0; i < length;i++) { switch(dir){ // Check if there is already a ship in the candidate squares case 0: if(this->at(x_start,y_start+i)){ correct = false; } break; case 1: if(this->at(x_start+i,y_start)){ correct = false; } break; } } }while(!correct); // Place the ships into the array .... } The at() function is this: BattleShip*& BattleMap::at(int x, int y){ if(x > size_x || y > size_y)return 0; // error: invalid initialization of non-const reference of type 'BattleShip*&' from a temporary of type 'int' return board[x*size_y +y]; } A: You are trying too hard to keep the ship from going off the side. Just allow x_start and y_start to be anywhere: x_start = rand()%size_x; y_start = rand()%size_y; And let your at() function return true if it goes off the side: bool BattleMap::at(int x,int y) const { if (x>=size_x || y>=size_y) return true; // regular check for a ship at x,y here }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does the click function not work after I change the class of a button? I have a set of buttons(previous & next) that the user clicks. <a id="prev_btn" class="prev_1" href="#">Previous</a> <a id="next_btn" class="next_1" href="#">Next</a> When the user clicks on the next button(.next_1), it changes the class name of the button to next_2 and changes the the previous button(.prev_1) to prev_2. Once the class name is changed, the click function that is set for prev_2 doesn't work. $('.next_1').click(function() { $('#next_btn').removeClass('next_1').addClass('next_2'); $('#prev_btn').removeClass('prev_1 inactive').addClass('prev_2'); }); $('.prev_2').click(function() { alert('this works'); }); Why does the click function not work after I change the class using jquery? A: That's because the bindings are defined at load. If you want them to work dynamically, bind teh click's via LIVE. $('.prev_2').live('click', function() { alert('hi!'); }); A: It sounds like you are confused about the time of evaluation here; $('.prev_2') gets all elements that currently have a class of 'prev_2', and applies a given action to them; it is not a declaration that stays in effect no matter which elements are added to or removed from this class. If you want a handler that is based on class, you can register an onclick handler at the document level, and test the class of the event target and dispatch accordingly. However, it is cleaner just to register a click function with a specific button and, within that handler, test the class of the button before acting. A: When $('.prev_2').click(...) is executed, the "previous" button does not have the prev_2 class, so it is not assigned the click handler, only thingas which currently have that calss when the .click method is called will have that handler bound. You want to look at the .live jquery function to achive what you are looking for
{ "language": "en", "url": "https://stackoverflow.com/questions/7509439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ninject, binding un-bound types to methods I have an interface ISettings. Many classes will implement this interface. I want to be able to kernel.GetService(typeof(MySettings)) and have it call the type be created from a method. I want to avoid using a type finder to pre-bind all ISettings implementations. I would like to be able to intercept GetService() calls to check if the type is of ISettings. If so, I want to provide a binding for it (method). What can ninject do for me?
{ "language": "en", "url": "https://stackoverflow.com/questions/7509442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a b2Vec2 to a class I have a class that I want to contain a b2Vec2 and an integer. I keep getting an error that says expected specifier-qualifier-list before 'b2Vec2'. I can't figure this out. Please help. @interface mTouch : NSObject { b2Vec2 touchPoint; int cannonNumber; } -(void)setTouchPoint:(b2Vec2)tp; -(void)setCannonNumber:(int)cn; -(b2Vec2)touchPoint; -(int)cannonNumber; @end @implementation mTouch -(id)init { touchPoint = b2Vec2(0, 0); cannonNumber = 0; } -(void)setTouchPoint:(b2Vec2)tp{ touchPoint = tp; } -(void)setCannonNumber:(int)cn{ cannonNumber = cn; } -(b2Vec2)touchPoint{ return touchPoint; } -(int)cannonNumber{ return cannonNumber; } @end A: include box2d and make sure the implementation of this header have the extension .mm instead of .m (for supporting c++).
{ "language": "en", "url": "https://stackoverflow.com/questions/7509443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Smalltalk runtime features absent on Objective-C? I don't know well Smalltalk, but I know some Objective-C. And I'm interested a lot in Smalltalk. Their syntax are a lot different, but essential runtime structures (that means features) are very similar. And runtime features are supported by runtime. I thought two languages are very similar in that meaning, but there are many features on Smalltalk that absent on Objective-C runtime. For an example, thisContext that manipulates call-stack. Or non-local return that unwinds block execution. The blocks. It was only on Smalltalk, anyway now it's implemented on Objective-C too. Because I'm not expert on Smalltalk, I don't know that sort of features. Especially for advanced users. What features that only available in Smalltalk? Essentially, I want to know the advanced features in Smalltalk. So it's OK the features already implemented on Objective-C like block. A: While I'm reasonably experienced within Objective-C, I'm not as deeply versed in Smalltalk as many, but I've done a bit of it. It would be difficult to really enumerate a list of which language has which features for a couple of reasons. First, what is a "language feature" at all? In Objective-C, even blocks are really built in conjunction with the Foundation APIs and things like the for(... in ...) syntax requires conformance to relatively high level protocol. Can you really talk about a language any more without also considering features of the most important API(s)? Same goes for Smalltalk. Secondly, the two are very similar in terms of how messaging works and how inheritance is implemented, but they are also very different in how code goes from a thought in your head to running on your machine. Conceptually different to the point that it makes a feature-by-feature comparisons between the two difficult. The key difference between the two really comes down to the foundation upon which they are built. Objective-C is built on top of C and, thus, inherits all the strengths (speed, portability, flexibility, etc..) and weaknesses (effectively a macro assembler, goofy call ABI, lack of any kind of safety net) of C & compiled-to-the-metal languages. While Objective-C layers on a bunch of relatively high level OO features, both compile time and runtime, there are limits because of the nature of C. Smalltalk, on the other hand, takes a much more top-to-bottom-pure-OO model; everything, down to the representation of a bit, is an object. Even the call stack, exceptions, the interfaces, ...everything... is an object. And Smalltalk runs on a virtual machine which is typically, in and of itself, a relatively small native byte code interpreter that consumes a stream of smalltalk byte code that implements the higher level functionality. In smalltalk, it is much less about creating a standalone application and much more about configuring the virtual machine with a set of state and functionality that renders the features you need (wherein that configuration can effectively be snapshotted and distributed like an app). All of this means that you always -- outside of locked down modes -- have a very high level shell to interact with the virtual machine. That shell is really also typically your IDE. Instead of edit-compile-fix-compile-run, you are generally writing code in an environment where the code is immediately live once it is syntactically sound. The lines between debugger, editor, runtime, and program are blurred. A: Not a language feature, but the nil-eating behaviour of most Objective-C frameworks gives a very different developing experience than the pop-up-a-debugger, fix and continue of smalltalk. Even though Objective-C now supports blocks, the extremely ugly syntax is unlikely to lead to much use. In Smalltalk blocks are used a lot. A: Objective-C 2.0 supports blocks. It also has non-local returns in the form of return, but perhaps you particularly meant non-local returns within blocks passed as parameters to other functions. thisContext isn't universally supported, as far as I'm aware. Certainly there are Smalltalks that don't permit the use of continuations, for instance. That's something provided by the VM anyway, so I can conceive of an Objective-C runtime providing such a facility. One thing Objective-C doesn't have is become: (which atomically swaps two object pointers). Again, that's something that's provided by the VM. Otherwise I'd have to say that, like bbum points out, the major difference is probably (a) the tooling/environment and hence (b) the rapid feedback you get from the REPL-like environment. It really does feel very different, working in a Smalltalk environment and working in, say, Xcode. (I've done both.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7509449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Running Javascript after an MVC Ajax..BeginForm partial postback I've got the following scenario using ASP.NET MVC2 I have a partial view that uses an Ajax.BeginForm to allow a partial postback, with the OnSuccess property of the AjaxOptions pointing to the js function onPartialReloadSuccess. The updateTargetId is housed on a parent View "Application" as referenced in the BeginForm script. This partial view itself renders a number of other partial views, the names of which are generated dynamically based on the model <% using (Ajax.BeginForm("Application", new AjaxOptions { UpdateTargetId = "mainframe", OnSuccess = "onPartialReloadSuccess" })) { %> <div id="breadcrumbs"> <% Html.RenderPartial(Model.Breadcrumbs, Model);%> </div> <div id="action"> <% Html.RenderPartial(Model.CurrentView, Model);%> </div> <% } %> My problem is as follows - after a partial postback the 'onPartialReloadSuccess' js function is successfully called without problem, but non of the javascript contained within the sub-views is re-run. They were initially set up to run after a jQuery $(document).ready()... which obviously won't work on a partial postback My question is this - is there any way to ensure that the javascript on these re-rendered partial views is run? I see a lot of solutions for asp.net forms (using scriptmanager and PageRequestManager), but nothing specific for ASP.NET MVC? thanks in advance for any help A: You could externalize those scripts into separate function(s) and then in the onPartialReloadSuccess function explicitly call this function(s). Also call them in the document.ready so that the initial load also works. A: looks like I found the answer I required at http://adammcraventech.wordpress.com/2010/06/11/asp-net-mvc2-ajax-executing-dynamically-loaded-javascript/ with the following quote explaining the problem I have been tinkering with ASP.NET MVC2 for a while and I had the problem where the MVC2 >Client Validation did not work when I was dynamically loading a partial view through MVC2 >AJAX. Upon further investigation, I discovered that the issue was not limited just to MVC2 >Client Validation, but to all JavaScript that is dynamically loaded through MVC2 AJAX. The >issue has to do with the way that the response is injected into the DOM element – through the >InnerHTML property. Any script block injected into that property will not be executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Deserialization of ArrayList GWT In my application I'm getting some data from a file located in the server. The data is stored in a text file (.obj), so I'm using an rpc to read the file and get the data. The file is read using a third party library http://www.pixelnerve.com/processing/libraries/objimport/ I'm sending the data to the client using ArrayLists, basicly I'm sending this: ArrayList[ArrayList[Vertex3dDTO]] where Vertex3dDTO is an serializable object with contains float parameters. ArrayList[Vertex3dDTO] is contained in another serializable class Face3dDTO, and ArrayList[Face3dDTO] is in the serializable class Group3dDTO. package com.nyquicksale.tailorapp.shared; import java.io.Serializable; public class Vertex3dDTO implements Serializable { float x,y,z; public Vertex3dDTO(){ } public Vertex3dDTO(float x, float y, float z){ this.x = x; this.y = y; this.z = z; } } public class Face3dDTO implements Serializable { ArrayList<Vertex3dDTO> vL = new ArrayList<Vertex3dDTO>(); Vertex3dDTO normal = new Vertex3dDTO(); Vertex3dDTO color = new Vertex3dDTO(); public Face3dDTO(){ } public Face3dDTO(ArrayList<Vertex3dDTO> v) { for(Vertex3dDTO v3dDTO : v){ vL.add(v3dDTO); } updateNormal(); } public class Group3dDTO implements Serializable { ArrayList<Face3dDTO> fL = new ArrayList<Face3dDTO>(); String name; public Group3dDTO(){ } public Group3dDTO(ArrayList<Face3dDTO> f) { for(Face3dDTO f3dDTO : f){ fL.add(f3dDTO); } } } Now, everything is working well in development mode, but when I tested the application in hosted mode, everything I receive as response is: //OK[0,1, ["java.util.ArrayList/4159755760"],0,7] So, I've been checked some other questions and seems the problem is about deserialization, but I've not found anything concrete. The question is what do I have to do to get the app working well in hosted mode? A: To successfully use RPC, your object needs to implement Serializable and should also have a default no arg constructor A: Your object may well be Serializable, but that doesn't equate to something usable by Remote Procedure Calls. You need to implement Serializable, have a default contructor with no arguments (that calls super() if necessary), and a serial version ID, like so: public class MyObject implements Serializable { /** * */ private static final long serialVersionUID = -1796729355279100558L; private Float someValue; public MyObject() { super(); } public MyObject(Float someValue) { super(); this.someValue = someValue; } public Float getSomeValue() { return someValue; } public void setSomeValue(Float someValue) { this.someValue = someValue; } } A: Have you made sure this is a serialization problem? You can write a simple RPC test method to pass an array list of your DTO's over the wire in hosted mode. If I were to bet money on a guess, I would say the problem is those array lists are sent empty in hosted mode. The .obj file read could be the problem. Perhaps in hosted mode the path of file doesn't match as in dev mode(different server configurations perhaps?), since file operations are in a try catch block an exception is most likely swallowed. Long word short, Did you make sure those array lists are not sent empty in hosted mode?
{ "language": "en", "url": "https://stackoverflow.com/questions/7509457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GITHUB setup - no address associated with name I'm trying to setup GitHub on my system and I have done all the installation and key setup process: But during test everything phase getting the following error by command: $ ssh -T git@github.com ssh:github.com:no address associated with name A: It means it doesn't found your HOME/.ssh/id_rsa and id_rsa.pub, and is looking for a HOME/.ssh/config file which could have defined the name 'github.com', as illustrated here. That usually means you don't have defined what HOME is (which isn't defined by default on Windows, see this answer) A: I tried almost everything found on Google related to this question, and nothing seemed to work. I remembered that Windows has made some updates on 'Windows Defender'. I may seem irrelevant but it is not; What worked for me was running Git as Administrator, which i never did before. A: I also faced the same problem and the error was that: I was using the wrong URI, it should be like: ssh -T git@bitbucket.org and not as what was copied for cloning ssh -T git@bitbucket.org:username/repo.git A: I had the same error message. In my case my netbook's wifi switch got bumped and I didn't notice I had no internet connection. So make sure you have internet access if you're getting this error! (duh!) A: If you are working behind proxy, try config ssh to work with the proxy, I encountered the same problem at first and used corkscrew to solve it: http://www.mtu.net/~engstrom/ssh-proxy.php A: I have a client who developed this problem after a Windows 10 update. After a great amount of web searches and trouble shooting, I noticed that his Windows User ID contained spaces, and the error message had said, "S no address associated with name". I noticed that after the space in his name was his middle initial, "S". So I postulated that the user ID was being passed without quotes and was terminating at the first space. To test my theory, I created a new user ID with no spaces and ran NX Client 3.5.0-7 and it worked. This also corrected a problem that sprung up with X2Go. The short answer is, you must not have any spaces in your user name or both NX Client and X2Go will fail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to move a subtree to another subtree in org-mode emacs I'd like to perform one simple task but there seems to be no clear solution for it: I have a structure of subtrees like this: * Tree A ** Subtree A1 ** Subtree A2 * Tree B ** Subtree B1 ** Subtree B2 I'd like to set up one key shortcut to move subtrees from Tree A to Tree B. Moving to the archive seems to be easy, but do you have any clue how to do it within one file? Any help appreciated! Thanks! A: I also wanted a way for org-refile to refile easily to a subtree, so I wrote some code and generalized it so that it will set an arbitrary immediate target anywhere (not just in the same file). Basic usage is to move somewhere in Tree B and type C-c C-x C-m to mark the target for refiling, then move to the entry in Tree A that you want to refile and type C-c C-w which will immediately refile into the target location you set in Tree B without prompting you, unless you called org-refile-immediate-target with a prefix arg C-u C-c C-x C-m. Note that if you press C-c C-w in rapid succession to refile multiple entries it will preserve the order of your entries even if org-reverse-note-order is set to t, but you can turn it off to respect the setting of org-reverse-note-order with a double prefix arg C-u C-u C-c C-x C-m. (defvar org-refile-immediate nil "Refile immediately using `org-refile-immediate-target' instead of prompting.") (make-local-variable 'org-refile-immediate) (defvar org-refile-immediate-preserve-order t "If last command was also `org-refile' then preserve ordering.") (make-local-variable 'org-refile-immediate-preserve-order) (defvar org-refile-immediate-target nil) "Value uses the same format as an item in `org-refile-targets'." (make-local-variable 'org-refile-immediate-target) (defadvice org-refile (around org-immediate activate) (if (not org-refile-immediate) ad-do-it ;; if last command was `org-refile' then preserve ordering (let ((org-reverse-note-order (if (and org-refile-immediate-preserve-order (eq last-command 'org-refile)) nil org-reverse-note-order))) (ad-set-arg 2 (assoc org-refile-immediate-target (org-refile-get-targets))) (prog1 ad-do-it (setq this-command 'org-refile))))) (defadvice org-refile-cache-clear (after org-refile-history-clear activate) (setq org-refile-targets (default-value 'org-refile-targets)) (setq org-refile-immediate nil) (setq org-refile-immediate-target nil) (setq org-refile-history nil)) ;;;###autoload (defun org-refile-immediate-target (&optional arg) "Set current entry as `org-refile' target. Non-nil turns off `org-refile-immediate', otherwise `org-refile' will immediately refile without prompting for target using most recent entry in `org-refile-targets' that matches `org-refile-immediate-target' as the default." (interactive "P") (if (equal arg '(16)) (progn (setq org-refile-immediate-preserve-order (not org-refile-immediate-preserve-order)) (message "Order preserving is turned: %s" (if org-refile-immediate-preserve-order "on" "off"))) (setq org-refile-immediate (unless arg t)) (make-local-variable 'org-refile-targets) (let* ((components (org-heading-components)) (level (first components)) (heading (nth 4 components)) (string (substring-no-properties heading))) (add-to-list 'org-refile-targets (append (list (buffer-file-name)) (cons :regexp (format "^%s %s$" (make-string level ?*) string)))) (setq org-refile-immediate-target heading)))) (define-key org-mode-map "\C-c\C-x\C-m" 'org-refile-immediate-target) It was hard to find a key that was free on the C-c C-x prefix, so I used m with the mnemonic i*mm*ediate A: I use M-left, M-up/down and then M-right if the structure of the file is not too complex. But keep in mind that if you try to move Subtree A1 to Tree B using this method, you will lose its child Subsubtree A1.1, unless you move it with M-S-left/right: * Tree A ** Subtree A1 <=== move this heading with M-S-left *** Subsubtree A1.1 <=== or you will leave this heading behind ** Subtree A2 * Tree B ** Subtree B1 ** Subtree B2 A: You can refile the subtree using C-c C-w, depending on how you have refile set up. Depending on the depth of your destination you may not be able to use it as a valid destination. You can kill or copy a subtree without having to fold the structure using the kill/copy subtree commands: C-c C-x C-w and C-c C-x M-w respectively, yanking a subtree is either C-c C-x C-y or simply C-y A: Moving a subtree within the same buffer can be done with org-refile. While moving, you can even change hierarchy of the original (number of stars). However, it might not work out of the box primarily because the buffer you are working with is not in the org-refile-targets. You could add the file in the refile targets by using C-[, then run org-refile with C-c C-w and finally remove the file from the refile targets with C-]. This might be too much (and might fail if your maxlevel setting is too low - which you can change anyway). Alternatively, to automate this procedure in one swoop, you will first have to define a function like this: (defun refile-in-current () "refile current item in current buffer" (interactive) (let ((org-refile-use-outline-path t) (org-refile-targets '((nil . (:maxlevel . 5))))) (org-refile))) The nil in there means "current buffer". The let redefines your variables locally only. You will then have to add a shortcut to run the function. Here is one way to bind it to C-c m: (add-hook 'org-mode-hook (lambda () (local-set-key "\C-c m" 'refile-in-current) A: You could try to refill the subtree with C-c C-w (it work also to move the subtree to another file). Another way is to fold the subtree, then to kill it with C-k C-k and to paste it where it should be. The third solution I use some time is to change the level of the subtree with M-left, then to move it with M-up and M-down, then M-right put it again on the correct level. This third way have the shortcoming that some time it make other part of the tree to move. A: (require 'org-archive) (setq org-archive-save-context-info nil) (setq org-archive-location "::* Archived Tasks") run (org-archive-subtree) at subtree which you want to move, it will be moved into "* Archived Tasks" heading
{ "language": "en", "url": "https://stackoverflow.com/questions/7509463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: update data based on another table I have a user table with following fields id int name varchar dob date/time Now, I have another table called user_map table, with 2 fields oldid int newid int user_map table is used for storing user id mapping, field 'oldid' is user's old id (which is current user id from user table), and 'newid' is user id going to be assigned I need a single update query, which can update user id for all users in user table How should it work? Well, for each id in user table, there will be only 1 record matching in user_map table. id from user table matches oldid from user_map table, and it should be replaced by newid For example (ignore dob field please) user table id name dob 1 aaa 0000-00-00 00:00:00 2 bbb 0000-00-00 00:00:00 3 ccc 0000-00-00 00:00:00 user_map table oldid newid 1 6 2 7 3 8 After query, user table should look like user table id name dob 6 aaa 0000-00-00 00:00:00 7 bbb 0000-00-00 00:00:00 8 ccc 0000-00-00 00:00:00 how can I achieve this? is it possible in 1 query only? A: Have you tried: update user, user_map set user.id = user_map.newid where user.id = user_map.oldid; A: Check following query update `user table` a, `user_map` b set a.id=b.newid where a.id=b.oldid this query is enough to update main table A: You can try to use the following - update user set id = um.newid from user un, user_map um where un.id = um.oldid
{ "language": "en", "url": "https://stackoverflow.com/questions/7509467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF4.1 Code first one to many self reference I'm trying to make a one to many self reference using EF4.1 code first. My entity looks like this public class Site { public int Id { get; set; } public int? ParentId { get; set; } public string Sitename { get; set; } public virtual Site ChildSite { get; set; } public virtual ICollection<Site> ChildSites { get; set; } } And in my context class I do this to make the self reference modelBuilder.Entity<Site>() .HasOptional(s => s.ChildSite) .WithMany(s => s.ChildSites) .HasForeignKey(s => s.ParentId); But when i try to add some dummy data to my database with this code var sites = new List<Site> { new Site { ParentId = 0, Sitename = "Top 1" }, new Site { ParentId = 0, Sitename = "Top 2" }, new Site { ParentId = 0, Sitename = "Top 3" }, new Site { ParentId = 0, Sitename = "Top 4" }, new Site { ParentId = 1, Sitename = "Sub 1_5" }, new Site { ParentId = 1, Sitename = "Sub 1_6" }, new Site { ParentId = 1, Sitename = "Sub 1_7" }, new Site { ParentId = 1, Sitename = "Sub 1_8" }, new Site { ParentId = 2, Sitename = "Sub 2_9" }, new Site { ParentId = 2, Sitename = "Sub 2_10" }, new Site { ParentId = 2, Sitename = "Sub 2_11" }, new Site { ParentId = 2, Sitename = "Sub 2_12" }, new Site { ParentId = 3, Sitename = "Sub 3_13" }, new Site { ParentId = 3, Sitename = "Sub 3_14" }, new Site { ParentId = 3, Sitename = "Sub 3_15" }, new Site { ParentId = 3, Sitename = "Sub 3_16" }, new Site { ParentId = 4, Sitename = "Sub 4_17" }, new Site { ParentId = 4, Sitename = "Sub 4_18" }, new Site { ParentId = 4, Sitename = "Sub 4_19" }, new Site { ParentId = 4, Sitename = "Sub 4_20" } }; sites.ForEach(s => context.Sites.Add(s)); context.SaveChanges(); I get this error : Unable to determine the principal end of the 'Cms.Model.Site_ChildSite' relationship. Multiple added entities may have the same primary key. What am i missing here ? Edit : Here is the solution to my problem. I removed the public virtual Site ChildSite { get; set; } from the entity public class Site { public int Id { get; set; } public int? ParentId { get; set; } public string Sitename { get; set; } public virtual ICollection<Site> ChildSites { get; set; } } I then changed the modelBuilder to this modelBuilder.Entity<Site>() .HasMany(s => s.ChildSites) .WithOptional() .HasForeignKey(s => s.ParentId); As it seems that auto generation of the database did not work I went ahead and created the table myself like this int Id, not null, primary key int ParentId, null string Sitename, null And everything works as I want it to. 2nd Edit And the final step to get the auto generation of dummy data to work var parent1 = new Site { Sitename = "Top 1", ChildSites = new List<Site> { new Site {Sitename = "Sub 1_5"}, new Site {Sitename = "Sub 1_6"}, new Site {Sitename = "Sub 1_7"}, new Site {Sitename = "Sub 1_8"} } }; ect . . . context.Sites.Add(parent1); context.SaveChanges(); See Slauma answer below A: I have a different model, but I will post what was necessary in my case and it works just fine with EF4.1 on MVC 3: Model public class Page { public int Id { get; set; } public virtual string Title { get; set; } public int? ParentId { get; set; } public virtual Page Parent { get; set; } public virtual ICollection<Page> Children { get; set; } } Database (use of fluent API) protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Page>() .HasOptional(s => s.Parent) .WithMany(s => s.Children) .HasForeignKey(s => s.ParentId); } Initializer var page1 = new Page() { Title = "title" }; context.Pages.Add(page1); var page2 = new Page() { Parent = page1, Title = "title2", }; context.Pages.Add(page2); A: Your mapping is correct and you don't need to remove the ChildSite property. You just can't use foreign key properties when you create your entities and "guess" how those autogenerated numbers will be after the entities are stored and use these numbers in the same entities which are being stored. The following instead should work and create the expected rows in the database: var parent1 = new Site { Sitename = "Top 1", ChildSites = new List<Site> { new Site {Sitename = "Sub 1_5"}, new Site {Sitename = "Sub 1_6"}, new Site {Sitename = "Sub 1_7"}, new Site {Sitename = "Sub 1_8"} } }; var parent2 = new Site { Sitename = "Top 2", ChildSites = new List<Site> { new Site {Sitename = "Sub 2_9"}, new Site {Sitename = "Sub 2_10"}, new Site {Sitename = "Sub 2_11"}, new Site {Sitename = "Sub 2_12"} } }; var parent3 = new Site { Sitename = "Top 3", ChildSites = new List<Site> { new Site {Sitename = "Sub 3_13"}, new Site {Sitename = "Sub 3_14"}, new Site {Sitename = "Sub 3_15"}, new Site {Sitename = "Sub 3_16"} } }; var parent4 = new Site { Sitename = "Top 4", ChildSites = new List<Site> { new Site {Sitename = "Sub 4_17"}, new Site {Sitename = "Sub 4_18"}, new Site {Sitename = "Sub 4_19"}, new Site {Sitename = "Sub 4_20"} } }; context.Sites.Add(parent1); context.Sites.Add(parent2); context.Sites.Add(parent3); context.Sites.Add(parent4); context.SaveChanges(); Edit If the entities represented by a foreign key exists in the DB you can use it - for example: var site = context.Sites.Single(s => s.Sitename == "Top 1"); site.ParentId = 4; // set a parent for "Top 1" context.SaveChanges(); Add a new child: var site = context.Sites.Single(s => s.Sitename == "Top 1"); site.ChildSites.Add(new Site { Sitename = "Sub 1_9" }); context.SaveChanges(); Remove a child: var site = context.Sites.Single(s => s.Sitename == "Top 1"); // works because of lazy loading var childToRemove = site.ChildSites.Single(s => s.Sitename == "Sub 1_9"); site.ChildSites.Remove(childToRemove); context.SaveChanges(); etc. A: Don't know what's the purpose of keepin a collection of ChildSite and one ChildSites for a site. Try out this configuration. public class Site { public int Id { get; set; } public int? ParentId { get; set; } public virtual Site Parent { get; set; } public string Sitename { get; set; } public virtual ICollection<Site> ChildSites { get; set; } } modelBuilder.Entity<Site>() .HasOptional(s => s.Parent) .WithMany(s => s.ChildSites) .HasForeignKey(s => s.ParentId); Edit And when you are inserting you need to do like this. site s1= new Site { ParentId = 0, Sitename = "Top 1" }; site s2= new Site { ParentId = 0, Sitename = "Top 2" }; site s3= new Site { ParentId = 0, Sitename = "Top 3" }; //.... site s4= new Site { Parent = s1, Sitename = "Sub 1_5"}; A: First of all - don't specify the id - I think the database is responsible for adding autonumbers to your entities. Try fill your database this way instead: var top1 = new Site { Sitename = "Top 1" }; var sub15 = new Site { ChildSite = top1 , Sitename = "Sub 1_5" }; var sub16 = new Site { ChildSite = top1 , Sitename = "Sub 1_6" }; var sub17 = new Site { ChildSite = top1 , Sitename = "Sub 1_7" }; ... context.Sites.Add(top1); var top2 = new Site { Sitename = "Top 2" }; var sub29 = new Site { ChildSite = top2 , Sitename = "Sub 2_9" }; var sub210 = new Site { ChildSite = top2 , Sitename = "Sub 2_10" }; var sub211 = new Site { ChildSite = top2 , Sitename = "Sub 2_11" }; .... context.Sites.Add(top2); .... context.SaveChanges(); Next: I think you should call your ChildSite for ParentSite that will make the code easyer to read: var top1 = new Site { Sitename = "Top 1" }; var sub15 = new Site { ParentSite = top1 , Sitename = "Sub 1_5" }; var sub16 = new Site { ParentSite = top1 , Sitename = "Sub 1_6" }; var sub17 = new Site { ParentSite = top1 , Sitename = "Sub 1_7" }; ... context.Sites.Add(top1); var top2 = new Site { Sitename = "Top 2" }; var sub29 = new Site { ParentSite = top2 , Sitename = "Sub 2_9" }; var sub210 = new Site { ParentSite = top2 , Sitename = "Sub 2_10" }; var sub211 = new Site { ParentSite = top2 , Sitename = "Sub 2_11" }; .... context.Sites.Add(top2); .... context.SaveChanges();
{ "language": "en", "url": "https://stackoverflow.com/questions/7509468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Drawing maps in WPF I want to draw a map in WPF without using any third party controls. I need each and every state of all the countries, and based on certain conditions I want to color them. How can I get the polygon shapes of each state of all the countries? A: Here is an SVG file with all the states as separate polygons (look at the source!) You can convert it to xaml if you want and fill the state differently. EDIT Just google for svg world map. One of the first hits seems to be a nice resource.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to store user activities in mysql database? Consider a simple websites with lots of user activities (like stackoverflow). What is the best way to store user activities such as votes, adding to favorites, etc. To my knowledge there are two possible ways: De-normalized: Storing user IDs of members who has voted for an article in a column for "who has voted" in the articles table. This will be comma-separated list of IDs. Normalized: Creating a relationship table to connect article ID to user ID. This method has invaluable advantage (and I know most of you will support this idea); but my concern is (1) This table can easily reach millions of row. Since it is indexed, reading should be fast enough, but updating (on a regular basis) of a long indexed table can be problematic. (2) Every time visiting the article page, we need to read one more table which will slow down the regular queries. A: You could also do the best of both worlds and have a transitional database and a rolled up reporting database that is refreshed "offline"
{ "language": "en", "url": "https://stackoverflow.com/questions/7509476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iPhone App to transfer message over bluetooth but device is not getting connected I am working on this iPhone app with which you can send message to other connected device. I have gone through following tutorial http://vivianaranha.com/apple-gamekit-bluetooth-integration-tutorial/ Everything seems to be fine. No memory leaks or anything like that. Now I installed this application on iPad and iTouch. iPad is running 4.3.5 and iTouch is running 4.2.1. I am using X Code 4.0 with iOS 4.3 as base sdk. I set my targets to 4.0 in X Code for above project (like Target->Messenger->summary->deployment target->4.0) similarly for project. Now when I run application and try to connect it with other device, it shows only looking for nearby iOS devices and nothing happens further. But when I set deployment target to 4.3 and install same app on iPad, that iPad can detect iTouch but not able to connect it. Can anyone tell me why is this happening and how to deal with it ? Regards, Sumit A: Did u try using Xcode Simulator to connect your iPod Touch by Blue Tooth? Then it can make more sure that your programming run correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: System wide right click context hook **Hello.. i am creating English To Gujarati Dictionary WinForm Application. I need to set a system wide hook to the right click context menu on for text selection. it means when this application is running,and if user selects word from any program and right click on it gujarati meaning of that word should be displayed as menu item. How to do this? or any other options like Registery Programming,shell extentions etc...? i have to do this,even if you say its not possible. so please help me.** A: Hooking the mouse activity is the easy part. See SetWindowsHookEx, and lots of questions regarding hooking in SO. This way, you can tell when the mouse is right-clicked. Getting the selected text is the harder part. See WindowFromPoint, for starters. You'd have to recognize the control, and if appropriate get the selected text from it. This will not always be possible using simple Win32 functions, if the control is complex. Adding the translation to the right-click menu is probably the impossible part. Adding stuff to explorer context menu is not a problem, because explorer provides that possibility. But various applications will have various right-click menus, without a way to extend them. They might not even use Win32 for the menus, for whatever reason. A better option, IMO, would be one of the following: * *Forget about changing the right-click menu. Open a window next to the point of selection with whatever content you want, and let the application show its own right-click menu. *If the user right-clicks while, say, pressing shift, show your own right-click menu, and don't pass the message to the application. So the user will see only one menu, which is yours. The user must of course be aware of this combination.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where is the best place to write the error to the log from? (BLL or ExceptionConstructor) I want to throw some custom exception and write it to the log. What is the best practice in regards the correct place to write the log from: BLL, or the Exception constructor itself? class TaskDataValidationFailedException : Exception { public TaskDataValidationFailedException(TaskValidationResult validation) { this.validation = validation; //SHOULD I WRITE THE LOG HERE? _log.Info("Task " + task.Name + " valication failed"); } } or here? if (!validation.validationSucceeded) { throw new TaskDataValidationFailedException(validation); //OR SHOULD I WRITE THE LOG HERE? _log.Info("Task " + task.Name + " valication failed"); } A: The second is better: * *Why should exception know something about log? These two things are independent. *You can write to log any number of variables, in the first case you have to pass all of them to your exception. Also you may consider to write a function for checking validation, writing to log and throwing an exception: void CheckValidation(...) { if (!validation.validationSucceeded) { _log.Info("Task " + task.Name + " valication failed"); throw new TaskDataValidationFailedException(validation); } } A: Well, most people log the Exception just before throwing it. However doing it in the constructor of the Exception has its merits, if you do it right ;D Doing it right means you need one inheritance level more. So you can do it in a centralized constructor (you should have one Exception base class per "component" of your system anyway). The intermediate level Exception will have a ctor that accepts the message and log it. Well, in Java the intermediate Exception would perhaps call a method which could be overwritten in derived classes but this is not possible in C++.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pass an array in jquery via ajax to a c# webmethod I'd like to pass an array to a c# webmethod but don't have a good example to follow. Thanks for any assistance. Here is what I have so far: My array: $(".jobRole").each(function (index) { var jobRoleIndex = index; var jobRoleID = $(this).attr('id'); var jobRoleName = $(this).text(); var roleInfo = { "roleIndex": jobRoleIndex, "roleID": jobRoleID, "roleName": jobRoleName }; queryStr = { "roleInfo": roleInfo }; jobRoleArray.push(queryStr); }); My ajax code $.ajax({ type: "POST", url: "WebPage.aspx/save_Role", data: jobRoleArray, contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function (data) { alert("successfully posted data"); }, error: function (data) { alert("failed posted data"); alert(postData); } }); Not sure on the webmethod but here is what I'm thinking: [WebMethod] public static bool save_Role(String jobRoleArray[]) A: You will be passing an array of: [ "roleInfo": { "roleIndex": jobRoleIndex, "roleID": jobRoleID, "roleName": jobRoleName }, "roleInfo": { "roleIndex": jobRoleIndex, "roleID": jobRoleID, "roleName": jobRoleName }, ... ] And in my opinion, it would be easier if you have a class that matches that structure, like this: public class roleInfo { public int roleIndex{get;set;} public int roleID{get;set;} public string roleName{get;set;} } So that when you call your web method from jQuery, you can do it like this: $.ajax({ type: "POST", url: "WebPage.aspx/save_Role", data: "{'jobRoleArray':"+JSON.stringify(jobRoleArray)+"}", contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function (data) { alert("successfully posted data"); }, error: function (data) { alert("failed posted data"); alert(postData); } }); And in your web method, you can receive List<roleInfo> in this way: [WebMethod] public static bool save_Role(List<roleInfo> jobRoleArray) { } If you try this, please let me know. Above code was not tested in any way so there might be errors but I think this is a good and very clean approach. A: I have implement something like this before which is passing an array to web method. Hope this will get you some ideas in solving your problem. My javascript code is as below:- function PostAccountLists() { var accountLists = new Array(); $("#participantLists input[id*='chkPresents']:checked").each(function () { accountLists.push($(this).val()); }); var instanceId = $('#<%= hfInstanceId.ClientID %>').val(); $.ajax({ type: "POST", url: "/_layouts/TrainingAdministration/SubscriberLists.aspx/SignOff", data: "{'participantLists': '" + accountLists + "', insId : '" + instanceId + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { AjaxSucceeded(msg); }, error: AjaxFailed }); } In the code behind page (the web method) [WebMethod] public static void SignOff(object participantLists, string insId) { //subscription row id's string[] a = participantLists.ToString().Split(','); List<int> subIds = a.Select(x => int.Parse(x)).ToList<int>(); int instanceId = Convert.ToInt32(insId); The thing to notice here is in the web method, the parameters that will receive the array from the ajax call is of type object. Hope this helps. EDIT:- according to your web method, you are expecting a value of type boolean. Here how to get it when the ajax call is success function AjaxSucceeded(result) { var res = result.d; if (res != null && res === true) { alert("succesfully posted data"); } } Hope this helps A: Adding this for the ones, like MdeVera, that looking for clean way to send array as parameter. You can find the answer in Icarus answer. I just wanted to make it clear: JSON.stringify(<your array cames here>) for example, if you would like to call a web page with array as parameter you can use the following approach: "<URL>?<Parameter name>=" + JSON.stringify(<your array>)
{ "language": "en", "url": "https://stackoverflow.com/questions/7509485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to acess the WCF service if the is service is authenticated i am using the visual studio 2005 in that i want to get some methods from the WCF service. i called the WCF service but i cant to able to access it because it is authenticated by the client credentials so i am getting error as like "PERMISSION DENIED TO GET THIS METHOD". How to pass the credentials from visual studio 2005 to access that WCF service?.As i am new WCF service please guide me? same code i have posted. EmployeeService service = new EmployeeService(); A: Have you tried using Credentials property. For example, EmployeeService service = new EmployeeService(); service.Credentials = new NetworkCredentials(userName, password);
{ "language": "en", "url": "https://stackoverflow.com/questions/7509486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I unregister my user from my application? I am using facebook C# SDK in my application and using Graph API. Everything is working fine. However, I didn't get how to unregister my users from my application meaning revoke the rights given to my application. I didn't get how to do this using SDK. Any help would be appreciated. Let me know if my question is not clear. A: From the user documentation: You can de-authorize an application or revoke a specific extended permissions on behalf of a user by issuing an HTTP DELETE request to PROFILE_ID/permissions with a user access_token for that app. Also, you can still call auth.revokeAuthorization or auth.revokeExtendedPermission.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use form.submit with jQuery validate and overlay windows I have figured out how to submitHandler and do some tasks before submitting the form. Now I need to show a few overlay windows (jQuery Tools) and onClose, submit the form. But its not working, Im getting a ton of errors in Firebug. Anyone have any ideas, here is my code: $("#frmcheckout").validate({ submitHandler: function(form) { // Before Submit - show compliance messages var state = $('#shippingState1').val(); if(state == 'CT' || state == 'Connecticut' || state == '1049'){ $("#compliance-order-ct").overlay({ expose: { color: '#333', loadSpeed: 200, opacity: 0.9 }, closeOnClick: false, load: true, onClose: function() { // Submit the form console.log('overlay closed'); form.submit(); //return true; } }); } }); If I bypass using the overlay, I'm able to use form.submit just fine - but once I include it in onClose event, then it doesn't submit. Just seeing if anyone sees anything glaring. A: Not sure without the errors and you only say its 'not working' (does the overlay not show up, or does the form not submit?) ...but I can say that onClose will not receive the form object as a param, it will get an Event. So you are probably trying to call submit on an Event Object, not the form. From the jQuery tools docs: All event listeners receive the Event Object as the first argument and there are no other arguments for Overlay.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: System.Net.Browser.ClientHttpWebRequest.EndGetResponse throw System.ArgumentException when header contains non-ascii content I have a function that written in my Windows Phone 7 project. It is going to trace the content header of each HttpWebRequest and if the content-type is document(like a pdf attachment in Web mail), it will download it. The function worked fine when the file name is English. However, when the file name is non-ascii, say Chinese and Japanese, it will throw an System.ArgumentException in (HttpWebResponse)m_responseRequest.EndGetResponse(m_responseCallbackAsyncResult). How to fix it? It is important to me as I need to handle a lot of file named in Chinese. The following is my code: private void _checkHeader(string m_uri) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_uri); request.Method = "POST"; request.BeginGetRequestStream((asynchronousResult) => { var m_readCallBackrequest = (HttpWebRequest)asynchronousResult.AsyncState; m_readCallBackrequest.BeginGetResponse((m_responseCallbackAsyncResult) => { var m_responseRequest = (HttpWebRequest)m_responseCallbackAsyncResult.AsyncState; try { var resp = (HttpWebResponse)m_responseRequest.EndGetResponse(m_responseCallbackAsyncResult); Debug.WriteLine(resp.Headers.ToString()); } catch (WebException) { } }, m_readCallBackrequest); }, request); } And the exception detail: System.ArgumentException was unhandled Message="" StackTrace: at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at FotomaxWP71.ViewModel.WebViewModel.<checkHeader>b_d(IAsyncResult m_responseCallbackAsyncResult) at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClassa.b_8(Object state2) at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadPool.WorkItem.doWork(Object o) at System.Threading.Timer.ring() InnerException: System.ArgumentException Message=[net_WebHeaderInvalidControlChars] Arguments: Debugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version=4.7.60408.0&File=System.Net.dll&Key=net_WebHeaderInvalidControlChars Parameter name: name StackTrace: at System.Net.ValidationHelper.CheckBadWebHeaderChars(String name, Boolean isHeaderValue) at System.Net.WebHeaderCollection.set_Item(String name, String value) at System.Net.Browser.HttpWebRequestHelper.AddHeaderToCollection(WebHeaderCollection headerCollection, String headerName, String headerValue) at System.Net.Browser.HttpWebRequestHelper.ParseHeaders(Uri requestUri, SecurityCriticalDataForMultipleGetAndSet`1 headers, WebHeaderCollection collection, Boolean removeHttpOnlyCookies, HttpStatusCode& status, String& statusDescription) at System.Net.Browser.ClientHttpWebRequest.Progress(Object sender, EventArgs e) at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName) Thanks a lot! A: change the code in try{} to this: var resp = (HttpWebResponse)m_responseRequest.EndGetResponse(m_responseCallbackAsyncResult); byte[] buf = new byte[resp.Headers.ToString().Length]; buf = resp.Headers.ToString().ToCharArray(); Debug.WriteLine(buf);
{ "language": "en", "url": "https://stackoverflow.com/questions/7509498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to configure mod_deflate to serve gzipped assets prepared with assets:precompile When running the assets:precompile rake task, gzipped versions of your app's assets are created. According to the Rails guide for the asset pipeline, you can configure your web server (in my case Apache 2.2) to serve these precompressed files instead of having the web server do the work. What I can't figure out is how to get mod_deflate configured so that these files are served instead of being double-compressed and then served? I have mod_deflate enabled via httpd.conf: AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html And I've converted the code on the rails guide to go into the .htaccess in public/assets: # Some browsers still send conditional-GET requests if there's a # Last-Modified header or an ETag header even if they haven't # reached the expiry date sent in the Expires header. Header unset Last-Modified Header unset ETag FileETag None # RFC says only cache for 1 year ExpiresActive On ExpiresDefault "access plus 1 year" # Serve gzipped versions instead of requiring Apache to do the work RewriteEngine on RewriteCond %{REQUEST_FILENAME}.gz -s RewriteRule ^(.+) $1.gz [L] # without it, Content-Type will be "application/x-gzip" <FilesMatch .*\.css.gz> ForceType text/css </FilesMatch> <FilesMatch .*\.js.gz> ForceType text/javascript </FilesMatch> Any ideas how to set this up properly? A: First, you don't want mod_deflate to operate here. So in your assets .htaccess file add: SetEnv no-gzip This should turn off mod_deflate for your assets. Second, I hate to disagree with the rails folks, but I think there are a couple deficiencies in their assets .htaccess recipe. The top part is fine but for RewriteEngine and beyond I'd have: RewriteEngine on # Make sure the browser supports gzip encoding before we send it RewriteCond %{HTTP:Accept-Encoding} \b(x-)?gzip\b RewriteCond %{REQUEST_URI} .*\.(css|js) RewriteCond %{REQUEST_FILENAME}.gz -s RewriteRule ^(.+) $1.gz [L] # without it, Content-Type will be "application/x-gzip" # also add a content-encoding header to tell the browser to decompress <FilesMatch \.css\.gz$> ForceType text/css Header set Content-Encoding gzip </FilesMatch> <FilesMatch \.js\.gz$> ForceType application/javascript Header set Content-Encoding gzip </FilesMatch>
{ "language": "en", "url": "https://stackoverflow.com/questions/7509501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How can I create an Rx observable which stops publishing events when the last observer unsubscribes? I'll create an observable (through a variety of means) and return it to interested parties, but when they're done listening, I'd like to tear down the observable so it doesn't continue consuming resources. Another way to think of it as creating topics in a pub sub system. When no one is subscribed to a topic any more, you don't want to hold the topic and its filtering around anymore. A: Rx already has an operator to suit your needs - well two actually - Publish & RefCount. Here's how to use them: IObservable xs = ... var rxs = xs.Publish().RefCount(); var sub1 = rxs.Subscribe(x => { }); var sub2 = rxs.Subscribe(x => { }); //later sub1.Dispose(); //later sub2.Dispose(); //The underlying subscription to `xs` is now disposed of. Simple. A: If I have understood your question you want to create the observable such that when all subscribers have disposed their subscription i.e there is no more subscriber, then you want to execute a clean up function which will stop the observable from production further values. If this is what you want then you can do something like below: //Wrap a disposable public class WrapDisposable : IDisposable { IDisposable disp; Action act; public WrapDisposable(IDisposable _disp, Action _act) { disp = _disp; act = _act; } void IDisposable.Dispose() { act(); disp.Dispose(); } } //Observable that we want to clean up after all subs are done public static IObservable<long> GenerateObs(out Action cleanup) { cleanup = () => { Console.WriteLine("All subscribers are done. Do clean up"); }; return Observable.Interval(TimeSpan.FromSeconds(1)); } //Wrap the observable public static IObservable<T> WrapToClean<T>(IObservable<T> obs, Action onAllDone) { int count = 0; return Observable.CreateWithDisposable<T>(ob => { var disp = obs.Subscribe(ob); Interlocked.Increment(ref count); return new WrapDisposable(disp,() => { if (Interlocked.Decrement(ref count) == 0) { onAllDone(); } }); }); } //Usage example: Action cleanup; var obs = GenerateObs(out cleanup); var newObs = WrapToClean(obs, cleanup); newObs.Take(6).Subscribe(Console.WriteLine); newObs.Take(5).Subscribe(Console.WriteLine);
{ "language": "en", "url": "https://stackoverflow.com/questions/7509503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I line up input fields and their labels in a grid like manner with css? I'm trying to do something that must be relatively easy, but I've spent hours mucking around with this and I'm no getting to the answer. I need to layout some input fields and their layers on a grid (or like a table I guess) with lable input label input label input label input Because the input fields are different widths (and would look pretty crappy if they were all the same width) the best I've managed to get is label input label input label logerinput label input How do I line up the second set of labels and there inputs? I've made two classes for the labels #dpi_form label { display: inline-block; width: 150px; margin-left: 20px; } #dpi_form .right-label { display: inline-block; width: 150px; margin-left: 220px; } and the associated controls are <label for="req_retailer_index_fld">Select the retailer*:</label><select id="req_retailer_index_fld" name="req_retailer_index_fld" class="required selectbox ui-widget-content"><option>item 1</option><option>item 2</option></select> <label for="req_region_index_fld" class="right-label">Select the region*:</label><select id="req_region_index_fld" name="req_region_index_fld" class="required selectbox ui-widget-content"><option>item 1</option><option>item 2</option></select><br /> <label for="req_customer_type_index_fld">Select the customer type*:</label><select id="req_customer_type_index_fld" name="req_customer_type_index_fld" class="required selectbox ui-widget-content"><option>item 1</option><option>item 2</option></select> <label for="req_meter_state_index_fldi" class="right-label">Select the meter state*:</label><select id="req_meter_state_index_fld" name="req_meter_state_index_fld" class="required selectbox ui-widget-content"><option>item 1</option><option>item 2</option></select><br /> within a div. I've tried absolute positioning, relative positioning, padding, all manner of right and left margins but still can't get the result I'm after. I can find heaps of stuff or vertical alignment of controls.. but nothing showing me how to do this one. Any clues please? Peter. A: Despite my comment about using tables on your question, this is how I would do it. CSS: label, input { display: block; } label { padding: 4px 0 0; } .labels1 { float: left; width: 80px; } .labels2 { float: left; width: 80px; } .inputs1 { float: left; width: 200px; } .inputs2 { float: left; width: 200px; } HTML: <div class="labels1"> <label for="input1">Input 1: </label> <label for="input2">Input 2: </label> <label for="input3">Input 2: </label> </div> <div class="inputs1"> <input type="text" value="" name="input1" id="input1" /> <input type="text" value="" name="input2" id="input2" /> <input type="text" value="" name="input3" id="input3" /> </div> <div class="labels2"> <label for="input4">Input 4: </label> <label for="input5">Input 5: </label> <label for="input6">Input 6: </label> </div> <div class="inputs2"> <input type="text" value="" name="input4" id="input4" /> <input type="text" value="" name="input5" id="input5" /> <input type="text" value="" name="input6" id="input6" /> </div> Then you can change the labels and inputs classes to the width you want. Although I still think tables are easier because then you don't have to worry about setting widths yourself; you also don't have to worry about vertical alignment with tables. A: use following styles. for parent container display: table; for row container display: table-row; for cell container display: table-cell; example <div style="display: table;"> <div style="display: table-row;"> <div style="display: table-cell;"> lable </div> <div style="display: table-cell;"> input </div> <div style="display: table-cell;"> label input </div> </div> <div> <div style="display: table-cell;"> lable </div> <div style="display: table-cell;"> input </div> <div style="display: table-cell;"> label input </div> </div> </div> A: Use a table, that's what they are for. A: I would suggest using a table or for a pure CSS solution maybe the 960 grid system 960.gs A: I would use floats. Here's a jsfiddle showing how I would do it: http://jsfiddle.net/pSsap/ I'll reproduce the code below. With html like this: <form class="grid"> <section> <label for="wind">wind</label> <span class="field"><input id="wind" name="wind" type="input" class="regular"></span> <label for="earth">earth</label> <span class="field"><input id="earth" name="earth" type="input" class="regular"></span> </section> <section> <label for="fire">fire</label> <span class="field"><input id="fire" name="fire" type="input" class="long"></span> <label for="air">air</label> <span class="field"><input id="air" name="air" type="input" class="regular"></span> </section> </form> And css like this: form.grid section { clear: both; } form.grid section label, form.grid section span.field { display: block; float: left; } form.grid section label { width: 50px; } form.grid section span.field { width: 150px; } input.regular { width: 100px; } input.long { width: 140px; } A: Solutions: * *Use a list: <ol> or <ul> *Set a width for that list: (in the example, 960px is the width of the <ul>) *Float the lists: <li> and set a width to limit its floating point: (in the example, 320px is the set width) *If you want to have a consistent alignment with the <label> and <select> pairs, set a width to the <label> (make sure you set it as a block-level element first: in the example, the <label> was set to 160px) *Make sure to clear (clear: left) any elements following this list (<ul>) used. The Markup: <ul> <li> <label for="req_retailer_index_fld">Select the retailer*:</label> <select id="req_retailer_index_fld" name="req_retailer_index_fld" class="required selectbox ui-widget-content"> <option>item 1</option><option>item 2</option> </select> </li> <li> <label for="req_region_index_fld" class="right-label">Select the region*:</label> <select id="req_region_index_fld" name="req_region_index_fld" class="required selectbox ui-widget-content"> <option>item 1</option><option>item 2</option> </select> </li> <li> <label for="req_customer_type_index_fld">Select the customer type*:</label> <select id="req_customer_type_index_fld" name="req_customer_type_index_fld" class="required selectbox ui-widget-content"> <option>item 1</option><option>item 2</option> </select> </li> <li> <label for="req_meter_state_index_fldi" class="right-label">Select the meter state*:</label> <select id="req_meter_state_index_fld" name="req_meter_state_index_fld" class="required selectbox ui-widget-content"> <option>item 1</option><option>item 2</option> </select> </li> </ul> The CSS ul { background: #EEE; width: 960px; } li { background: #FFC0CB; float: left; list-style: none; width: 320px; } label { display: inline-block; width: 160px; } The result is that, the list will just drop when the <ul> can't contain it any longer (since you have set a width in it). On the other hand, the width of the <li>s will consistently make them align to each other, while being floated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to release a view when it's not visible in a tabbar controller? I have a simple app with a tabbar navigation interface. It has three view (A, B and C) and a modal view. Each view has its own view controller and nib . They are all designed and connected in the interface builder. I'd like to release views which are not visible. Tried release and nil them when another view appears such as [[[self.navigationController.viewControllers objectAtIndex:0] view] release]; [[self.navigationController.viewControllers objectAtIndex:0] view] = nil; etc. It doesn't cause any issues but when I run instruments it does not make any difference. I don't see any drop in memory usage I would appreciate your help A: The drop in memory usage might not be significant, depending on what the released viewController holds on to. I sugest you out a NSLog into the 'dealloc' of the viewController to see if it really gets dealloced or if there is some other object still holding on to it. Remember that release won't free the memory, it will only do so (by calling dealloc) if the objects retain count reached 0. A: You don't want to do this. Let the TabBarController handle your view controllers for you. (It will already retain your viewController internally so whatever you do will only make retain count go out of sync) You may be able to make it more memory efficient if you release objects in viewWillDisappear. Then rebuild the data again in viewWillAppear. A: as @Daryl Teo wrote you should release and recreate in viewWillDis/Appear and (thats why I write this answer) you have a method called didReceiveMemoryWarning, use it! You can simply log out whenever it gets called and test it with the Simulator included memory warning test function. Simply open a tab, open another tab and call that test function. Your debug console should print out the log. If not you should double check if you have released all objects maybe someone is over-retained (which again should be released in viewWillDisappear).
{ "language": "en", "url": "https://stackoverflow.com/questions/7509506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installing bluecloth - configuration options? I tried installing the bluecloth gem by typing gem install bluecloth But when I do that I get the following error message: checking for random()... *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/Users/cyrusstoller/.rvm/rubies/ruby-1.9.2-p136/bin/ruby --with-rdiscount-dir --without-rdiscount-dir --with-rdiscount-include --without-rdiscount-include=${rdiscount-dir}/include --with-rdiscount-lib --without-rdiscount-lib=${rdiscount-dir}/lib What options am I supposed to provide? A: I needed to have markdown installed before I tried to install the gem. run brew install markdown then gem install bluecloth A: I had the same problem when trying to install bluecloth 2.0.11 under Ruby 2.2.3. Turns out that Ruby 2.2.3 was too new. Going back to Ruby 2.1.5 resolved the issue. Check your .ruby-version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Encoding a binary tree to json I'm using the sqlalchemy to store a binary tree data in the db: class Distributor(Base): __tablename__ = "distributors" id = Column(Integer, primary_key=True) upline_id = Column(Integer, ForeignKey('distributors.id')) left_id = Column(Integer, ForeignKey('distributors.id')) right_id = Column(Integer, ForeignKey('distributors.id')) how can I generate json "tree" format data like the above listed: {'id':1,children:[{'id':2, children:[{'id':3, 'id':4}]}]} A: I'm guessing you're asking to store the data in a JSON format? Or are you trying to construct JSON from the standard relational data? If the former, why don't you just create entries like: {id: XX, parentId: XX, left: XX, right: XX, value: "foo"} For each of the nodes, and then reconstruct the tree manually from the entries? Just start form the head (parentId == null) and then assemble the branches. You could also add an additional identifier for the tree itself, in case you have multiple trees in the database. Then you would just query where the treeId was XXX, and then construct the tree from the entries. A: I hesitate to provide this answer, because I'm not sure I really understand your the problem you're trying to solve (A binary tree, JSON, sqlalchemy, none of these are problems). What you can do with this kind of structure is to iterate over each row, adding edges as you go along. You'll start with what is basically a cache of objects; which will eventually become the tree you need. import collections idmap = collections.defaultdict(dict) for distributor in session.query(Distributor): dist_dict = idmap[distributor.id] dist_dict['id'] = distributor.id dist_dict.setdefault('children', []) if distributor.left_id: dist_dict.['children'].append(idmap[distributor.left_id]) if distributor.right_id: dist_dict.['children'].append(idmap[distributor.right_id]) So we've got a big collection of linked up dicts that can represent the tree. We don't know which one is the root, though; root_dist = session.query(Distributor).filter(Distributor.upline_id == None).one() json_data = json.dumps(idmap[root_dist.id])
{ "language": "en", "url": "https://stackoverflow.com/questions/7509513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GWT designer size limitation I am designing a home page by using the GWT designer.But when I reached the height of more than 600 the images are not displayed.I have placed some images and run the application then it will show.But in the design mode it is not visible.Is there any such limitation in the size ?.I am unable to align the text in the footer which is obviously at the end .... A: This is a known limitation of GWT Designer. There's no way around this limitation so far. A: This is a known operating system limitation (it won't render anything larger than the physical display). Use a larger physical (or virtual) display.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reusing the main activity I have a main activity from where I will be switching from one activity to another..So i don't want to re initialize every time..After the first time of creation , the same activity should be called without having to create it over and over again..how do I do this? #newbie-android A: What you want to do is simply start both your activities and switch between them by bringing them to the foreground. You should refer to this question for a possible solution. This documentation might also help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reloading a page inside of a with $_GET The following page loads inside of on my index.php. I initially call it using the following link: Import Mutuals This part works dandy. The problem I'm having is with the refresh code at the bottom: var auto_refresh = setInterval(function(){\$('#import').show('fast').load('fb_import_statuses.php?i=$i').show('fast');}, 1000); I want it to initially load with record 1 and then keep refreshing, updating my SQL until it reaches record 255. If I do this same code outside of a DIV using Meta Refresh it steps through the sequence fine, but using this JavaScript refresh it will sequence like this: 1, 2, 3, 2, 3, 4, 2, 3, 4, 5 etc... How can I get it to sequence as 1, 2, 3, 4, 5, 6, 7 etc... require 'batch_include.php'; require 'html_head.php'; if (isset($_GET['i'])){$i = $_GET["i"];} else {$i=0;} $getcount = mysql_query("SELECT COUNT(id) AS get_count FROM people", $conn); while ($row = mysql_fetch_array($getcount)){$get_count = "".$row{'get_count'}."";} $result = mysql_query("SELECT id FROM people LIMIT ".$i.",1", $conn); while ($row = mysql_fetch_array($result)){ $get_uid = addslashes("".$row{'id'}.""); $me_friends = $facebook->api(array('method' => 'fql.query', 'query' => 'SELECT status_id, message, source, time FROM status WHERE uid="'.$get_uid.'" LIMIT 5')); foreach ($me_friends as $fkey=>$me_friends){ $get_status_id = $me_friends['status_id']; $get_message = addslashes($me_friends['message']); $get_source = $me_friends['source']; $get_timestamp = $me_friends['time']; $insert = mysql_query("INSERT INTO statuses (id, message, source, timestamp, uid) VALUES ('$get_status_id', '$get_message', '$get_source', '$get_timestamp', '$get_uid')", $conn); } } $i = $i + 1; if ($i<=$get_count){ echo "$i"; echo "<script>var auto_refresh = setInterval(function(){\$('#import').show('fast').load('fb_import_statuses.php?i=$i').show('fast');}, 1000); </script>"; } else { echo "Import complete: "; echo "<img src='/images/check.png'>"; } A: the problem is that you add multiple setInterval functions (everytime the page is loaded you echo another method). try putting your refreshing method out of the div or make it call a function that includes php code responsible for retrieving information from db. if you don't have to refresh the page every second, you could get all the data from db with one php file and return it in some form (json for example). I think this would be the best way to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: MAMP Pro 2.0.3 doesn't work in OS-X Lion see https://superuser.com/q/338471/98725 When I start MAMP Pro 2.0.3 on Mac OS X Lion I get the following error: Apache wasn't able to start. Please check log for more information. When I look at the Console it says: kernel: nstat_lookup_entry failed: 2 Anyone know what I need to do to fix this? Thanks, Dan
{ "language": "en", "url": "https://stackoverflow.com/questions/7509519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java pass by reference vs pass by value trouble why am i getting an error in the pass by reference example obj1.add200really is underlined public class Test { private int number; Test(){ number = 1; } public static void main(String[] args) { Test obj1 = new Test(); System.out.println("the number is " + obj1.number); System.out.println("the number 1 plus 200 is " + obj1.add200(obj1.number)); System.out.println("while the number is still " + obj1.number); System.out.println("\n"); System.out.println("the number is " + obj1.number); System.out.println("the number 1 plus 200 is " + obj1.add200really(obj1.number)); System.out.println("while the number is still " + obj1.number); } int add200(int somenumber){ somenumber = somenumber + 200; return somenumber; } int add200really(Test myobj){ myobj.number = 999; return myobj.number; } } A: Use obj1.add200really(obj1); A: Because you have no method add200really(int) Your method add200really() requires an object. You're trying to call it with an int
{ "language": "en", "url": "https://stackoverflow.com/questions/7509521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connection between windows service and sql database I am trying to establishing a connection between a Windows service written in C# and a SQL Server Express database. But when connection.open is called I get this exception System.data.sqlClient.sqlexception: {"Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed."} But the same code works fine when I run it as console application.Can someone please help me with this?? _connection = new SqlConnection("Data Source=.\\MSSQLSERVER1;AttachDbFilename=D:\\vinay\\project\\LightHistorian\\LH_DB.MDF‌​;Integrated Security=True;User Instance=True;"); i gave same credentials as local system.It works a times and doesnt at some other time.But when ever this exception happens,If i restart the machine it works.Wonder what the problem is?? I have used same connection for both windows service and console application A: When you execute your console application, the EXE runs under your user credentials. When you execute your service, which are user credentials? Is your service running under Locl Service Account? Or System? Or what? Try to manually set the credentials your service must run with (in Windows services panel, check your service properties) and try to execute it with the same user/pwd you run your console app with. UPDATE taken from here: Using an User Instance on a local SQL Server Express instance The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server 2005 instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL Server instance to a user with limited administrative rights on the computer. I could think that your service credentials are not granted to create a new SQL server instance, so try to remove that part. Anyway, set user credentials on service properties and see what happens.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to package a Ruby application? I've got an application in Ruby that uses the Qt 4 bindings. I want to be able to package and release it. I've looked at other applications such as rake and puppet to see how they're packaged. Both rake and puppet are packaged as gems. I started going down this route when I realized that both rake and puppet are more system level tools rather than user-level applications. I also looked at orca, but it's windows only. Are there other options available for packaging a Ruby GUI app other than gem or orca? I'd like something that's cross platform. A: Take a look at the platform specification for gems. You can package up a gem for each platform that your code supports. Some gems consist of pre-compiled code (“binary gems”). It’s especially important that they set the platform attribute appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: does my opengl es draw(); call draw objects not currently seen on the screen? In Android. If im drawing objects off screen, it would be a big performance boost to disable these objects assuming they arent already disabled from being drawn when off screen. A: I assume your question is how to cool the invisible objects. It depends on whether you're using 2d or 3d scene. In 2d it's very simple: everything outside the screen rectangle is culled. While in 3d it is very complex problem and there are tons of different techniques like bsp trees or portal rendering. The key word to google is "object culling".
{ "language": "en", "url": "https://stackoverflow.com/questions/7509528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - Zend Framework - Using static methods for data access I've been reading online about the pros and cons of using static methods for accessing data from the database. I have a LAMP based site built on Zend framework. Some say in terms of performance - there is hardly any difference as quoted here by Greg Beech's analysis in calling a method two billion times you could save yourself around 5ms by making it static, which is a saving of approximately nothing for each method call But if I understand the concept of static methods correctly - there is only one instance of method which means only one DB connection - so on a high traffic website - while one request is being served - the other requests will be queued for the same method right? So just wanted your thoughts and inputs on whether it makes sense to declare access methods as static or not. Thanks much A: I think you may have a skewed understanding of the processes at hand here. Every individual request of an individual visitor is served completely independent of each other. Imagine these 2 independent requests: Request visitor 1 Request visitor 2 index.php index.php creates Zend_Db instance $db creates Zend_Db instance $db calls $db->insert() calls $db->insert() calls $db->insert() again calls $db->insert() again \ / \ / \ / Database Queue might be something like: 4. insert 2 from request 2 3. insert 2 from request 1 2. insert 1 from request 2 1. insert 1 from request 1 In other words: basically only the database itself is troubled with queuing the SQL statements. The PHP scripts work independent of each other. So whether you create instance methods or static methods is completely irrelevant to how the SQL queries are being queued. A: A static method doesn't necessarily mean that there is only one, it means you don't need an instance of the class to call a method. The Singleton Pattern can be used if you only want 1 instance of an object to exist for the lifetime of a request. Each individual user requesting a page would get their own instance of that object, but they could only have one of each. As fireeyedboy said, the database would be responsible for queuing up the requests as they came in. In the case of a large influx of requests, each page's calls to interact with the database may have to wait for earlier requests to be processed first, causing some delays to processing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hook into the end of an asynchronous javascript call I'm calling a javascript function provided by a third-party. This function fires off a few ajax/asynchronous requests before returning, and (impolitely) neither allows me to pass a callback, nor returns any references to the asynchronous calls it is making. Is there any way I can trigger something when all of the calls it's making complete? Is there a way I can track 'calls' launched from a javascript function? Forgive my terminology; I'm a javascript beginner. A: Is this a library that's loaded from an external source, or do you have your own local copy? In the latter case, you could patch the code to do what you want. Otherwise, I don't really see a way to directly intercept the calls. If you know exactly what state changes occur for each completed async call, you could set a function to execute on an interval (setInterval(fn, millis)) and check whether all those states have been met. Then, you could fire off some sort of final function to indicate completion. ie: var completionHandler = function() { /* do something awesome */ } var checkCompletion = function() { if (state1 && state2 && state3) { clearInterval(interval); // make sure you clear the interval. completionHandler(); } } var interval = setInterval(checkCompletion, 200); A: If your third party script is based on jQuery you could try to modify the ajax behaviour with $.ajaxSetup(), set a context object and bind a ajaxComplete handler to this object. But that might mess up the third party library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I check the return value of an SQL query in PHP? So if I have the code: $result = mysql_query("SELECT password FROM users WHERE username = '$username'"); $return = mysql_fetch_assoc($result); I then want to check the returned value, namely, the value of "password". Therefore, I tried this: if ($return['password'] == $password) { login_success(); } However, that code just puts PHP into some sort of crazy loop mode where it prints out the page content again and again endlessly until I close my browser. So how do I check the return value of password against the text stored in the variable password? A: For check login purpose follow below code $username=$_REQUEST['username']; $password=$_REQUEST['password']; $query="select * from users where username='$username' and password='$password' "; $result=mysql_num_rows(mysql_query($query)); if($result>0) { echo "Login Success"; } else { echo "Login Failed"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Apache Problem, phpinfo gives following arror Simply calling phpinfo(); gives the following info.. Fatal error: Using $this when not in object context in /var/www/phpinfo.php on line 2 It is a fresh Ubuntu + Apache install on Amazon EC2. A: not possible, there has to be something else in the file. <?php phpinfo(); ?> A: You might be using $this->phpinfo(); Try using simply phpinfo(); More info here http://php.net/manual/en/function.phpinfo.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7509539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Join tableA.column1 to tableB where tableA.column1 is between tableB.column2 and tableB.column3 I have two tables: user, zone # user table CREATE TABLE `customers_users` ( `userid` INT(10), `username` VARCHAR(12), `homePhone` VARCHAR(10) ) # zone table CREATE TABLE `zone` ( `id` INT(10), `range_from` VARCHAR(10), `range_to` VARCHAR(10), `zone` VARCHAR(10) ) The zone table defines what zones different telephone numbers fall under. Given a zone table of: | range_from | range_to | zone | | 0260000000 | 0261000000 | Zone 1 | | 0261000001 | 0262000000 | Zone 2 | | 0262000001 | 0263000000 | Zone 3 | The following would be the desired result : | homePhone | zone | | 0260000001 | Zone 1 | | 0260000011 | Zone 1 | | 0261000001 | Zone 2 | | 0261000101 | Zone 2 | | 0262000001 | Zone 3 | | 0262001001 | Zone 3 | The question is how do I join the user table to the zone table to acquire this result. A: Join conditions are quite flexible: select c.homePhone, z.zone from customers_users as c join zone as z on c.homePhone between z.range_from and z.range_to
{ "language": "en", "url": "https://stackoverflow.com/questions/7509541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Missing Integration Services option in SSMS I installed SQL Server 2008 R2 Express edition on a box that already had SQL Server 2008 Developer Edition installed in it. Now Integration Services will not show up in the connect drop-down menu in the object explorer. Any ideas why this is happening? Thanks. A: 2 Possibilities spring to mind: * *You are using Management Studio Express which doesn't support SSIS *You have done what I just did & have installed "Management Tools basic" & left out "Management tools - complete" Either way the solution is to run a SQL 2008 install (not express), choose "add features" & check "management tools - complete" A: There's another angle to this one. If you have SQL Server 2008 already installed, you need to select the upgrade option. If you don't, then in your installation of SQL Server 2008 R2 your "management tools - complete" will be grayed out when you get to the install items choice screen. Hover over it and it will tell you as much. Hope this helps someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: dynamically resizable div jquery my Proplem is when i creat div use var toprint= "<div id='any' class ="resizable sort">content</div> <div id='any2' class ="resizable darg">content</div> "; then add to page use this code $(ui.item).html(toprint); it be sortable only not resizable too $('.sort').sortable({ handle:'.widget-head', connectWith: ".sort", out: function (e,ui) { $(".sort").children().resizable({ axis: 'x', containment: 'parent', resize: function(event, ui) { ui.size.width = ui.originalSize.width; (ui.helper).css({'position': '', 'top': '0px'}); } }); } }); A: Try this it might work. $('.sort').live('click', function() { $(function() { $('.sort).children().resizable({ axis: 'x', containment: 'parent', resize: function(event, ui) { ui.size.width = ui.originalSize.width; (ui.helper).css({'position': '', 'top': '0px'}); }); }); }); }); A: its work now just need live function :) <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Resizable - Maximum / minimum size</title> <link rel="stylesheet" href="http://jqueryui.com/themes/base/jquery.ui.all.css"> <script src="js/jquery.min.js"></script> <script src="js/jquery-ui-1.8.13.custom.min.js"></script> <style> #resizable { width: 440px; height: 150px; padding: 5px; border-right:5px #3C0 solid; } </style> <style type="text/css"> .tableres { border-collapse:collapse; } .tableres, td, th { border:1px solid black; } .ul1 { } </style> <script> $('.ul1').live('click', function() { // Bound handler called. $(function() { $( ".ui-widget-content" ).resizable({ maxWidth: 780, minWidth: 100 }); }); }); </script> </head> <body> <div class="demo"> <table class="tableres" width="880px" cellspacing="0" cellpadding="0"> <tr> <td width="10%" align="center" valign="top"><div id="resizable" class="ui-widget-content ul1"></div></td> <td width="90%" align="center" valign="top"><div class="ul1" >make me resize</div></td> </tr> </table> </div><!-- End demo --> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7509553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Canvas with Zoom Animation i am developing a small app in WPF and trying to set up an animation of zoom (using ZoomSlider) for a canvas but without good result ,do you have any suggestion how do a nice animation meantime is zooming the Canvas? Thanks so much for your attention . Cheers A: Jossef Goldberg posted a VirtualizedCanvas for WPF way back in 2008 on his blog. The code not only contains a virtualized canvas (which you probably don't neeed - it is usually overkill) but also has some gestures such as (animated) zooming and panning. You can download the code from his blog: https://learn.microsoft.com/en-us/archive/blogs/jgoldb/virtualized-wpf-canvas This should give you a great starting point how to do it for your own canvas.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binary addition/subtraction I am having a bit of trouble understanding Carry Flag (CF) and Overflow Flag (OF). Here are some sample problems I am working on: 1. 1011 1111 2. 1111 0111 3. 0111 1110 --> 0111 1110 + 1011 0111 + 1101 1101 - 1011 0000 --> + 0100 1111 ___________ ___________ ___________ + 1 0111 0110 1101 0100 ___________ 1100 1110 * *The carryout of the sign position is 1 and the carry in to the sign position is 0, so OF = 1? *The carryout of the sign position is 1 and the carry in to the sign position is 1, so OF = 0? *The carryout of the sign position is 0 and the carry in to the sign position is 1, so OF = 1? I guess I am having trouble understanding an unsigned overflow and the appropriate CF value. A: Disclaimer: I'm not an expert (or even a user of this level of code :) ). I believe the carry-flag makes sense for unsigned data, and the overflow-flag makes sense for signed data. Both will always be generated, but it is up to you to determine if you consider the values unsigned, or two's complement, so it is up to you which flag you pay attention to. From: http://en.wikipedia.org/wiki/Overflow_flag Internally, the overflow flag is usually generated by an exclusive or of the internal carry into and out of the sign bit. As the sign bit is the same as the most significant bit of a number considered unsigned, the overflow flag is "meaningless" and normally ignored when such numbers are added or subtracted. The sign bit is the most significant bit (the one farthest left). Exclusive or (XOR) is: * *If neither: 0 *If either: 1 *If both: 0 Carry-in to the sign bit is when the 2nd most significant bits, when added, produce a value to be carried over to the next column. Carry-out is whether carry must be done when adding the most significant bits (the sign bits, if the numbers are two's complement) together. XOR those two values, and you should end up with the value for your overflow flag after a given addition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: BinarySearch - Replace a string element with another string element once found How do I make a binary search replace an element of an array of strings with another element of an array of strings? This is the final part of my program and I don't get it...I know with char's you use strcpy, or .replace, etc. I have a struct that has an "orginalWord" and a "replacementWord", then a string array of "inputword"'s, it takes the inputword, finds it within the struct array (comparing to the orginalWord), and once found (Which it does find it...that part works, it finds the correct element number, so I know the searching is correct) replaces the "inputword" with the "replacementword". I just can't make it replace the element within the "inputword" with the "reaplcementWord" it finds. Help please!! I'll post the Binarysearch function seperate from the rest of my code for easy of reading. I know this should be simple, but I can't remember for the life of me. Example: So...searchitem is inputword[20] = "Like". Sruct Array... encryption[50].OrginalWord = "Like". Match found...encryption[50].ReplacementWord = "Ducks". I would like to put "Ducks" into inputword[20]. How would I do this using the BinarySearch? //Function call within main: for(number=0; number < plaincount; number++) { BinarySearch(encryption, count, inputword[number]); } int BinarySearch (StringPair correctword[], int size, string searchitem) { int middle =0, start = 0, last = size-1; bool found = false; int position = -1; while (!found && start <= last) { middle = (start + last)/2; // Midpoint // Was a breakpoint here, why? if(correctword[middle].orginalWord == searchitem) { position = middle; cout << "Replacing word: " << searchitem << " With: " << position << endl; searchitem.swap(correctword[position].replacementWord); found = true; return position; // Return new value for inputword array? } else if (correctword[middle].orginalWord < searchitem) { start = middle+1; } else last = middle-1; } cout << "Misspelled word found: " << searchitem << endl; return false; } A: If searchitem is going to be modified, you need to pass it by reference: int BinarySearch (StringPair correctword[], int size, string &searchitem)
{ "language": "en", "url": "https://stackoverflow.com/questions/7509563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can i break the line in JOptionpane message box <script language="javascript"> <![CDATA[ importPackage(javax.swing); importPackage(java.lang); System.out.println("Hello from JavaScript!"); var optionPane = JOptionPane.showMessageDialog(null,'Deployment instruction = ' + Deployment_Instrution); ]]> </script> here Deployment_Instruction is variable in which i am storing the output of sql select query. the output of sql select query length is too much big so the size of JOptionpane message box is also going bigger. for this i want to break the big line in message box. how can i do this.pls help[ me out asap. thanks in advance.... A: I guess you'll have to break the line by inserting newlines where appropriate. For a simple application like this it might do to just have a basic function that breaks on spaces once a line reaches the maximum length that you want. Something like: var boxText = wrapLines( 30, Deployment_Instruction ); JOptionPane.showMessageDialog( null, boxText ); Here the maximum length would be 30 characters. With the wrapLines function being: function wrapLines(max, text) { max--; text = "" + text; var newText = ""; var lineLength = 0; for (var i = 0; i < text.length; i++) { var c = text.substring(i, i+1); if (c == '\n') { newText += c; lineLength = 1; } else if (c == ' ' && lineLength >= max) { newText += '\n'; lineLength = 1; } else { newText += c; lineLength++; } } return (newText); } Note that this will give a 'ragged' right edge, so if there is a very long word at the end of a line it may not be satisfactory. By the way your variable name is missing a letter 'c' - Instru?tion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql Distinct function nested within other function in select Is there a way we can use disctinct for below cd.date_id? It's getting concatenated but I would also like distinct function aswell so it's like GROUP_CONCAT( CAST( distinct(cd.date_id) AS CHAR ) ) As date_id but it does not seem to work... SELECT b.bar_id, b.bar_name, b.bar_image, b.bar_lat, b.bar_lng, b.bar_address, b.bar_phone, b.bus_web, b.bar_open_hours, c.coupon_id, c.coupon_text, bc.coupon_start_time, bc.coupon_exp_time, GROUP_CONCAT( CAST( cd.date_id AS CHAR ) ) As date_id, d.calender_date, bc.bc_id, bc.priority As priority FROM bars b JOIN bars_coupons bc ON (bc.bar_id = b.bar_id) JOIN coupons c ON (bc.coupon_id = c.coupon_id) JOIN calendardates cd ON (cd.bc_id = bc.bc_id) JOIN date d ON (d.date_id = cd.date_id) GROUP BY cd.bc_id A: DISTINCT inside there would not make any sense. What do you want to do here exactly? It seems you want only one row per distinct cd.date_id. If that's the case just add cd.date_id to your GROUP BY clause at the end. Like this: GROUP BY cd.bc_id, cd.date_id And as you are using MySQL, you need not worry about using aggregate functions on all selected columns, if they would have the same value in all rows Grouped by the Group By clause, if not MySQL will just pick the first one UPDATE Looking at documentation for GROUP_CONCAT, you might be able to do it like this GROUP_CONCAT( DISTINCT CAST(cd.date_id AS CHAR) ) As date_id
{ "language": "en", "url": "https://stackoverflow.com/questions/7509566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: rails devise plugin has created a users table. How can I add to it? I created the following with the devise rails plugin. How do I go about adding a username string and unique user_id integer to the users table? Also is it necessary to create a users_controller when using devise? Or is that not necessary? class DeviseCreateUsers < ActiveRecord::Migration def self.up create_table(:users) do |t| t.database_authenticatable :null => false t.recoverable t.rememberable t.trackable # t.encryptable # t.confirmable # t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both # t.token_authenticatable t.timestamps end add_index :users, :email, :unique => true add_index :users, :reset_password_token, :unique => true # add_index :users, :confirmation_token, :unique => true # add_index :users, :unlock_token, :unique => true # add_index :users, :authentication_token, :unique => true end def self.down drop_table :users end end A: The guide linked to in the comments will provide good reading on migrations, which you will come to use very frequently. In short, however, you can generate the migration needed by doing: rails g migration add_username_to_users username:string Once the migration is created, you can actually add the column by doing: rake db:migrate A: To answer to your last question, no, you don't need to create a controller to use devise Although you could do if you wanted to have an index or show page for your users. In which case you would need to modify your routes a little
{ "language": "en", "url": "https://stackoverflow.com/questions/7509569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not able to import the another project as a library? I am going to licensing my Application. I know all the process for licensing application. But for that I have to load the Library Project in My Workspace. I have loaded the Library Project in my WorkSpace then i have imported it into my Original project. It works great. But now the problem is, If i have once deleted that library project and then if i have imported into workspace from another location and if i import it in to my that project then it is not going to import it. And if i Import it from the previour one location, then its again works fine. . . So why it is happening like that? Why i am not able to import the library project from any location? Please guide me for this. Thanks. A: I dont know why it is happend. But if you have import once from any location. and then delete it. Now if you are imported the same project from another location than it is also not going to imported. For sollution you have to Put that library project at once place for which you what it every time. And if necessary then do not delete that library project after Importing it to the Original Project. Thanks. A: From your question, i am assuming that you want to import any library into your project and if you want to use any library(.jar) then you can do these steps: * *create "libs" folder inside your application's structure, at same level of "src" directory. *Now copy those libraries into this libs folder. *Right click on any librarary -> Build Path -> Add to Build Path. Update: As you have commented below as its library project, i would suggest you to go through this Android doc on Setting up a Library Project A: If you want to include a project to your current project follow the steps, 1.) Right Click(or Alt+Enter) on the project_as_library->Library-> check mark Is Library 2.) Right Click(or Alt+Enter) on the project where you want to include the Library, go to Android->Library->Add. When you click Add you will see the Project name that you declared as Library, selected that and Press Ok and you are done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: alternative to php to perform data mining computation i'm working on a website that performs a lot of data mining and machine learning calculation thus very computationally expensive i'm using zend framework, redis and mysql to build the website and so far everything works perfect because the traffic isnt that huge however i'm feeling that at some point , when the traffic is bigger ,i will have to worry about the performance of php doing huge Data analysis and a lot of computation. i wanna tackle the problem now and think about an alternative solution to php to perform all my data mining and machine learning operations. i was thinking about setting up a job server and rewrite some codes in C or C++ and call it from php with gearman or any library that does work distribution. what do you guys think ? i just wanna know if there are better options out there ? A: I'm not sure if it would fit your scenario or if you've already tried it, but Zend Framework has Zend_Queue that can talk to messaging/queue servers or store them later for php to process. See the Zend Queue Adapters for references on powerful job processors you can talk to with zend. You could also write the intense processing stuff in C/C++ and execute them directly from ZF you would just need to figure out a way to wait for the jobs to complete, or something to periodically check for completed jobs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: string as parameter in a function i wrote a function to search if its parameter is in a given table obtab1.txt....the optab table has two columns out of which the parameter can only be in the first column....in the aviasm.h file i wrote this code.... class aviasm { public: aviasm(char *,char *); ~aviasm(); void crsymtab(); bool in1(string ); } In the aviasm.cpp file i wrote... bool aviasm::in1(string s) { ifstream in("optab1.txt",ios::in);//opening the optab1.txt char c; string x,y; while((c=in.get())!=EOF) { in.putback(c);//putting back the charcter into stream in>>x;//first field in>>y; if(x==s) return true; else return false; } } but i encountered several errors on compiling.... 'bool aviasm::in1(std::string)' : overloaded member function not found in 'aviasm' 'aviasm::in1' : function does not take 1 arguments 'syntax error : identifier 'string' ...can anybody help?? A: It appears as though you are trying to use string without the proper declarations, you will need this at the top of your file: #include <string> using std::string;
{ "language": "en", "url": "https://stackoverflow.com/questions/7509573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python IDLE won´t start I´m a noob in python and about a week ago IDLE stop working, I have readed some other people questions about this, but none of them had the same error that I´m getting, which is: Traceback (most recent call last): File "c:\python26\Lib\idlelib\idle.py", line 21, in <module> idlelib.Pyshell.main() File "C:\python26\Lib\idlelib\PyShll.py", line 1386, in main root = Tk(className="Idle") File "C:\python26\Lib\lib-tk\Tkinter.py", line 1643, in __init__ self.tk = _tkinter.creat(screenName, baseName, className, interactive, want objects, useTk, sync, use) _tkinter.TclError: Can´t find a usable init.tcl in the following directories: C:/Python26/lib/tcl8.5 c:/lib/tcl8.5 c:/lib/tcl8.5 c:/library c:/library c:/ tcl8.5.2/library c:/tcl8.5.2/library This probably means that Tcl wasn´t installed properly. So I have reinstall python about 3 to 4 times and I keep getting the same error. I´ll will for ever be in debt to anyone that gives me a solution to this error. By the way, I´m running Python 2.6.6 on Win 7 32-Bit. Thank you. A: This TCL issue has appeared in a number of Python forums and is generally prevents the IDLE GUI from starting e.g. http://www.gossamer-threads.com/lists/python/python/902912 and is related to the TCL_LIBRARY enviroment variables. Try and edit the enviroment variables Right click on (My) Computer, go to properties, Advanced Tab, press Environment Variables and edit TCL_LIBRARY to indicate the Python path e.g C:\Python26\tcl\tcl8.5 (or enter the path that represents your version. Idle should start then. I noticed that this is an issue when you install other programs that may depend on the TCL Library. Happened to me after I installed SciLab. Therefore changing the variable may cause issues with another installed app. Hope this helps. A: Some folders may have been deleted or removed. Go to Uninstall Program Choose Python Click "Change" Then click "repair" Allow the computer to repair....Should work after this. Some notes* Always make sure everything is in the same directory that you are working in CMD. I opened up my directory from the cmd and put my files in the same directory. Check your 'App data' folder too for any Python files. Be aware that 'App data' folder may be hidden. Also when you reinstall click customize and python will allow you to make your own customize path location which is helpful and a lot more simple then what python chooses. A: This could be caused by using the wrong version of Python. 32-bit and 64-bit work differently. A: (Assuming your Python install is not corrupt. Did you make any changes to the Python install, try and install anything else?) What is your Python install directory? Look under Python_install_directory/tcl , init.tcl should be there, is it? Tell us what you find. A: Hey I don't know why this worked for me but I just right clicked on the the idle icon and clicked "Duplicate". This created another icon "IDLE duplicate", weirdly, and when I try to open this version it works. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7509579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating a PowerShell Connection String I have been trying to create a ConnnectionString that will allow me to connect to my local database using PowerShell. Below is my code: $conn = New-Object System.Data.SqlClient.SqlConnection $conn.ConnectionString = "Server=localhost;Database=test;Uid=<username here>;Pwd=<password here>;" $conn.Open() $sql = "SELECT EMP_STATUS FROM test_table" $cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn) $rdr = $cmd.ExecuteReader() while($rdr.Read()) { $test = $rdr["EMP_STATUS"].ToString() } Write-Output $test However, I have NO CLUE what I am doing wrong and have been pulling my hair out for quite some time. Can anyone help me figure out what I am doing wrong in the ConnectionString? Thanks everyone!! I realized that my first problem was that I have MySQL database, not SQL database. As a result, I will have to connect using a different method. This is exactly where I need your help!! So far I have modified my code as follows: [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data") $conn = New-Object MySql.Data.MySqlClient.MySqlConnection $connString = "server=localhost;port=3306;uid=<username here>;pwd=<password here> ;database=test;" $conn.ConnectionString = $connString $conn.Open() $sql = "SELECT EMP_STATUS FROM test_table" $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql,$conn) $rdr = $cmd.ExecuteReader() $test = @() while($rdr.Read()) { $test += ($rdr["EMP_STATUS"].ToString()) } Write-Output $test However, here are a few more questions: 1) How do you use the MySQL .NET connection tool to connect to a local MySQL database? 2) Where should this PowerShell script be saved? 3) Are there any additional changes I should make? Thanks so much A: try this: $conn.ConnectionString = "Server=localhost;Database=test;User ID=<username here>;Password=<password here>;" then $test give you only the last value found in the select! To have $test containing all value from select change your code like this: $conn = New-Object System.Data.SqlClient.SqlConnection $conn.ConnectionString = "Server=localhost;Database=test;User ID=<username here>;Password=<password here>;" $conn.Open() $sql = "SELECT EMP_STATUS FROM test_table" $cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn) $rdr = $cmd.ExecuteReader() $test = @() while($rdr.Read()) { $test += ($rdr["EMP_STATUS"].ToString()) } Write-Output $test
{ "language": "en", "url": "https://stackoverflow.com/questions/7509591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating a dialog in new thread Suppose if i create a thread using CreateThread, and I want a modal or modeless dialog in that thread. Do i need to use a seperate message loop for that like I have here, while(GetMessage(&msg, 0, 0, 0)) // Get any window messages { TranslateMessage(&msg); // Translate the message DispatchMessage(&msg); // Dispatch the message } But for modal dialog, you don't use that, so why shouldn't it work when i create a dialog? A: When you use a modal dialog, it creates its own message queue, that's why it works. If you want to use modeless dialogs then you will have to create a message queue yourself. From the documentation for DialogBox: The DialogBox macro uses the CreateWindowEx function to create the dialog box. (snip) and starts its own message loop to retrieve and dispatch messages for the dialog box.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how does facebook push their changes to the live site From this video https://www.facebook.com/photo.php?v=778890205865 I understood that Facebook moves their changes to their live site on a daily basis. Some changes are visible, whereas most of them are not visible to the end user. With a userbase of just over 700 million how do they manage to do it without any glitches. Can someone throw light on this? I have read about the Gatekeeper which allows Facebook to run different code to different set of users. Is there any other technology involved? thanks. A: From what I've read, they push code to their internal users first, so that staff are using the 'alpha' code. It's then pushed to the beta teir (sunday I think) which lets developers test against the beta code and report any issues The beta tier is then pushed live on Tuesday night to the main website
{ "language": "en", "url": "https://stackoverflow.com/questions/7509595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Alternating Threads Could you point me in a direction for discovering how threads are being alternated in the Linux kernel? A: Although I do not possess in depth knowledge about the kernel, but AFAIK to the kernel threads (& processes) appear as tasks. The switching between tasks is known as context switch. Context switch is triggered by scheduler through schedule call which is present in kernel/sched.c ( http://lxr.linux.no/linux+v3.0.4/kernel/sched.c#L4247 ). In schedule function context_switch is called which switches memory map & register values for the new thread. I would suggest looking at schedule function. P.S.: You can use http://lxr.linux.no for browsing kernel code online. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7509599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dont remove(just hide) the previous data when ajax updated a page ? In case I have a need to revisit the previous data , while updating webpages through ajax is it advisable to keep caching the visited data in hidden tabs or hidden divs(instead of just replacing it with new data) so that when the user needs the same data, there is no need to touch the server again ? A: It depends on how often it is likely to happen, and how much that extra data might effect your page. If you user is likely to go back and forth between the data fairly often, and the hits on your server would pile up, then you might wanna keep the data on the page. But if the data on the page has a lot of event listeners and would slow down querying for elements, then your page might run faster by not bogging down the page with all the extra data. A: Unless the amount of data is really, really huge, it doesn't hurt to just keep it around. So in most cases it is advisable to just hide the old data rather than replacing it (hide it either by setting the display style in the DOM, or by detatching the element and storing it in memory for later, the latter method usually done with the help of a framework). In vanilla javascript, you can just apply the style element.style.display = 'none'; where element is a reference to the DOM element you want to hide. To show it again later, you'd do element.style.display = 'block'; (assuming it is a block element -- you can also do inline, etc... as appropriate).
{ "language": "en", "url": "https://stackoverflow.com/questions/7509600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery-ajax: pass values from a textfield to a php variable (same a file) jquery-ajax: pass values from a textfield to php file and show the value i made a variation of the link above this time using only one file and no div tag. test.php <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $("#submit").click(function(){ var dataString = $("#inputtext").val(); $.ajax({ type: "POST", url: "test.php", data: "dataString=" + dataString, success: function(result){ window.location.reload(true); } }); window.location.reload(true); }); }); </script> </head> <body> <input type="text" id="inputtext"> <input type="button" id="submit" value="send"> <?PHP if(isset($_POST['dataString'])){ $searchquery = trim($_POST['dataString']); print "Hello " . $searchquery; } ?> </body> </html> value from dataString won't show. why? A: Sorry for the question, but what's the point of using ajax to reload the same page?? Use it to call another page and then load the result, not the way you're doing it. Try this In test.php: $("#submit").click(function(){ var dataString = $("#inputtext").val(); $.ajax({ type: "POST", url: "anothepage.php", data: dataString, success: function(result){ $('#result').html(result). } }); return false; //so the browser doesn't actually reload the page }); And you should actually use a form, not just inputs. And use the name attribute for them, or php won't pick the value! ID is for javascript and css. <form method="POST" action=""> <input type="text" id="inputtext" value="" name="inputtext"> <input type="submit" id="submit" value="send" name="submit"> </form> <div id="result"> <!-- result from ajax call will be written here --> </div> In anotherpage.php: if(isset($_POST['inputtext'])){ $searchquery = trim($_POST['inputtext']); echo htmlentities($searchquery); // We don't want people to write malicious scripts here and have them printed and run on the page, wouldn't we? } A: When you refresh the page using JavaScript, you lose any POST parameters you sent to the page. That is one reason why you never saw any valid results. You are also missing the benefits from using AJAX - A motivating reason to deploy AJAX is to remove the requirement to refresh the page while still accepting and processing user input. If you prefer to process the data from AJAX on the same page that is serving the HTML, here is a working example based on your supplied code. <?php if( isset($_POST['dataString'])) { echo 'Hello ' . trim( $_POST['dataString']); exit; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> <title>Testing jQuery AJAX</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $("#submit").click(function(){ var dataString = $("#inputtext").val(); $.ajax({ type: "POST", url: "test.php", data: "dataString=" + dataString, success: function( data){ alert( data); } }); }); }); </script> </head> <body> <form action="test.php" method="post"> <input type="text" id="inputtext" /> <input type="button" id="submit" value="send" /> </form> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7509604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Conversion of binary to octal or hex. Which one is easy (C language compiler) I was going through some questions related to C programming language. And i found this question to be confusing. http://www.indiabix.com/c-programming/bitwise-operators/discussion-495 The question is "is it easy for a c compiler to convert binary to hexadecimal or binary to octal. The explanation given there is group every 4 bits and convert it to hex.. but its very easy to group 3 bits and convert it to octal. or is it easy for a human to convert octal easily than hex? what would be the easiest method of a compiler to convert binary to octal/hex A: All of them are the same in easiness. However, in computing world the use of octal is kinda seldom compared to hex. The only quite important use is on unix style permissions, other than that it's hex and binary that takes the lead (along with decimal for common human friendly style). A: Both octal and hexadecimal can be converted from binary by grouping the bits(3 in case of octal and 4 in case of hexadecimal) http://www.ascii.cl/conversion.htm But the thing is that the memory allocate by compiler is in 2^n and you can't split 2^n 3 size blocks while it can be done easily with hexadecimal where block size is 4 for example with gcc concider integer of 32 bits which can't be split into equal 3 bit 32/3 = 10.666 while it can be split in to 4 bits block 32/4 = 8 Hope I make my point clear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MPMoviePlayerController bug or feature: Setting initialPlaybackTime to t seconds hides the time-slider upto t Say a movie is 10 min long and I am setting initialPlaybackTime to the 1 minute mark, like thus: NSString *urlStr = @"http://<ip>/vod_movie.m3u8"; // 10 minute long video MPMoviePlayerController* playerController = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:urlStr]] ]; [playerController prepareToPlay]; [playerController setInitialPlaybackTime:60]; // Want to play from the 1 minute mark This results in the video starting to play from the 1 minute mark, but the time-slider hides the part before 1 min, so there is no way you can seek backwards. A: This is the intended behavior of initialPlaybackTime. I don't know of any recommended solution for what you are trying to do, but you could try setting initialPlaybackTime to -1 and after the video starts playing use setCurrentPlaybackTime to scroll to the position in the movie that you want the playback to start at.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Gorm vs. Hibernate Mapping in Grails? I know that Gorm uses Hibernate under the covers to achieve what it does. As of yet I have not found a way to use the hibernate mapping strategy for inheritance with a per-table-subclass with Gorm and therefore I am not sure that I should use Gorm. I want a base class for most of the persisted classes in my web-app that contains a Created Date, an Updated Date, and a boolean value called Deleted (as these will be common fields between the classes). I'd like to be able to keep track of the fields that are common to most of the classes which is the purpose of my base class. I've worked with Matt Rabile's Appfuse project in the distant past which generated all of the hibernate config files for me. Would it be worth it to use hibernate config files (for this and other unforseen future circumstances), or should I just use GORM, and ignore my OCD tenancies to put the common persisted fields in a base class? A: If you would like to use table-per-subclass that can be done by setting the mapping as follows: static mapping = { tablePerHierarchy false } There is more documentation here. I have used this option and it will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to modify Request.JSON to satisfy cross domain security I'm using mootools to request json from my web handler and this is working fine from the same machine. I've read in places about need for a callback to satisfy cross domain issues but unsure how to apply this. I'd like to run this code from another domain. var input = []; var jsonRequest = new Request.JSON({ url: "http://www.mysite.com.au/GetImages.ashx?p=2", onSuccess: function (result) { for (var i = 0; i < result.length; i++) { // alert(result[i].MediaPath); var s = result[i].MediaPath.split('|'); for (var j = 0; j < s.length; j++) { // alert(s[j]); input.push(s[j]); } } } }).get(); cheers! A: One solution is to use JSONP. Here is the client-side code you would use: <script> function onSuccess(result) { for (var i = 0; i < result.length; i++) { // alert(result[i].MediaPath); var s = result[i].MediaPath.split('|'); for (var j = 0; j < s.length; j++) { // alert(s[j]); input.push(s[j]); } } } </script> <script src="http://www.mysite.com.au/GetImages.ashx?p=2&callback=onSuccess" ></script> <!-- !!! Notice that the src now has a "callback" paramater which the client is passing to the server. --> Here is what the server would respond with: onSuccess( { 'your':'json', 'data':'here' } ) The trick which makes this work is that the server no longer technically returns json data. Instead, it will return json data wrapped by a javascript function (which the client-side code will define) that will automatically be executed by the browser because that's what browsers do with tags. If you need to have it dynamically gathered, then you can have javascript code create a script element, add the url as the 'src' attribute, then append the script tag to body to have the browser execute it. This hack is a very standard way to dynamically download scripts. MooTools might already have a way to do this. Downside with my suggestion: it is no longer asynchronous. A: Another potential solution is to have your server proxy the json requests from other sites. I am unfamiliar with how this would be done, but I think that the SOAP protocol implements this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Function counting characters of a string class being skipped? I was trying to count the number of characters in a string class but for some reason the program is skipping over my function completely. This is just the test code from the main program, it still was giving me the same results. How come the counter function is skipped over? #include <iostream> #include <string> using namespace std; void prompt(string& dna) { cout << "Input: "; getline(cin, dna); } void counter(const string DNA, int* a_count, int* t_count, int* c_count, int* g_count) { for (int i = 0; i < DNA.size(); i++) { if (DNA.at(i) == 'a') { *a_count++; } else if (DNA.at(i) == 't') { *t_count++; } else if (DNA.at(i) == 'c') { *c_count++; } else if (DNA.at(i) == 'g') { *g_count++; } } } int main() { string dna; int a = 0; int t = 0; int c = 0; int g = 0; prompt(dna); if (! dna.empty()) { cout << "Before:\n" << "A: " << a << endl << "T: " << t << endl << "C: " << c << endl << "G: " << g << endl; counter(dna, &a, &t, &c, &g); cout << "\n\nAfter:\n" << "A: " << a << endl << "T: " << t << endl << "C: " << c << endl << "G: " << g << endl; } system("pause"); return 0; } A: You're applying operator ++ the wrong way. It should be: if (DNA.at(i) == 'a') { (*a_count)++; } else if (DNA.at(i) == 't') { (*t_count)++; } else if (DNA.at(i) == 'c') { (*c_count)++; } else if (DNA.at(i) == 'g') { (*g_count)++; } A: You've got a priority problem between the ++ and * operators. You are incrementing the pointer address, not the value. (*a_count)++; would be correct. A: You may find it easier to use reference parameters for the counts instead, since you don't actually need to do any pointer arithetic. ie: void counter(const string DNA, int& a_count, int& t_count, int& c_count, int& g_count) And, yes a switch statement would be neater.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access user's text messages on iphone Is there a way to access a user's text messages (without an internet connection, obviously...not trying to take the client's messages) and analyze the text within an app? Totally understandable if there isn't (for security reasons), but I figured i'd ask anyway. A: Nope, you can only send them :S http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/SystemMessaging_TopicsForIOS/Articles/SendinganSMSMessage.html#//apple_ref/doc/uid/TP40010416-SW1
{ "language": "en", "url": "https://stackoverflow.com/questions/7509626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: On Android, How do I display html in ListView? I am feeding a ListView from a database in this way (nothing special), except COL_TXT_TRANSL2 contains html formatting: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); mCurrBookID = extras.getString("BookID"); mCurrChapterNum = extras.getString("ChapterNum"); mCurrChapterTitle = extras.getString("ChapterTitle"); mGitaDB= Central.mDB; this.setTitle(mCurrChapterNum+"."+mCurrChapterTitle); setContentView(R.layout.chapterdisplay); //set chapter intro TextView tvIntro=(TextView) findViewById(R.id.textIntro); tvIntro.setText(Html.fromHtml(extras.getString("ChapterIntro"))); try { String[] columns = new String[] { mGitaDB.COL_TXT_TEXT_NUM, mGitaDB.COL_TXT_TRANSL2 }; int[] to = new int[] { R.id.number_entry, R.id.title_entry }; mCursor=mGitaDB.GetGitaTexts(mCurrBookID, mCurrChapterNum); mAdapter = new SimpleCursorAdapter(this, R.layout.textslist_row, mCursor, columns, to); setListAdapter(mAdapter); } catch (Exception e) { String err="Error: " + e.getMessage(); Toast toast = Toast.makeText(Central.context, err, 15000); toast.show(); } } Now the problem is that the text displayed in this ListView has HTML formatting. How can I make listview display this HTML formatting? Currently it is displayed as a plain text with all tags. A: Assuming the HTML is fairly simple you can run it through this method: http://developer.android.com/reference/android/text/Html.html#fromHtml(java.lang.String) The resulting Spannable can be sent to a TextView in the ListView. Beware the fromHtml method is very slow and may slow down scrolling, you might want to cache the Spannables. A: Define a CharSequence ArrayList, include all the elements from your database to be displayed in this arraylist as HTML. Include a personal TextView layout for the individual entities of the listView, and display the Charsequence in the list. I had made use of the following code for my app: List<CharSequence> styledItems = new ArrayList<CharSequence>(); droidDB.open(); articles = droidDB.getAllArticleTitles(feed.feedId); droidDB.close(); for (Article article : articles) { styledItems.add(Html.fromHtml(article.title)); } ArrayAdapter<CharSequence> notes = new ArrayAdapter<CharSequence>(this, R.layout.feeds_row,styledItems); setListAdapter(notes); For the feeds_row.xml: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#FFFFFF"/> Hope this helps. A: My problem was similar to yours. I was reading data from file in json format, where I have objects with id and text fields. text field is html. I have resolved problem this way: ArrayList<MyObject> myObjectsList = new ArrayList<MyObject>(); ArrayList<HashMap<String, CharSequence>> tableElements = new ArrayList<HashMap<String, CharSequence>>(); String keyword = in.getStringExtra(TAG_KEYWORD); InputStream is = this.getResources().openRawResource(R.raw.data); JSONParser jParser = new JSONParser(); myObjectsList = jParser.searchForObjects(is, keyword); for (MyObject element : myObjectsList) { String id = Integer.toString(element.id); CharSequence text = Html.fromHtml(element.text); // creating new HashMap HashMap<String, CharSequence> map = new HashMap<String, CharSequence>(); // adding each child node to HashMap key => value map.put(TAG_ID, id); map.put(TAG_TEXT, text); // adding HashList to ArrayList tableElements.add(map); } ListAdapter adapter = new SimpleAdapter(this,tableElements, R.layout.search_item, new String[] { TAG_ID, TAG_TEXT.toString()}, new int[] { R.id.exercise_id, R.id.text }); setListAdapter(adapter);
{ "language": "en", "url": "https://stackoverflow.com/questions/7509627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to populate the state and city in my project without using AJAX and refresh page? I am looking a sample for the functionality where there are 2 drop downs. One is 1 is State/Province and the 2rd is City. Based on the state drop down selection, city drop down values should be populated. I need sample database design also.... Could anyone please help me out on getting a sample for this. Regards padman.. A: With neither Ajax nor refreshes? Bad idea, unless you have a very limited number of state/city combinations--otherwise the HTML/JavaScript you send will be huge. Otherwise it's a simple dependent select, which is searchable on the web. The nutshell version is that when your state changes, you take the value of the selected state option, use it to look up cities in a map of state id => cities, and use the cities collection to populate the second select box. The state/cities JavaScript structure is created on the server side using whatever template mechanism the rest of the app uses (I assume JSP or Velocity since you're using Struts 1). DB DB design for what? States and cities? Have a table of states. Have a table of cities with a state id foreign key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }