text
stringlengths
8
267k
meta
dict
Q: Android AsyncTask seems to stop after onPreExecute I've some problems with AsyncTasks in Android. I searched for hours for a solution but I don't get it... The Task should check via HTTP an account exists and safe an access key via SharedPreferences. Here is the AsyncTask code: (not integrated class!) package de.test.barcode; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.content.SharedPreferences; import android.os.AsyncTask; import android.view.View; import android.widget.ProgressBar; public class LoginTask extends AsyncTask<Void, Void, Void> { private String username, password; private ProgressBar progressBar; private SharedPreferences accPrefs; public LoginTask(String username, String password, ProgressBar progressBar, SharedPreferences accPrefs) { this.username = username.trim(); this.password = password.trim(); this.progressBar = progressBar; this.accPrefs = accPrefs; } protected Void doInBackground(Void... params) { ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); InputStream is = null; try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://{URL}"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ SharedPreferences.Editor prefEditor = accPrefs.edit(); prefEditor.putBoolean("is_using_account", true); prefEditor.putString("username", username); prefEditor.putString("password", password); prefEditor.putString("access_key", "null"); prefEditor.commit(); } try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; line = reader.readLine(); sb.append(line); is.close(); String accessKey = sb.toString(); if(!accessKey.equals("null")) { SharedPreferences.Editor prefEditor = accPrefs.edit(); prefEditor.putBoolean("is_using_account", true); prefEditor.putString("username", username); prefEditor.putString("password", password); prefEditor.putString("access_key", accessKey); prefEditor.commit(); } }catch(Exception e){ SharedPreferences.Editor prefEditor = accPrefs.edit(); prefEditor.putBoolean("is_using_account", true); prefEditor.putString("username", username); prefEditor.putString("password", password); prefEditor.putString("access_key", "null"); prefEditor.commit(); } return null; } protected void onPreExecute(){ progressBar.setVisibility(View.VISIBLE); } protected void onPostExecute() { progressBar.setVisibility(View.GONE); } } And here are the lines which (should) execute the AsyncTask: (all elements are defined right) LoginTask login = new LoginTask(username, password, progressBar, accountSettings); login.execute(); A: i usually have to executeOnExecutor to get it to work like this new PlayActivity().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); see this Android SDK AsyncTask doInBackground not running (subclass)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Selecting dynamic default value in I have a php script which updates user info. I have created an html form, which allows user to edit the values and enter new ones. Now when the form is loaded for the first time, it displays some default values taken from php variables. The works fine but the problem is with tag. <input type = "text" name = "name" class = "text" value = "<?php echo $user->name; ?>" /> this works fine.. <select name = "department" value = "<?php echo $user->department; ?>"> <option>Information Technology</option> <option>Computer Science</option> <option>Electronics & Communication</option> <option>Mechanical Engineering</option> <option>Civil Engineering</option> <option>Electrical & Electronics Engineering</option> <option>M.Tech</option> <option>MBA</option> <option>MCA</option> </select> how can I solve this issue? A: The Select tag doesn't have a value option. Use this instead: For example: <select name = "department"> <option value="IT" <?php if ($user->department == "IT") echo "selected='selected'";?> >Information Technology</option> <option value="CS" <?php if ($user->department == "CS") echo "selected='selected'";?> >Computer Science</option> </select> A: Something like this would work <select name = "department" value = "<?php echo $user->department; ?>"> <option value="1" <?= ( $user->department == 1 ? 'selected="selected"' : '' ) ?>> Information Technology </option> ... </select> A: This can be solved with one single if statement. For example: <select name = "department"> <option value="IT">Information Technology</option> <option value="CS">Computer Science</option> <?php if (strlen($user->department)>1 ) echo "<option value="."$user->department"."selected='selected >"."$user->department"."</option>";?> </select>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best Practice for "Evaluate Now, Respond Later"? Suppose I'm building a login system. The user enters a username and password into a field and it is sent via HTTPS to the server, which validates the login before the page loads. If a bad password is sent, the login obviously fails immediately, but one would want the error message to be displayed later in the page, near the login box. The obvious solution is to set a global flag and have the login box check it and add the error message if necessary, but my understanding is that global variables are best avoided. Is there another straightforward method of achieving this functionality? A: For a non-AJAX login page, it is common practice to redirect the user browser to the login page with an extra query parameter in the url, In pseudo-code, here is the login validation controller code segment: success = checkLogin(username,password) if (success == false) redirect('http://example.com/login?failedlogin=true') The login page controller would be responsible for detecting this query param and telling the view code to display a failure message. I don't believe the term 'global flag' applies to this practice so it should meet your requirements. If the login page uses Ajax, the Javascript on the login page takes the results of the AJAX call and updates the appropriate DOM elements with the failure message.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MKMapview transform rotate only the map content I need to transform-rotate a MKMapview based on the course of the CLLocations I get from CoreLocation. I basically have this already: mapview.transform = CGAffineTransformMakeRotation(degreesToRadians(course)); However, this is not good since this rotates the entire map, with annotations. Now I can fix the annotations, but the problem is it also rotates the Google logo! After searching all other posts here on this problem the main answer was this is not possible with the google logo but the thing is, I have seen some Apps (Trapster for example) that actually do this, they rotate the map but the google logo is always in the same place. So my question is, is there a new function I don't know about that purely rotates the content of the map, or do all these apps rotate the mapview, fix rotations of the annotations and perhaps add their own google image to the view containing the mapview? Thanks! A: Probably you could do by finding the right view with mapView.subviews. If I do: for (UIView *aView in mapView.subviews){ NSLog(@"view class: %@", aView.class); } I get back: view class: UILabel view class: UIView view class: UIImageView view class: UILabel I would guess one of these is the google logo and the map itself...
{ "language": "en", "url": "https://stackoverflow.com/questions/7571718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: difference between assigning between self. and assigning from ivar directly Possible Duplicate: When to use self on class properties? Difference between self.ivar and ivar? I know that when you do self.array = [[NSMutableArray alloc] init]; this means that I am calling the setter method. However, I can also do: array = [[NSMutableArray alloc] init]; Which is assigning the ivar directly, no setters is called (I assume). Sometimes both cases will have the same effect, sometimes not. So what is the crucial main difference between doing one over the other? Can someone explain this clearly.. A: If array property is retained then 1st one will cause a memory leak. In that case you are gaining ownership twice in one line, one via alloc and one via retained property. So one release is not enough. And in 2nd one if you release immediately after alloc then you loose the ownership immediately as you have not retained array in that case. A: The crucial difference is that the setter can have additional side effects — such as retaining the argument or issuing KVO notifications — while a simple assignment can't. A: The Objective-C Programming Language tells you to use direct access in the initializer: There are several constraints and conventions that apply to initializer methods that do not apply to other methods: * *If you set the value of an instance variable, you typically do so using direct assignment rather than using an accessor method. Direct assignment avoids the possibility of triggering unwanted side effects in the accessors. and in dealloc: Typically in a dealloc method you should release object instance variables directly (rather than invoking a set accessor and passing nil as the parameter), as illustrated in this example: - (void)dealloc { [property release]; [super dealloc]; } to avoid, as Chuck said, side effects like KVO notifications. Example: in my code I have a variable that triggers the preloading of related data in advance. Sometimes I release it or set it to nil to get rid of the variable, which means I don't need to preload anything, so I use direct access. This example is rarely the case, but it doesn't cost you anything to follow this convention.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight - Close Browser Window I have a Silverlight application that launches another Silverlight application in a new browser window. The new Silverlight application has a button called "Close". When a user clicks "Close", I run the following code: HtmlPage.Window.Invoke("close"); This code works on IE just fine. However, it does not work in Chrome. How do I write code that will close the window in both IE and Chrome? Thank you! A: It's a known issue in Chrome browser. To workaround it, insert the following line before you call "close": HtmlPage.Window.Invoke("open", new object[] {"", "_self", ""} ); HtmlPage.Window.Invoke("close");
{ "language": "en", "url": "https://stackoverflow.com/questions/7571736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a way to GROUP BY a time interval in this table? I have a table like this one: DateTime A 10:00:01 2 10:00:07 4 10:00:10 2 10:00:17 1 10:00:18 3 Is this possible to create a query that returns me the average value of A each 10 seconds? In this case the result would be: 3 (4+2)/2 2 (2+1+3)/3 Thanks in advance! EDIT: If you really think that this can not be done just say NO WAY! :) It's an acceptable answer, I really don't know if this can be done. EDIT2: I'm using SQL Server 2008. I would like to have different groupings but fixed. For example, ranges each 10 sec, 1 minute, 5 minutes, 30 minutes, 1 hour and 1 day (just an example but something like that) A: In SQL Server, you can use DATEPART and then group by hour, minute and second integer-division 10. CREATE TABLE #times ( thetime time, A int ) INSERT #times VALUES ('10:00:01', 2) INSERT #times VALUES ('10:00:07', 4) INSERT #times VALUES ('10:00:10', 2) INSERT #times VALUES ('10:00:17', 1) INSERT #times VALUES ('10:00:18', 3) SELECT avg(A) -- <-- here you might deal with precision issues if you need non-integer results. eg: (avg(a * 1.0) FROM #times GROUP BY datepart(hour, thetime), DATEPART(minute, thetime), DATEPART(SECOND, thetime) / 10 DROP TABLE #times A: It depends on DBMS you are using. In Oracle you can do the following: SELECT AVG(A) FROM MYTABLE GROUP BY to_char(DateTime, 'HH24:MI') A: Someone may come along and give you an answer with full code, but the way I would approach this is to break it down to several smaller problems/solutions: (1) Create a temp table with intervals. See the accepted answer on this question: Get a list of dates between two dates This answer was for MySQL, but should get you started. Googling "Create intervals SQL" should also yield additional ways to accomplish this. You will want to use the MAX(DateTime) and MIN(DateTime) from your main table as inputs into whatever method you use (and 10 seconds for the span, obviously). (2) Join the temp table with your main table, with a join condition of (pseudocode): FROM mainTable m INNER JOIN #tempTable t ON m BETWEEN t.StartDate AND t.EndDate (3) Now it should be as simple as correctly SELECTing and GROUPing: SELECT AVG(m.A) FROM mainTable m INNER JOIN #tempTable t ON m BETWEEN t.StartDate AND t.EndDate GROUP BY t.StartDate Edit: if you want to see intervals with that have no records (zero average), you would have to rearrage the query, use a LEFT JOIN, and COALESCE on m.A (see below). If you don't care about seeing such interals, OCary's solution is better/cleaner. SELECT AVG(COALESCE(m.A, 0)) FROM #tempTable t LEFT JOIN mainTable m ON m BETWEEN t.StartDate AND t.EndDate GROUP BY t.StartDate A: CREATE TABLE IF NOT EXISTS `test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dtime` datetime NOT NULL, `val` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; INSERT INTO `test` (`id`, `dtime`, `val`) VALUES (1, '2011-09-27 18:36:19', 8), (2, '2011-09-27 18:36:21', 4), (3, '2011-09-27 18:36:27', 5), (4, '2011-09-27 18:36:35', 3), (5, '2011-09-27 18:36:37', 2); SELECT *, AVG(val) FROM test GROUP BY FLOOR(UNIX_TIMESTAMP(dtime) / 10) A: I approached this by using a Common Table Expression to get all the periods between any given dates of my data. In principal you could change the interval to any SQL interval. DECLARE @interval_minutes INT = 5, @start_date DATETIME = '20130201', @end_date DATETIME = GETDATE() ;WITH cte_period AS ( SELECT CAST(@start_date AS DATETIME) AS [date] UNION ALL SELECT DATEADD(MINUTE, @interval_minutes, cte_period.[date]) AS [date] FROM cte_period WHERE DATEADD(MINUTE, @interval_minutes, cte_period.[date]) < @end_date ) , cte_intervals AS (SELECT [first].[date] AS [Start], [second].[date] AS [End] FROM cte_period [first] LEFT OUTER JOIN cte_period [second] ON DATEADD(MINUTE, 5, [first].[date]) = [second].[date] ) SELECT i.[Start], AVG(data) FROM cte_intervals i LEFT OUTER JOIN your_data mu ON mu.your_date_time >= i.Start and mu.your_date_time < i.[End] GROUP BY i.[Start] OPTION (MAXRECURSION 0) A: From http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=142634 you can use the following query as well: select dateadd(minute, datediff(minute, 0, timestamp ) / 10 * 10, 0), avg ( value ) from yourtable group by dateadd(minute, datediff(minute, 0, timestamp ) / 10 * 10, 0) which someone then expands upon to suggest: Select a.MyDate, Start_of_10_Min = dateadd(mi,(datepart(mi,a.MyDate)/10)*10,dateadd(hh,datediff(hh,0,a.Mydate),0)) from ( -- Test Data select MyDate = getdate() ) a although I'm not too how they plan on getting the average in in the second suggestion. Personally I prefer OCary's answer as I know what is going on there and that I'll be able to understand it in 6 months time without looking it up again but I include this one for completeness.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: FlexLib Windowshade and Flex 4 I'm trying to build a collapsible panel in Flex 4. I thought I'd use s/thing like this: <s:Panel width="100%"> <s:controlBarContent> <flexlib:WindowShade width="100% /> </s:controlBarContent> </s:Panel> But that throws an error: Instantiation attempted on a non-constructor. I grabbed the flexlib zip for flex 4 but I'm still getting that error. Is there another way to create a collapsible panel in a control bar? Thank you for any tips! A: You need to define the header renderer or header Class for the WindowShade component. Looking at their code where this exception occurs Exception is: TypeError: Error #1007: Instantiation attempted on a non-constructor. at flexlib.containers::WindowShade/createOrReplaceHeaderButton()[...\src\flexlib\containers\WindowShade.as:258] The code that throws exception is this if(_headerRenderer) { _headerButton = _headerRenderer.newInstance() as Button; } else { var headerClass:Class = getStyle("headerClass"); _headerButton = new headerClass(); } You need to define either a headerClass or a headerRenderer. For testing purposes i used <s:Panel width="100%"> <s:controlBarContent> <containers:WindowShade headerClass="mx.controls.Button" width="100%" /> </s:controlBarContent> </s:Panel> and it works like a charm :) Have fun and good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: COUNT() together with the rest of the table's columns What's the easiest way to select the number of rows found, together with other columns from the table? The only way I've found is to do a join with a sub-query, but I imagine it's more resource heavy than such a simple task should be... The result I'm looking for is SELECT lots_of_rows, count(*) FROM table with some magic, so it doesn't reduce everything in one row. f1 f2 f3 rowcount ---------------------- a b c 3 a c e 3 a r g 3 Or something like that. A: You can do it without a subquery, the last row will hold all nulls and the total rowcount in field rowcount SELECT lots_of_rows, count(*) as rowcount FROM atable GROUP BY atable.primary_key WITH ROLLUP Another option might is: SELECT lots_of_rows FROM atable; SELECT FOUND_ROWS() as rowcount; The second query will return instantly, because it just gives you the rowcount from the first query. See: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows A: Here's a way using an inline view, which will work even if your table doesn't have a primary key. By using an inline view, you don't have to use a join. Note: This was done on Oracle, but I believe the SQL should work for MySQL or require minimal tweaking. CREATE TABLE t1 (f1 CHAR(1), f2 CHAR(1), f3 CHAR(3)); INSERT INTO t1 VALUES ('a','b','c'); INSERT INTO t1 VALUES ('a','c','e'); INSERT INTO t1 VALUES ('a','r','g'); SELECT a.f1 , a.f2 , a.f3 , b.cnt FROM t1 a , (SELECT COUNT(*) cnt from t1) b Result: F1 F2 F3 CNT 1 a b c 3 2 a c e 3 3 a r g 3
{ "language": "en", "url": "https://stackoverflow.com/questions/7571747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Get variable & keep changes after postback This question is related to: Hide div on clientside click The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making. Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison. Html: <div runat="server" id="someDiv1" enableviewstate="true" > <asp:LinkButton OnClientClick="Show_Hide_Display()" ID="lbtnDiv1" runat="server" CausesValidation="true" OnClick="lbtn_onClickServer"> </asp:LinkButton> </div> <div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true"> </div> Javascript: <script type="text/javascript"> function Show_Hide_Display() { var div1 = document.getElementById("<%=someDiv1.ClientID%>"); var div2 = document.getElementById("<%=div2.ClientID %>"); if (div1.style.display == "" || div1.style.display == "block") { div1.style.display = "none"; div2.style.display = "block"; } else { div1.style.display = "block"; div2.style.display = "none"; } } </script> The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available. If it is available show a tick, if it isn't error. I got the error working and am trying to program the tick on client side. So OnClientClick I am able to toggle between some text and a tick. So I need to: * *Get the bool result from code behind *After postback keep tick (if username is available) I am almost there but can't quite figure the last two points out. A: If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback: Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback? Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel) A: The answer for the both questions lies of checking the boolean value send from the code behind. 1-----.in code-behind c# protected void Page_Load(object sender, System.EventArgs e) { var linkbtn = (Button)Page.FindControl("lbtnDiv1"); linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')"); } 2------- change your javascript function Show_Hide_Display(parameter) { if( paramater=='true') { ----your logic--- } else { ----your logic } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to specify a literal initialiser for Stack or Queue? This: List<string> set = new List<string>() { "a","b" }; works fine, but: Stack<string> set = new Stack<string>() { "a","b" }; Queue<string> set = new Queue<string>() { "a","b" }; fails with: ...does not contain a definition for 'Add' which does make me wonder why the compiler was dumb enough to ask for Add. So, how should one initialise at a Queue/Stack constructor? A: Collection initializers are a compiler feature that call the Add method with each item you pass. If there is no Add method, you can't use it. Instead, you can call the Stack or Queue constructor that takes an IEnumerable<T>: var stack = new Stack<int>(new [] { 1, 2, 3 }); A: in C# 6.0, you can do this: var stack = new Stack<string> () {"a","b"}; with below extension method public static class Util { public static void Add<T>(this Stack<T> me, T value) { me.Push(value); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Async ajax requests aren't really async (JQuery and Zend) I've got a stack of ajax request: $("someTable tr").each(function() { // send the data. var scriptURL = "/module/action/data/" + $(this).find(".data").html() + "/"; document.cyonVars.xhrPool[count] = $.ajax({ type: "GET", url: scriptURL, queue: "autocomplete", cancelExisting: true, dataType: 'json', success: function(data){ // do something } } }); count++; }) While these requests are running the user can press a button. This triggers another ajax request. Something like that: var scriptURL = "/module/anotheraction/" + data) + "/"; $.ajax({ type: "GET", url: scriptURL, queue: "autocomplete", cancelExisting: true, dataType: 'json', success: function(data){ // Do another thing } }); The requests from the first action responding asynchrone as I wish. When a user triggers the second request that one waits till the other requests are finished. But the second request should be proceed earlier. I already worked with session_write_close() didn't changed anything. Thanks for helping. A: i'm not so sure, that it should be processed futher. browsers have limits on connections to the same server and if it takes long for a request to reply your app might stop on few or more requests. just think, that async requests are shoot asynchronously (code after ajax request continues to execute), but requests are executed in sequence. A: The problem was Zend_Session::Start(); I had to avoid using Zend_Session while proceeding async requests
{ "language": "en", "url": "https://stackoverflow.com/questions/7571757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Internet Explorer causes an Invalid Authenticity Token error This works in all browsers except IE7 and IE8 ( and probably IE6 ). For some reason it won't respect my Authenticity Token. Any ideas, tips for debugging, workarounds? My standard setup: $(document).ajaxSend(function(event, request, settings) { if ( settings.type != 'GET' ) { settings.data = (settings.data ? settings.data + "&" : "") + "authenticity_token=" + encodeURIComponent( AUTH_TOKEN ); } }); My AJAX call: $(".ajax-referral").click(function(){ $.ajax({ type: "POST", url: $(this).parent("form").attr("action"), data:$(this).parent("form").serialize(), dataType: "script", }); return false; }); A: This error was caused by using IETester in Parallels through Mac OSX. IETester does not hold Authenticity Tokens in its sessions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Blur parent form when child showed How to blur parent form when child form showed to user? I using C#. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7571767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Editing with Coda I use coda as my text editor/subversion client at the studio I work at. We have many clients who hire us for a redesign of existing websites, meaning we have to stick with their existing file extensions. While I don't have to have an auto complete or color-coder for my PHP (and I write the majority of my code in separate files that are just included in the .html) It would be nice to be able to use it in .html files. Is there any way to switch between how Coda interprets the file I am looking at, so that I can use auto-complete and the other features for PHP in an HTML file, or is there a plugin that can accomplish this? A: You should be able to add a "custom syntax mode" in the Coda preferences to edit files with the "html" extension using "PHP-HTML" syntax highlighting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ssrs 2008 r2 pdf blank pages I have report with dynamic-width list which when exported to pdf has every second page blank. I followed instructions given here, squeezed everything as hard as I could - and it worked. However I also have footer inside which I have horizontal line that should continue through whole page width. If I make it long I have every second page blank, if I make it short - it stays that short. Also suppose I need to have textbox at the far right corner of a page, which again would make blank pages in pdf to appear. Is there any solution to this? A: One thing I have found useful to diagnose exactly why SSRS is generating blank pages, is to set the background of the report (or report elements) to a non-white color. Generate the report again, then you can usually see what is being spilt over into another page. You can usually figure out what SSRS is doing, and tweak your report accordingly. A: Set the report property ConsumeContainerWhitespace to True. I believe the default is false, so if you didn't think to ltrim(rtrim()) in your dataset, something I often forget to do, then the whitespace could be causing it. A: For the line, if it is simply to separate the footer from the body of the report, try selecting the entire footer row and set the BorderStyle-Top property to Solid instead of having a line. For the text box, it has to be entirely within the page dimensions or you will get a second mostly blank page. Left margin + right margin + report width <= page width. On one of our printers this still isn't enough so we have to reduce the right margin by another 0.05cm more (so 0.45cm instead of 0.5cm which it should be) to stop getting blank pages every second page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML5 Canvas - lines self-intersection with alpha-channel Please look at the picture (sorry, new users can't insert an image directly into post). Lines are drawn semi-transparent colors (alpha = 0.5). When the red line crosses itself, the double overlay translucent colors does not occur. At the same time, separate the green line superimposed on the red as it should. It can be concluded that the lines are drawn on canvas is not linear, as well as the whole area. I think this is incorrect behavior. Live demo: jsfiddle.net/dom1n1k/xb2AY/ I will not ask how to fix it :) The question is ideological: how do you think about this behavior? * *This is logical and it should be; *This is not logical, but if it happened - we assume that feature; *Canvas work that way for technological reasons - the implementation is simpler. *This is an obvious bug, and the authors of browsers should fix it. P.S. Sorry for my bad english. A: Great question! The spec writer (and I) believe that the answer is: * *This is logical and it should be; Lets explore the reasoning for this. You are not drawing separate lines when you draw the red path. You are drawing an entire path, and an entire path is drawn all at once and stroked all at once, and the color of the path cannot "overlap" itself. This is intentionally defined by the specification. It reads: Since the subpaths are all stroked as one, overlapping parts of the paths in one stroke operation are treated as if their union was what was painted. If you wanted to get an overlay effect you could simply use multiple paths, as you do by adding the green line. So you can easily do it the other way when necessary. You should consider this feature a good thing: If the Canvas spec were to require each subpath of the path to cause an additional overlay then the corners of every path (where each line is joined) would look horrible! (see the red connections here for an example of what each corner would look like) Since having the path overlap on the crosses also means it would overlap on every corner, the specification decides to only use the union'd path when stroking, which keeps normal-looking corners as the expected default (I think most people would expect them to look as they do, not to look as I showed). If the lines were overlaid on the crossings but not every corner then it would not be a consistent rule, which makes it much harder to learn and work around. So the reasoning is clear I hope. The specification has to give us 3 things, usually in this order: The most-common expected output (corners look as they do), consistency (if we overlaid on line crosses we'd also be doing it on corners, so we shouldn't do it), and ease of understanding. A good specification is always consistent. If something is consistent then it is more learnable, which makes it easier to understand once you know why something is done that way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: String manuplation in C# Is there any method that I can use that returns a fixed length array after spliting a string with some delimiter and fill the rest with a default string. Eg. string fullName = "Jhon Doe"; string[] names = fullName.SpecialSplit(some parameters); //This should always return string array of length 3 with the second elememnt set to empty if there is no middle name. A: Next time specify the language you're asking about. We're no guessers. In Java: fullName.split(" "); And anyway, no method will "return string array of length 3 with the second elememnt set to empty if there is no middle name". For the method, there are just two elements. You have to write that method yourself wrapping the standard split() method. A: You should read over Jon Skeet's Writing the perfect question. It will be beneficial to you in the future when posting questions of StackOverflow. There is no method in C# to do what you are asking, but you can easily write an extension method to do what I think you are asking. here is a quick example: public static class AbreviatorExtention { public static string[] GetInitials(this String str, char splitChar) { string[] initialArray = new string[3]; var nameArray = str.Split(new char[] { splitChar }, StringSplitOptions.RemoveEmptyEntries); if (nameArray.Length == 2) { var charArrayFirstName = nameArray[0].ToCharArray(); var charArrayLastName = nameArray[1].ToCharArray(); initialArray[0] = charArrayFirstName[0].ToString().ToUpper(); initialArray[1] = string.Empty; initialArray[2] = charArrayLastName[0].ToString().ToUpper(); } else { for (int i = 0; i < nameArray.Length; i++) { initialArray[i] = (nameArray[i].ToCharArray())[1] .ToString().ToUpper(); } } return initialArray; } } class Program { static void Main(string[] args) { string FullName = "john doe"; //Extension method in use string[] names = FullName.GetInitials(' '); foreach (var item in names) { Console.WriteLine(item); } Console.ReadLine(); } } Output: J D A: I would set it up to split the string separate from the fixed array. If you still want a fixed array, then you set up the array to a size of three an populate. This is not the best method, however, as it has no meaning. Better, set up a person or user class and then populate, via rules, from the split string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Sortable doesn't work properly with draggable and droppable See demo http://jsfiddle.net/nivea75ml/5NhFA/1/. Here, the green blocks at bottom which can be dragged and dropped into the dark gary area. Also I want the 3 blocks are sortable, for example, if the Block2 are dragged into dark gray area first and the Block3 should move to the Block2's position. Currently the sortable function is working without Draggable & Droppable, view it at http://jsfiddle.net/nivea75ml/sNnAe/. However it doesn't work with Draggable & Droppable, see http://jsfiddle.net/nivea75ml/5NhFA/1/. Can anyone help me out? Thanks in advance! A: Sounds like you just want to use Sortable with a connected list: http://jqueryui.com/demos/sortable/#connect-lists I modified your first jsfiddle: HTML: <div class="demo"> <div id="droppable" class="drp"> </div> <div id="draggableElements" class="drp"> <div class="draggable"> <p>Sen1</p> </div> <div class="draggable"> <p>Sen2</p> </div> <div class="draggable"> <p>Sen3</p> </div> </div> </div> Javascript: $(function() { $("#draggableElements, #droppable").sortable({ connectWith: ".drp", placeholder: "ui-draggable" }); }); This makes the above grey area sortable as well, which may or may not suit your needs completely. If you're wanting to drop a sortable item into a droppable, and be able to bring it back into a sortable, take a look at this: jQuery Sortable and Droppable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Routing errors when adding an Admin namespace I added an Admin namespace to my app so when logging in to the administration area, it would have to be like this: admin/websites and admin/page/8 So this is what I have in my routes.rb namespace :admin do |admin| match '/' => 'dashboard#index' resources :websites resources :pages resources :sessions get 'login' => 'sessions#new', :as => 'login' get 'logout' => 'sessions#destroy', :as => 'logout' end I have admin_controller.rb in app/controllers directory. class Admin::BaseController < ApplicationController protect_from_forgery include UrlHelper ... I created an admin directory inside app/controllers. So I have this inside app/controllers/admin/websites_controller.rb class Admin::WebsitesController < ApplicationController Some other answers suggested class Admin::WebsitesController < Admin::BaseController, but that never worked for me. If I'm wrong please let me know. So then in my layout file (app/views/layouts/application.html.erb) I have links like this one edit_admin_website_path(@website) that give me routing errors Routing Error No route matches {:action=>"edit", :controller=>"admin/websites"} Whyyyy?! :( A: Add a file named application_controller.rb in the admin directory with this content: class Admin::ApplicationController < ApplicationController end Then, for each controller on this directory, extend the Admin::ApplicationController class. Did you try this? admin_edit_website_path(@website) A: Rails namespaces rely on folder structure for loading the right classes. You should structure it like this: app/controllers admin_controller.rb # class AdminController < ApplicationController app/controllers/admin websites_controller.rb # class Admin::WebsitesController < AdminController The AdminController should be defined outside the admin folder. If put it in there you'd have to refer to it as Admin::AdminController which is a little odd. In fact, you could call it AdminNamespaceController to be clear. You can also use rails generate which will set things up for you in the expected places, although I don't think it creates the namespace base class for you to inherit from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to achieve high-performance REST API on Azure with .NET? We have a .NET Web Role hosted on Windows Azure that only serves a REST API with only a hand few web methods. API is used rather aggressively by other cloud hosted apps (not browsers). Each method is stateless which enable direct scaling out, and typically interacts with the Blob or Table Storage. Then contrary to most classical API, the amount of data uploaded to the API is typically much larger than the data downloaded from the API. Then, the size the average message is typically quite big as well (i.e. above 100kB). So far, we are using WCF on top of ASP.NET Forms with POX messages (Plain Old Xml). The front-end performance are not very good, culprits are: * *XML is verbose ==> bandwidth limitation. *ASP.NET + WCF + WcfRestContrib slow to parse/serialize messages ==> CPU limitation. I am wondering what is the best strategy to achieve the highest possible front-end performance to reduce the number of VMs needed to support the workload. Possible strategies that I am considering: * *Discard XML in favor of ProtoBuf. *Add upstream GZip compression (classical HTTP compression only applies downstream). *Discard WCF entirely in favor of raw HttpHandlers. Does anyone has benchmarked the various alternatives to achieve the most of each Azure VM for such usage? Ps: Implicitly referring the Lokad Forecasting API but tried to phrase the question in a more general way. A: Is your XML being serialized via reflection (ie. using attributes and so forth)? If so, then protobuf-net stands to be much, much faster. In fact, though, even if your XML serialization is customized using explicit getter and setter Func<>s, you can still see some significant gain with protobuf-net. In our case, depending on the size and content of the objects being serialized, we saw 5-15% speed increases in serialization times. Using protobuf-net will also provide a bump to available bandwidth, though that will depend on your content to a large extent. Our system sounds pretty different from yours, but FWIW we find that WCF itself has an almost imperceptibly low overhead compared to the rest of the flow. A profiler like dotTrace might help identify just where you can save once you've switched to protobufs. A: Is the size of the messages your service is receiving so big because there is a large amount of data in the message or because they contain files? If it is the first case, then ProtoBuf does indeed seem like a very good option. If the message size is big because it embeds files, then one strategy I have been using with success is creating two different architectures for your service methods: one for methods that upload and download files and another one for methods that only send and receive messages. The file related methods will simply transmit the files inside the body of the HTTP requests, in binary form without any transformation or encoding. The rest of the parameters will be send using the request URL. For file uploads, in WCF REST services, in the service method you will have to declare the parameter representing the file of being of type Stream. For example: [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "uploadProjectDocument?projectId={projectId}")] void UploadProjectDocument(Guid projectId, Stream document); When encountering Stream parameters, WCF will simply take their content directly from the body of the request without doing any processing on it. You can only have one parameter of type Stream on a service method (which makes sense because each HTTP request has only one body). The downside to the above approach is that besides the parameter representing the file, all the other ones need to be of basic types (like strings, number, GUIDs). You cannot pass any complex object. If you need to do that you will have to create a separate method for it, so you might end up having two methods (which will translate in two calls at runtime) where at the moment you have only one. However, uploading files directly in the body of the request should be much more efficient than serializing them, so even with the extra call things should be improved. For downloading files from the service you will need to declare the WCF methods as returning Stream and simply write the file in returned object. As with the Stream paramters, WCF will output the content of the Stream directly into the body of the result without any transformations on it. A: This article http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 covers performance issues with Azure. Azure roles by default only run in a single thread, which is very inefficient on the servers. There are some very nice design patterns out there that shows you how to implement multithreaded Azure roles, I personally follow this one http://www.31a2ba2a-b718-11dc-8314-0800200c9a66.com/2010/12/running-multiple-threads-on-windows.html . With this your roles can serialize objects in parallel. I use JSON as an interchange format instead of XML, it has a much smaller bytesize and is well supported with .NET 4. I currently use DataContractJsonSerializer but you could also look into JavaScriptSerializer or JSON.NET, if it is serialization performance you are after I would suggest you compare these. WCF services are single threaded by default ( source: http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.SERVICEMODEL.SERVICEBEHAVIORATTRIBUTE.CONCURRENCYMODE);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true ) . Here is a code sample that will make your RESTfull API multi-threaded: ExampleService.svc.cs [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall, IncludeExceptionDetailInFaults = false, MaxItemsInObjectGraph = Int32.MaxValue)] public class ExampleService : IExample web.config <system.serviceModel> <protocolMapping> <add scheme="http" binding="webHttpBinding" bindingConfiguration="" /> </protocolMapping> <behaviors> <endpointBehaviors> <behavior name=""> <webHttp defaultOutgoingResponseFormat="Json" /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> ExampleService.svc <%@ ServiceHost Language="C#" Debug="true" Service="WebPages.Interfaces.ExampleService" CodeBehind="ExampleService.svc.cs" %> Also, ASP.NET by default only allow for two concurrent HTTP connections (source See http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 ) . These settings will allow for up to 48 concurrent HTTP connections: web.config <system.net> <connectionManagement> <!-- See http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 --> <add address="*" maxconnection="48" /> </connectionManagement> </system.net> If your HTTP POST body messages are usually smaller than 1460 bytes you should turn of nagling to improve performance ( source http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 ) . Here is some settings that does this: web.config <system.net> <settings> <!-- See http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 --> <servicePointManager expect100Continue="false" /> </settings> </system.net> Define your JSON APIs something like this: using System.ServiceModel; using System.ServiceModel.Web; using Interchange; namespace WebPages.Interfaces { [ServiceContract] public interface IExample { [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string GetUpdates(RequestUpdates name); [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] string PostMessage(PostMessage message); } } You can serialize to JSON in .NET 4 like this: string SerializeData(object data) { var serializer = new DataContractJsonSerializer(data.GetType()); var memoryStream = new MemoryStream(); serializer.WriteObject(memoryStream, data); return Encoding.Default.GetString(memoryStream.ToArray()); } A typical interchange entity you can define as normal: using System.Collections.Generic; using System.Runtime.Serialization; namespace Interchange { [DataContract] public class PostMessage { [DataMember] public string Text { get; set; } [DataMember] public List<string> Tags { get; set; } [DataMember] public string AspNetSessionId { get; set; } } } You could write your own HTTPModule for upstream GZip compression, but I would try the stuff above first. Finally, make sure that your table storage is at the same location as the services that consume them. A: I've had a very pleasant experience with ServiceStack: http://www.servicestack.net. It's basically your last option; a fairly thin layer on top of HttpHandlers with fast XML and JSON serialization, that exposes a REST API. The JSV serialization it also offers is about half the speed of Protobuf.NET I believe, and support for ProtoBuf is planned. I don't know for sure if it runs on Azure, but I can't think of a reason why not as it simply integrates into any ASP.NET application. A: In your POCs, I think you can remove Azure from the equation as you test through some of the scenarios. If this is truly bandwidth, compression is certainly an option, but it can be problematic if this web service will be opened up to the "public" rather than simply used by applications under your control. This is especially true in a heterogenous environment. A less verbose format is an option, as long as you have a good means of RESTfully communicating failures due to bad formatting. XML makes this very easy. Lacking experience in ProtoBuf, it does appear to have some safety in this area, so it could be a very good option if bandwidth is your problem and may solve the speed of parsing issue. I would POC it outside of Azure first and then put it in. I would only run the raw HttpHandler direction if you have evidence WCF overhead is an issue. Azure is hard enough to debug with so much being in config that I am not convinced adding the additional issue of raw HttpHandlers is the proper direction to go. A: Here are Benchmarks for different .NET serialization options Out of all JSON Serializers I've benchmarked my ServiceStack's Json serializer performs the best around 3x faster than JSON.NET. Here are a couple of external benchmarks showing this: * *http://daniel.wertheim.se/2011/02/07/json-net-vs-servicestack/ *http://theburningmonk.com/2011/08/performance-test-json-serializers/ ServiceStack (an Open source alternate to WCF) comes pre-configured with .NET's fastest JSV and JSON Text Serializers OOB. I see someone include lengthy configuration on how you can bend WCF to configure it to use the slower JSON Serializer shipped with .NET. In Service Stack every web service is automatically available via JSON, XML, SOAP (inc. JSV, CSV, HTML) automatically without any config required, so you get to choose the most appropriate endpoint without any additional effort. The same amount of code and configuration for the WCF example in Service Stack is just: public class PostMessage { public string Text { get; set; } public List<string> Tags { get; set; } public string AspNetSessionId { get; set; } } public class GetUpdatesService : IService<GetUpdates> { public object Execute(GetUpdates request){ ... } } public class PostMessageService : IService<PostMessage> { public object Execute(PostMessage request){ ... } } Note: decorating your DTOs with [DataContract] is optional. The ServiceStack Hello World example shows all the links different formats, metadata pages XSD Schemas and SOAP WSDLs automatically available after you create a web service. A: I found the initialization of blob storage (CreateCloudBlobClient(), GetContainerReference() etc) to be quite slow. It's a good idea to take this into consideration when designing Azure services. I have separate services for anything that requires blob access as it dragged down the time for the pure db requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Why does FETCH FIRST N ROWS not work in combination with WITH statement? I have the following SQL statement which does not run on my DB2 database: WITH a AS ( SELECT * FROM sysibm.systables ) SELECT a.* FROM a FETCH FIRST 10 ROWS Without the FETCH statement it works. The error message I get is: Illegal use of keyword OPTIMIZE, token ERR_STMT WNG_STMT GET SQL SAVEPOINT HOLD FREE ASSOCIATE was expected. Any suggestions? A: You're missing the ONLY keyword at the end of the FETCH clause. WITH a AS ( SELECT * FROM sysibm.systables ) SELECT a.* FROM a FETCH FIRST 10 ROWS ONLY; A: Missing the Only Keyword at the end. Example here. A: While the example you give is likely simplified, how about putting the fetch first clause in the first select portion? I can never read the documentation clearly, but as the with-statement creates a common-table-expression, you might not be able to use the fetch-first-clause on selecting from it. According to this documentation, having the fetch-first-clause in the select of the with-statement is valid syntax. i.e. WITH a AS ( SELECT * FROM sysibm.systables FETCH FIRST 10 ROWS ONLY ) SELECT a.* FROM a;
{ "language": "en", "url": "https://stackoverflow.com/questions/7571786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regular analysis over irregular time series I have an irregular time series (xts in R) that I want to apply some time-windowing to. For example, given a time series like the following, I want to compute things like how many observations there are in each discrete 3-hour window, starting from 2009-09-22 00:00:00: library(lubridate) s <- xts(c("OK", "Fail", "Service", "OK", "Service", "OK"), ymd_hms(c("2009-09-22 07:43:30", "2009-10-01 03:50:30", "2009-10-01 08:45:00", "2009-10-01 09:48:15", "2009-11-11 10:30:30", "2009-11-11 11:12:45"))) I apparently can't use period.apply() or split() to do it, because those will omit periods with no observations, and I can't give it a starting time. My desired output for the simple counting problem (though, of course, my real tasks are more complicated with each segment!) would be something like this if I aggregated 3 days at a time: 2009-09-22 1 2009-09-25 0 2009-09-28 0 2009-10-01 3 2009-10-04 0 2009-10-07 0 2009-10-10 0 2009-10-13 0 2009-10-16 0 2009-10-19 0 2009-10-22 0 2009-10-25 0 2009-10-28 0 2009-10-31 0 2009-11-03 0 2009-11-06 0 2009-11-09 2 Thanks for any guidance. A: Use align.time to put the index of s into the periods you're interested in. Then use period.apply to find the length of each 3-hour window. Then merge it with an empty xts object that has all the index values you want. # align index into 3-hour blocks a <- align.time(s, n=60*60*3) # find the number of obs in each block count <- period.apply(a, endpoints(a, "hours", 3), length) # create an empty xts object with the desired index e <- xts(,seq(start(a),end(a),by="3 hours")) # merge the counts with the empty object and fill with zeros out <- merge(e,count,fill=0)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Critical tunnel failure problem in Blackberry I am facing critical tunnel failure problem in Blackberry while testing in Blackberry device. I am appending interface=wifi while i am making request in device,but it shows critical tunnel failure problem.While testing in simulator it not showing any error. http://maps.google.com/maps/api/geocode/json?address=marine%20parade&sensor=false;interface=wifi A: You may be connecting over MDS or even BIS in which case ;interface=wifi is not required. This is further explained in this video: http://supportforums.blackberry.com/t5/Java-Development/Networking-Transports-II/ta-p/446742 You may benefit from using the ConnectionFactory class in OS5 to avoid writing this sort of connection logic yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Visual C++ with a different C++ compiler? I like the Visual Studio IDE. I'm used to it and find it is the best IDE I've ever tried. We also find increasing use of C#/.NET here. However, after the underwhelming announcement regarding C++11 features in VS11 I'm looking into replacing the compiler. It seems that the Intel compiler fully integrates with VS but that doesn't mean it will compile our Windows code. I don't know how I'd fare with a try of g++ or clang Can VS actually be productively used with a different C++ compiler to compile Windows code, that is legacy code using all kinds of Win32 / MFC / COM stuff? A: Depends on how much use you made of the Microsoft-proprietary extensions. Things like #pragma once tend to be supported by all the major compilers, but the weirder COM things (e.g., #import and anything C++/CLI) probably won't be. No idea if MFC will build under the new compiler, but you'll probably have to link it statically or ship your own DLL; G++ definitely uses a different mangling scheme than MSVC. I'm not sure how easy it is to replace cl.exe and keep your vcproj files intact (though some compilers actually do it), but there are always Makefile projects. A: I have never actually worked with the Intel C++ compiler, but I see no reason why it wouldn't compile the code that VC++ does. Here is official Intel documentation. A: I use Visual Studio 2008 with a Makefile project to cross-compile; no reason you couldn't do the same with a different Windows compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Calling Python script that creates a subprocess over ssh hangs I have a bunch of scripts that are used to start similar processes across a number of servers. I'd like to condense them down to one Python script called 'START', but something weird is happening when it's run over ssh. $ ./START APP_A works as expected: APP_A is launched and begins doing its thing. Control is returned to the console immediately (before APP_A terminates). $ ssh localhost /path_to/START APP_A sort of works: APP_A is launched and begins doing its thing, but ssh doesn't print any output to the screen or return control to the console until after APP_A terminates. I assume it's a problem with signals or file handles, but I'm at a loss. Here's the Popen call that seems to be causing the trouble: sub = subprocess.Popen(shlex.split(cmd), stdout=open(file_out, 'a+'), stderr=subprocess.STDOUT, close_fds=True) print 'New PID:', sub.pid I'm using Python 2.4.3 on RHEL. EDIT: Wrapping the Python script seems to work: DIR="$( cd "$( dirname "$0" )" && pwd )" pushd $DIR >> /dev/null ./START $1 & popd >> /dev/null A: Don't use shlex to call in conjunction with subprocess. It doesn't do what you expect. Instead, give subprocess a Python list of the command, like subprocess.Popen(['/some/program', 'arg1', 'arg2', 'arg3']) A: When you do: ssh some_host remote_command remote_cmd_param then it is normal that ssh does not return control before remote_command is done. If you want otherwise you need to sent it to background aby adding & at the end. ssh redirects stdout of remote_command to its (local) stdout. If you don't see any output this may be because remote_command does not set any to stdout but tries to send it to the console for example. This is why you cannot do: ssh remote_host mc # or any other command using terminal A: You should put this in START_APP_A nohup /path/to/APP_A >/path/to/log 2>&1 </dev/null & Then it will work, and all the output from APP_A will go into a log file which you can inspect when you need to. Note that if you need to inspect this output while APP_A runs, then you need to change APP_A so that it flushes stdout after printing or else change stdout to be unbuffered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Window.Show() display new window and then disappear behind main window I am developing a Prism application where I need to publish view-models in a new window. To achieve that I created a service dedicated to the publication of these view-models. I call it like this: windowService.Publish(myViewModel); And the body of the Publish method is like this: public void Publish(FloatingViewModel viewModel) { var floatingWindow = ServiceLocator.Current.GetInstance<FloatingWindow>(); floatingWindow.DataContext = viewModel; floatingWindow.Show(); } After the Show() method execution, the new window quickly shows up above my main window and then disappears behind my main window like if it took back the focus. Does anybody knows where this behavior could come from? A: I finally found the problem and it was actually way deeper than I thought. This answer will not be relevant of the described problem as the root cause was totally different. The code that was publishing the view-model in a window was actually nested in a WPF command and this command was attached to the MouseDoubleClick event through a InvokeCommandAction. I discovered that even when you bind an event to a command, the event is not marked as handled and therefore will propagate until it is handled. That was causing my main window to take back the focus.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you programmatically apply a css class to an asp.net control? I'm wondering how I can apply a CSS class to an ASP.NET Control (TextBox in this case) through the backend in C#. For example: <asp:TextBox ID="firstName" CssClass="input left" runat="server" Text="First Name" /> I'd like to add another class to the element "selected" if a value is true that I test for on the backend. <asp:TextBox ID="firstName" CssClass="input left selected" runat="server" Text="First Name" /> What is the best way to do this? Thanks! A: You can just do this: firstName.CssClass = "input left selected". If you want to append to any existing class names, do this: firstName.CssClass += " selected"; A: It's just a string property of WebControl: firstName.CssClass += " selected"; A: if(yourCondition) { var css = "myClass"; if(String.IsNullOrWhiteSpace(element.CssClass)) element.CssClass = css; else element.CssClass += " " + css; } A: I think you could do that in the normal way something like below: if (value.Equals(true)) { firstName.CSSClass = "input left selected"; } Hope this helps!! A: Simply create an entry in the ViewDataDictionary for the class. The backend would look something like ViewData["selectedclass"] = <conditionalstatement> ? "selected" : ""; And the view would be <asp:TextBox ID="firstName" CssClass="input left <%= ViewData["selectedclass"]%>" runat="server" Text="First Name" /> A: You can implement adding cssClass like firstName.CssClass = "input left selected"; Or make onClick event for textbox <asp:TextBox ID="firstName" CssClass="input left" runat="server" Text="First Name" OnClick="firstName_Click" /> Then in code-behind: void firstName_Click(Object sender, EventArgs e) { MyTextBox.CssClass = "input left selected"; } A: you can use attribute of ui controls firstName.Attributes["css"]="Your Class Name";
{ "language": "en", "url": "https://stackoverflow.com/questions/7571801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Recovering from a separate (now corrupt) SVN repository? So for some reason (miscommunication for what the actual subversion URL is and only 1 person working on the code previously) we have two different subversion repositories with what we want to be the same code. Basically the timeline went like this: * *Created X repository *Put code in *Created Y repository *Put code from X in *Made modifications to Y *SVN repo Y got corrupted (so he just stopped committing.. not bothering to say something before the backups replaced themselves) *I made changes to X And, so now I need to somehow merge the changes from Y into X. What would be the best method for doing this? A: * *create a branch from x at the revision where y was created *put the code from y in that branch *commit *merge the 'branch-y' to your trunk in x
{ "language": "en", "url": "https://stackoverflow.com/questions/7571805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails and AWS enforcing SSH/HTTPS I've been struggling with this for a few days now but I think it has something to do with Amazon's AWS. I want to enforce SSH/HTTPS, so that if a user inadvertanly goes to HTTP:// myaddress.com they will be redirected to HTTPS:// myaddress.com. I have added this to my config.groovy file: environments { production { // force all traffic over HTTPS in production grails.plugins.springsecurity.secureChannel.definition = [ '/**': 'REQUIRES_SECURE_CHANNEL' ] } The problem is that when I upload to amazons AWS, my application will not run properly. I get no errors in my catalina.out file. The only indication is that the status will not turn from red to green and there is a warning that the system health check did not pass. When I navigate to either HTTP or HTTPS address the page is blank white with no errors. has anyone come across this or know what the problem is? It seems like the app is fine (due to no errors) but it is not being properly redirected. I have Spring Security installed, and HTTPS is already set up. also, the web address uses a DNS, so the address for the HTTPS is not the same as the controllers. thanks jason A: Just a thought... Did you set up https port in the AWS beanstalk application configuration? http://docs.amazonwebservices.com/elasticbeanstalk/latest/dg/index.html?using-features.managing.elb.html A: Are you terminating SSL at the EC2 LB? If so, the EC2 will set the x-forwarded-proto header and forward the request over HTTP. Your production config needs to handle that differently. Checkout http://grails-plugins.github.com/grails-spring-security-core/docs/manual/guide/17%20Channel%20Security.html where they talk about Header Checking. If the LB is terminating the SSL, you can't check the HTTP protocol on the webserver. HTH.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use i18n with a Grails/Groovy enum in a g:select? i am trying to get i18n localisation working on an Grails/Groovy enum, public enum Notification { GENERIC(0), CONFIRM_RESERVATION(100), CONFIRM_ORDER(200), CONFIRM_PAYMENT(300), final int id; private Notification(int id) { this.id = id } String toString() { id.toString() } String getKey() { name() } } Any hints on how i could achieve that? I tried to put the full classname etc in a localisation but this does noet seem to work <g:select from="${Notification.values()}" name="notification" valueMessagePrefix="full.path.to.package.Notification"/> A: One method is shown in this blog post by Rob Fletcher (from 2009) Make sure your enum class implements org.springframework.context.MessageSourceResolvable Then implement the methods it defines A: Sorry for the delay but I think this could help you. I was having the exact same problem with enums and i18n. This is the solution I found: Following your enum defined before, in your message.properties files put an entry for each value of the enum for example: enum.value.GENERIC enum.value.CONFIRM_RESERVATION enum.value.CONFIRM_ORDER enum.value.CONFIRM_PAYMENT Then when you want to show the values of the enum in a select element then do as follows: <g:select from="${path.to.package.Notification.values()}" keys="${path.to.package.Notification?.values()}" name="notification" valueMessagePrefix="enum.value"/> According to the Grails documentation regarding the select tag, the value you put in the attribute valueMessagePrefix is used followed by a dot(.) and then the value of the element of the enum. So that way it would go to the message.properties file and search for the lines you put before. Now, the other thing you would need to do is for example in a list of data, show the value of the enum for each record. In that case you need to do as follows: ${message(code:'enum.value.'+fieldValue(bean: someDomainClass, field: "notification"))} This is if you have a domain class with one attribute of type Notification. Hope this helped. Bye! A: You need to implement MessageSourceResolvable to provide your codes: enum Notification implements org.springframework.context.MessageSourceResolvable { GENERIC(0), CONFIRM_RESERVATION(100), CONFIRM_ORDER(200), CONFIRM_PAYMENT(300), final int id; private Notification(int id) { this.id = id } String toString() { id.toString() } String getKey() { name() } public Object[] getArguments() { [] as Object[] } //This methods do the trick public String[] getCodes() { [ "notification." + name() ] } public String getDefaultMessage() { name() } } And define your messages in i18n: notification.GENERIC=Generic notification.CONFIRM_RESERVATION=Confirm reservation notification.CONFIRM_ORDER=Confirm order notification.CONFIRM_PAYMENT=Confirm payment The select tag should look like this: <g:select name="type" from='${Notification.values()}' optionKey="id"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to browse when click other button I am trying to simulate the browse button, so when you click other button let it browse the file input? A: Really easy just make it <a href="#" onclick="form.browse.click();return false;">Browse</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GitSharp cannot find cloned bare repository I have created a bare clone of a Git repository and placed it on a shared network drive. I am trying to open this bare repository from GitSharp. I used the following command to clone the repository: $ git clone --bare my_project my_project.git With GitSharp I can open the repository on the shared network drive without a problem. However if I attempt to connect to the cloned bare repository (on the same server), GitSharp cannot find the repository. The cloned repository is shared just as the original is. var git_url = Repository.FindRepository(p); // where 'p' is the path to the shared bare clone. The above returns the git url if I connect to the orginal repository but it returns NULL if I attempt to connect to the clone. Any ideas? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7571813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: adding multiple components to Jframe.getcontentpane() I have a class that extends JPanel and draws a triangle. I called it from other class to create three triangles but when third triangle is drawn the previous two disappeared. How can I add multiple triangles that are shown together. Code is as follows: Triangle.Java: public class Triangle extends JPanel{ Point p1, p2, p3; public Triangle(Point _p1, Point _p2, Point _p3) { this.p1=_p1; this.p2=_p2; this.p3=_p3; } public void paint(Graphics g) { super.paint(g); int[] xs = {p1.x,p2.x,p3.x}; int[] ys = {p1.y,p2.y,p3.y}; Polygon triangle = new Polygon(xs, ys, xs.length); g.fillPolygon(triangle); } } SwingApplication.java: public class SwingApplication { public static void main(String[] args) { Triangle triangle1=new Triangle(new Point(120,10), new Point(170,110),new Point(220,10)); Triangle triangle2=new Triangle(new Point(120,210), new Point(170,110), new Point(220,210)); Triangle triangle3=new Triangle(new Point(10,400), new Point(170,210), new Point(320,400)); JFrame frame = new JFrame("Swing Application - Question 2"); //frame.setLayout(new FlowLayout()); frame.getContentPane().add(triangle1); frame.getContentPane().add(triangle2); frame.getContentPane().add(triangle3); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 450); //frame.pack(); frame.setVisible(true); } } A: If you want to draw them all on in one spot, then do that -- draw them all in the same JPanel's paintComponent method (not a paint method). One way to do that is to separate the Triangle class from the JPanel class, give your Triangle class a public void draw(Graphics g) method, give your JPanel 3 Triangle instances (or an ArrayList of Triangle), and then have the JPanel's paintComponent method call draw(Graphics g) on all the Triangle objects it holds. If on the other hand you want to have each Triangle displayed in its own JPanel and have the panels shown side by side or one below the other (your question is not clear on this issue), then you'll need to study the layout manager tutorials and use this knowledge to set the layout of the contentPane to one that will display more than one JPanel easily. Currently you're adding all of the Triangle/JPanels to the contentPane, and you'll find in the tutorials that a top-level container's (i.e., a JFrame's) contentPane uses BorderLayout as its default layout manager. If you add a component to a BorderLayout-using container without specifying where, it will land in the BorderLayout.CENTER position and will cover up anything that had been added there previously. A: I had the same problem and tried to call the frame.revalidate() and frame.repaint() method in my application after every adding to contentPane, it works fine. I don't know, how regular it is, but works great for me. frame.getContentPane().add(triangle1); frame.revalidate(); frame.repaint(); frame.getContentPane().add(triangle2); frame.revalidate(); frame.repaint(); frame.getContentPane().add(triangle3); frame.revalidate(); frame.repaint();
{ "language": "en", "url": "https://stackoverflow.com/questions/7571818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Oracle, Inserting correlative numbers based on other fields Sorry for my english: My query select date from mytable returns something like this: DATE 27/09/2011 27/09/2011 27/09/2011 27/09/2011 28/09/2011 28/09/2011 29/09/2011 29/09/2011 29/09/2011 I also need that my query returns a correlative based on each diferent date. something like... DATE | CORRELATIVE | 27/09/2011 | 1 27/09/2011 | 2 27/09/2011 | 3 27/09/2011 | 4 28/09/2011 | 1 28/09/2011 | 2 29/09/2011 | 1 29/09/2011 | 2 29/09/2011 | 3 I need help to get it, something like select date, any_way_to_get_it from mytable thk! A: Here's the function you should use. SELECT date, ROW_NUMBER() OVER (PARTITION BY date ORDER BY date) AS any_way_to_get_it FROM mytable;
{ "language": "en", "url": "https://stackoverflow.com/questions/7571820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determine size of object sent across the network I am trying to figure out the size of an object that is sent to my application via TCP. Unfortunately there is a third party tool that is receiving data and then handing my application an object through a callback. Is there a tool provided with solaris that would help me determine the bytes of these messages? Alternatively I could do it on a test windows version of the app. A: You could try using a network analyzer, such as Wireshark, to look at the TCP traffic. Apologies if I have misunderstood your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any good alternatives for MessageBox in WinForms? A WinForms program will inevitably send notification to user. There are two types of notifications: * *Important: user needs to take action on it *Non-Important: kind of like "there is something going on, and you might want to pay attention". It's pretty common that MessageBox is used for both of the two types. But recently I found MessageBox is kind of annoying: it steals user's focus and user has to click to dismiss it. I want to know what's the alternatives for MessageBox and their pros/cons? To start, here is some idea: Statusbar: not easy to display lengthy notification taskbar notification: does people think it's evil since most internet ads popup use that approach? floating statusbar: Chrome/IE9/Evernote use similar floating statusbar, which is hidden when there is no link address or no message. * *Chrome UI: Infobar and Status Bubble *IE9: Notification bar A: We implemented a mechanism similar to taskbar notification, but placed in some coordinates inside a WinForms control. This has some advantages: * *You have some context about where (location) the notification is shown and why. *It is non modal, so it not blocks the GUI. *It's easy to implement using a owned form without border. *You can place it wherever you want. *You can show a link label with a short explanation and show help, other dialos, or link some actions if the user needs further explanation. The user experience is improved. But I recommend using notifications only for informative messages. You must take into account some tips about the messagebox: * *It's the standard way to show information to the user. *It should be user to notify an error message or a warning. The messagebox ensures that the user, at least, clicked ok. So the user is aware that something happens. Yes, maybe he didn't read the message, but at lease he saw an error or warning. *It is possible that the user ignores other reporting mechanisms. Hope it helps. A: I have been working on a C# WinForms solution using the WebBrowser control on a form. At this time it has three modes: Prompt; Countdown Prompt; Countdown Timer and Combo(box) prompt. Using the webbrowser control allows HTML to be used which gives you free selection of Fonts; Colors and sizes. I'd share what I have if I only knew how to share a solution instead of a code snippet. What I've got works and has two parts, the designer and the prompt itself. If an admin will contact me I can provide a download link and they can review to see what they think.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: EOFError when open https I've been trying to use facebook graph api, though ruby raise EOFError when open api url (https://graph.facebook.com/.....) I'm using Ruby 1.8.6 and Rails 2.2.2. The code is as follows: require 'uri' require 'https' access_token = open("https://graph.facebook.com/oauth/access_token?client_id=app_id&client_secret=app_secret&grant_type=client_credentials"){|f| f.read } Got following error: end of file reached /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:133:in `sysread' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:133:in `rbuf_fill' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/timeout.rb:62:in `timeout' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/timeout.rb:93:in `timeout' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:132:in `rbuf_fill' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:116:in `readuntil' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/protocol.rb:126:in `readline' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/http.rb:2022:in `read_status_line' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/http.rb:2011:in `read_new' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/http.rb:1050:in `request' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:248:in `open_http' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/net/http.rb:543:in `start' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:242:in `open_http' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:616:in `buffer_open' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:164:in `open_loop' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:162:in `catch' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:162:in `open_loop' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:132:in `open_uri' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:518:in `open' /Users/user/.rvm/rubies/ruby-1.8.6-p420/lib/ruby/1.8/open-uri.rb:30:in `open' app/models/news_release.rb:75:in `post_to_facebook_wall' I thoroughly googled and searched about this error and tried such as httpparty, mechanism, fb_graph, and koala. However those raise same efoerror. It seems that there is a bug with ruby-1.8.6 or open-uri, but I don't want to upgrade ruby. Any ideas? Thanks in advance. A: It looks like ssl is failing because you didn't fill out the parameters. Try it like this: require 'open-uri' app_id = 'fill_me_out' app_secret = 'fill_me_out_too' url = "https://graph.facebook.com/oauth/access_token?client_id=#{app_id}&client_secret=#{app_secret}&grant_type=client_credentials" access_token = open(url).read
{ "language": "en", "url": "https://stackoverflow.com/questions/7571829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to use MVCScaffolding to create Views with problems NOTE: I have looked at this link and disabled CustomTools and still receive this error: MvcTextTemplateHost not found I am trying to create custom Views in one command for Create, Update, Details, Filter, and List operations. I am able to add them one at a time by right clicking and choosing New View, but when I type Scaffold AddView SampleModel I get the following error message: The type or namespace name 'MvcTextTemplateHost' could not be found (are you missing a using directive or an assembly reference?). The template file is AddView.cs.t4. I tried renaming it to .tt but I cannot get the Powershell to look for a .tt file. Any ideas? A: MvcScaffolding uses its own custom template host and does not use the MvcTextTemplateHost. I would take a look at the T4 templates that are included with the MvcScaffolding NuGet package. The beginning of one of these templates is shown below. <#@ Template Language="C#" HostSpecific="True" Inherits="DynamicTransform" #> <#@ Output extension="aspx" #> <# var viewDataType = (EnvDTE.CodeType) Model.ViewDataType; #>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IE6 and 7 issue with innerHTML IE6 and 7 issue with innerHTML I have used ajax in the application i have develop, but there are issues with IE6 and IE7, they doesn't support innerHTML. What must be used to fixed this issue and to be a cross browser compatible? the sample code looks like this. function showFAQ(src, target){ xhr.onreadystatechange=function(){ if(xhr.readyState == 4 && xhr.status == 200){ document.getElementById('resultDiv').innerHTML=xhr.responseText; } } str = "?action=get&request="+src; xhr.open("GET", "./requests/data.php"+encodeURI(str), true); xhr.send(); } In FireFox, IE8 and other major browsers works fine. Just the problem is with IE6 and 7. Any help/advice will be appreciated. Thanks A: IE cannot update readonly elements using innerHTML... consider this too.. :) A: Try var xmlHttp; function getXmlHttpObject() { var xmlHttp = null; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer 6+ try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } var xhr = getXmlHttpObject(); Update Try adding xhr.send(null); after str = "?action=get&request="+src; xhr.open("GET", "./requests/data.php"+encodeURI(str), true); A: innerHTML is supported as of IE5. I think you problem is the use of the xmlhttprequest object. That one is only supported as of IE7. You can however ActiveXObject as stealthyninja's code uses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check value exists in XSLT I have some xml like this; <formErrors> <value>address_1</value> <value>address_2</value> //.. etc And in an XSL template I have $formErrors as a variable and I want to check if a value exists. If there was a PHP equivalent, I would want an in_array() function. How can I do this in XSLT? A: <xsl:if test="count(formErrors/value) > 1"> Show Errors </xsl:if> <!-- Test if value exists --> <xsl:if test="formErrors/value ='address_1'"> Show Errors </xsl:if> A: Try this : <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" > <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:variable name="check">address_1</xsl:variable> <xsl:if test="count(/formErrors[value/text() = $check]) > 0"> <xsl:message terminate="no">Value with text <xsl:value-of select="$check"/> : exists!</xsl:message> </xsl:if> </xsl:template> </xsl:stylesheet> Output : [xslt] : Warning! Value with text address_1 : exists!
{ "language": "en", "url": "https://stackoverflow.com/questions/7571832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: In ASP, what is the best way to save request variables to a frame I have a main page with a frame with its attribute src set to equal "SomeOther.asp". Since I have some rather large request variables, I want to save my request variables from my current page into my SomeOther.asp frame. Is there a way to transfer my request variables to my frame's page? The reason is b/c in my SomeOther.asp I can't really use query string for all variables b/c one is a bunch of 1,2,3,4,5,..... 4000 more of them which represents IDs, and I'd rather not use cookies, but I can use request object, or perhaps a session variable. If I can't use request attributes I am planning on using a session variable and just transferring the name of this variable in a query string ie... <frame src="SomeOther.asp?mysess=uniquesessionname ... Here is my workflow page1 form loaded, submit button hit, from data submitted to post to page2. Page2 automatically calls page3 with query string data. Page3 has the frame on it. I can access the request input items from page1 on page3, but not on page3's frame. This is what I'm trying to do. Thanks. A: You can try by post method on same page as src of Ifram. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <form action="v.asp" method="post"> <iframe src="v.asp"></iframe> <input type="text" name="txt1" value="123" /> <input type="submit" value="click" /> </form> </body> </html> A: You can transfer your querystring to the iframe using JavaScript: document.frames[0].src="SomeOther.asp?" + document.location.pathname A: You may want to clarify what you mean by request variables. Variables in query strings would generally be considered request variables but you say you can't use querystring... Do you mean you want to do them like form submission? And where are these variables coming from? Are they calculated in your asp page or are they external parameters passed to your parent page somehow? You can set the target for a form submission to be an iframe in which case the response from the form will be displayed in the frame. You can as others have suggested put the variables on the querystring but you suggest that might get too long. If they are starting off on the server then storing them on the server is sensible. If in session you can either store each of the variables in an equivalent session variable. This will cause problems if the user has multiple copies of the page open. You can do as you suggest and store all the variables under a single unique session key and then pass that as the single querystring parameter. Lastly you could store the state into a persistent medium such as a database and use the id of that in your frame querystring to retrieve it. This may be better than storing in session depending on the size of what you are storing, volume of traffic, etc. Generally it can be a very bad idea to store anything too large in session due to the amount of memory you may start eating up if you aren't careful. Without more details it is hard to say what will be best for your scenario but hopefully the above should give you some ideas on where you can go with it. A: Is it absolutely necessary that you use a frame? If it's just to display a menu or special area only visible to a logged in user, you should really consider using CSS to create the "frame" effect then you won't need to pass your request variables to your frame or have to necessarily mess around with sessions just to pass information from one to the other. Here are some examples: http://fu2k.org/alex/css/frames/scalablefixed http://www.webpelican.com/web-tutorials/css-frames-tutorial/ If the frame is necessary then I'd suggest going with sessions. A: If you want to manipulate with the submited data within an iframe, why not use "target" attribute of the form tag to point to the iframe? <form action="ProcessPage.asp" target="iframeName"> ....all your inputs... </form> <iframe name="iframeName"></iframe> A: To the best of my knowledge it is possible to bind query string variables inside of frame elements: <frame src="SomeOther.asp?someid=5&mode=2"/> AFAIK, HTML treats all URLs the same and so frames can contain the same query string data as normal Page URLs have. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ERROR 1005 (HY000): Can't create table '......\issue.frm' (errno: 150) This is the SQL: CREATE TABLE user ( userID INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL, username VARCHAR(100) NOT NULL, isAdmin BOOL NOT NULL DEFAULT 0, canAssignIssue BOOL NOT NULL DEFAULT 0, canMarkDuplicate BOOL NOT NULL DEFAULT 0, canProcessIssue BOOL NOT NULL DEFAULT 0 ) ENGINE = InnoDB; CREATE TABLE issue ( issueID INTEGER UNSIGNED AUTO_INCREMENT NOT NULL, title VARCHAR(100) NOT NULL, body TEXT NOT NULL, duplicateOf INTEGER UNSIGNED DEFAULT NULL, issueDateTime DATETIME NOT NULL, postBy INTEGER UNSIGNED NOT NULL, PRIMARY KEY (issueID, postBy, duplicateOf), INDEX (postBy, duplicateOf), FOREIGN KEY (duplicateOf) REFERENCES issue (issueID) ON DELETE SET NULL, FOREIGN KEY (postBy) REFERENCES user (userID) ON DELETE SET NULL ) ENGINE = InnoDB; I got this error message from the above code: ERROR 1005 (HY000): Can't create table '......\issue.frm' (errno: 150) However, if I change FOREIGN KEY (duplicateOf) REFERENCES issue (issueID) ON DELETE SET NULL, to FOREIGN KEY (duplicateOf) REFERENCES issue (issueID) ON DELETE NO ACTION, the code works. A: I reckon the problem here is that you are specifying columns in your issue table primary key definition to be set to null in the event of their parent row being deleted. MySQL will not like this since primary key columns are not allowed to contain null values. A quick tweak to the DDL of the issue table should allow you to do what you want. One of the key (no pun intended) differences between a primary key and a unique key is that unique key columns are allowed to contain null values. I'm taking a guess that the issueID column will be unique too given that it is specified as AUTO_INCREMENT. Try the following: CREATE TABLE issue ( issueID INTEGER UNSIGNED AUTO_INCREMENT NOT NULL, title VARCHAR(100) NOT NULL, body TEXT NOT NULL, duplicateOf INTEGER UNSIGNED, issueDateTime DATETIME NOT NULL, postBy INTEGER UNSIGNED NULL, PRIMARY KEY (issueID), UNIQUE INDEX (issueID,duplicateOf,postBy), INDEX (postBy, duplicateOf), FOREIGN KEY (duplicateOf) REFERENCES issue (issueID) ON DELETE SET NULL, FOREIGN KEY (postBy) REFERENCES user (userID) ON DELETE SET NULL) ENGINE = InnoDB; Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7571851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Delay in parallel computing I'm using parallel.for to launch in many threads a external program. But despite the fact that these are separate threads I need implement sth like delay. E.g. 2 threads want to launch this external program at the same moment - then one of them should wait and start e.g. 10 sec after second thread. Is it possible? A: It's possible, but given the information you've provided it seems pointless... you're enforcing single-threaded execution of the external program, so you might as well have a single thread executing it. If Thread 2 has to wait for Thread 1 in order to start the "external program," then just let Thread 1 do all the work since it already knows when it started the "external program." The only benefit you will get from a multi-threaded approach is if you have a bunch of processing that you need to do prior to executing the "external program" and that processing has to be a good candidate for concurrent execution. Update OK, there are a couple of ways to do this with only one extra thread in order to keep your Main/GUI thread responsive. The first approach is a simple lock around the external resource which you're interacting with: public class ExternalResourceHandler { private readonly ExternalResource _resource; private readonly object _sync = new object(); // constructors // ... // other methods public void PerformExternalOperation() { lock(_sync) { Result result = _resource.Execute(); // do soemthing with the result } } } Here are 3 multi-threaded version for executing the code: * *Using a Parallel.For method: recommended if the external program takes a short amount of time to execute- I'd suggest for things under 25 seconds (although this is not necessarily a "correct" number). *Using a ThreadPool: again, I'd recommend for things that take less than 25 seconds (with the same reservation as above). *Using a Thread: this would be recommended if the operation runs longer (i.e. more than 25 seconds, but it would do just as good if it's under 25 seconds). Here are some examples (not necessarily functional, mostly meant to give you an idea of the different approaches): public class Program { public static ExternalResourceHandler _erh = new ExternalResourceHandler(); static int Main() { Console.WriteLine("Type 'exit' to stop; 'parallel', 'pool' or 'thread' for the corresponding execution version."); string input = Console.ReadLine(); while(input != "exit") { switch(input) { case "parallel": // Run the Parallel.For version ParallelForVersion(); break; caase "pool": // Run the threadpool version ThreadPoolVersion(); break; case "thread": // Run the thread version ThreadVersion(); break; default: break; } input = Console.ReadLine(); } return 0; } public static void ParallelForVersion() { Parallel.For(0, 1, i => { _erh.PerformExternalOperation(); }); } public static void ThreadPoolVersion() { ThreadPool.QueueUserWorkItem(o=> { _erh.PerformExternalOperation(); }); } public static void ThreadVersion() { Thread t = new Thread(()=> { _erh.PerformExternalOperation(); }); t.IsBackground = true; t.Start(); } } The other option is to employ the Producer/Consumer design pattern where your ExternalResourceHandler is the consumer and it processes requests to the external resource from a thread-safe queue. Your main thread just places requests on the queue and immediately returns back to work. Here is an example: public class ExternalResourceHandler { private volatile boolean _running; private readonly ExternalResource _resource; private readonly BlockingQueue<Request> _requestQueue; public ExternalResourceHandler( BlockingQueue<Request> requestQueue) { _requestQueue = requestQueue; _running = false; } public void QueueRequest(Request request) { _requestQueue.Enqueue(request); } public void Run() { _running = true; while(_running) { Request request = null; if(_requestQueue.TryDequeue(ref request) && request!=null) { _resource.Execute(request); } } } // methods to stop the handler (i.e. set the _running flag to false) } Your main would look like this: public class Program { public static ExternalResourceHandler _erh = new ExternalResourceHandler(); static int Main() { Thread erhThread = new Thread(()=>{_erh.Run();}); erhThread.IsBackground = true; erhThread.Start(); Console.WriteLine("Type 'exit' to stop or press enter to enqueue another request."); string input = Console.ReadLine(); while(input != "exit") { _erh.EnqeueRequest(new Request()); input = Console.ReadLine(); } // Stops the erh by setting the running flag to false _erh.Stop(); // You may also need to interrupt the thread in order to // get it out of a blocking state prior to calling Join() erhThread.Join(); return 0; } } As you see: in both cases all the work for the external handler is forced on a single thread yet your main thread still remains responsive. A: Look at producer-consumer pattern. The first thread produces the information "external progam launched" the second thread consumes it, waits 10 second and then launches the external program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: netdb.h not linking properly I'm trying to compile this program, as referenced in Beej's Guide to Network Programming on page 19. #include <stdio.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> int main() { int status; struct addrinfo hints; struct addrinfo *servinfo; /* Will point to the results */ memset(&hints, 0, sizeof hints); /* Make sure the struct is empty */ hints.ai_family = AF_UNSPEC; /* Don't care IPv4 or IPv6 */ hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ((status = getaddrinfo(NULL, "3490", &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status)); exit(1); } /* Servinfo now points to a linked list of 1 or more struct addrinfos ... do everything until you don't need servinfo anymore .... */ freeaddrinfo(servinfo); /* Free the linked-list */ return 0; } Among other errors, I see ../main.c:8:18: error: storage size of ‘hints’ isn’t known ../main.c:13:19: error: ‘AI_PASSIVE’ undeclared (first use in this function) ../main.c:16:3: warning: implicit declaration of function ‘gai_strerror’ It appears that gcc isn't linking with netdb.h. Eclipse, the IDE that I'm using to build this, has no trouble finding the file. Here's the compiler command: gcc -O0 -g3 -pedantic -Wall -c -fmessage-length=0 -ansi -MMD -MP -MF"main.d" -MT"main.d" -o"main.o" "../main.c" Adding -lnetdb doesn't resolve the issue. Also... ~> find /usr/include/ -name netdb.h /usr/include/bits/netdb.h /usr/include/gssrpc/netdb.h /usr/include/netdb.h /usr/include/rpc/netdb.h I think these files came preinstalled on my openSUSE host. Why doesn't gcc detect netdb.h? Or am I drawing the wrong conclusion? A: add at the top of your file #define _XOPEN_SOURCE 600 A: ../main.c:8:18: error: storage size of ‘hints’ isn’t known ../main.c:13:19: error: ‘AI_PASSIVE’ undeclared (first use in this function) ../main.c:16:3: warning: implicit declaration of function ‘gai_strerror’ It appears that gcc isn't linking with netdb.h.... These are not linking errors, and you don't need a netdb shared object file (there is no such beast; netdb.h simply defines data structures and macros for use in your code). These are compiler errors: gcc complaining because you're using names that it doesn't recognize (AI_PASSIVE) and data types for which the structure is unknown (struct addrinfo). The code as you've presented it appears to be correct, and addrinfo is defined in /usr/include/netdb.h. What happens if you compile it like this: gcc -c main.c Do you still get the same behavior? If so, take a look at the output of: gcc -E main.c This generates a preprocessed version of the code, with all of the #include statements replaced by their actual content. You should be able to grep through this and see if the compiler is actually getting /usr/include/netdb.h if if it's finding something else: $ gcc -E foo.c | grep netdb.h | awk '{print $3}' | sort -u Which on my system yields: "/usr/include/bits/netdb.h" "/usr/include/netdb.h" "/usr/include/rpc/netdb.h" When you add -ansi to the command line, your are changing the way gcc behaves in ways that will break the Linux kernel and many system header files. The addrinfo definition in netdb.h is protected like this: #ifdef __USE_POSIX /* Structure to contain information about address of a service provider. */ struct addrinfo { int ai_flags; /* Input flags. */ int ai_family; /* Protocol family for socket. */ int ai_socktype; /* Socket type. */ int ai_protocol; /* Protocol for socket. */ socklen_t ai_addrlen; /* Length of socket address. */ struct sockaddr *ai_addr; /* Socket address for socket. */ char *ai_canonname; /* Canonical name for service location. */ struct addrinfo *ai_next; /* Pointer to next in list. */ }; // ...other stuff... #endif When you run gcc with the -ansi flag, this undefines the __USE_POSIX macro, because things protected by this may not be strictly ANSI compliant. You can see the difference if you compare this: gcc -E /usr/include/netdb.h With this: gcc -E -ansi /usr/include/netdb.h Only the former contains the addrinfo structure. A: Linking doesn't attach a header file to the program, pre-processing handles header files. Linking attaches shared object libraries (look in /usr/lib) to compiled objects. Sometimes it is not sufficent to just add "-lnetdb" as the library might not be in the linker path. In that case, you need to use a -L(path) to add a path entry so the directive "-lnetdb" can find the correct netdb.so file. A: Use #include <netinet/in.h> ....along with that.....and in compilation (ubuntu).... gcc server/client -o server/client.c -lpthread (here lpthread is a linki processing thread)...which solves your problem. :-D
{ "language": "en", "url": "https://stackoverflow.com/questions/7571870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to create a group that can only manage registered users in Joomla I'm making a website for a client and Joomla, I want the client to be able to manage users on the site / delete them if necessary, but that is it, I don't want them to be able to see or do anything else on the site, what is the best way of doing that? Ideally I would have liked to have this done through the front end, I was looking to make a simple list osf users that only the admin group can access and manually delete them from the DB directly, but I'd rather do it through Joomla if that was possible for security reasons. I looked at ACL's a bit but couldn't really figure out how to limit the functions to what I want, any help is really appreciated. A: From the front end you won't have much luck with that. As far as user management all of that is handled on the backend. If you're looking to do that sort of thing you'll simply have to get much more familiar with the ACL - there's a good amount of documentation on www.joomla.org Even by utilizing the ACL I don't think there will be much you can do to limit a particular group to having access to JUST the userbase specifically. The best bet would be to educate your client about Joomla, how it works, what to change, how to change it and why to leave everything else alone. I know that may be problematic for things in the future, but unfortunately I don't know of any (and have not heard of any) front end solutions for what you're looking to do. I haven't heard of any back end solutions either however. I think certain things will be so intertwined to certain levels of permission you won't be able to have that kind of granularity. **edit: I'm almost 100% positive there's no way this is possible on 1.5.23 (or earlier versions) because the ACL simply isn't there. So my advice above is aimed specifically at versions up to 1.7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get a valid response code for an image using PHP CURL on a Linux server? I am trying to detect whether a URL to an image is valid, behind a firewall or behind an authenticated area. Below is the function that I have written: private function pingImg($img){ $found = FALSE; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $img); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_TIMEOUT, 7); $result = curl_exec($curl); if($result !== false){ if(curl_getinfo($curl, CURLINFO_HTTP_CODE) == "401"){ $found = TRUE; $this->_httpBasicAuthImages = TRUE; } //now check for invalid cert if(stripos($img, "https") !== FALSE){ curl_close($curl); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $img); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curl, CURLOPT_TIMEOUT, 7); $result = curl_exec($curl); if(!$result) { $found = TRUE; $this->_invalidSSL = TRUE; } } } else { //stalled ping, probably behind a firewall $found = TRUE; $this->_firewallImg = TRUE; } curl_close($curl); return $found; } That code works great on our development Windows server (returns all the proper response codes) but unfortunately it does not work on our production Linux server. Basically no response code is returned on the Linux server when an image is behind an authenticated zone (ie 401 status code). The response is blank. Has anyone encountered this same issue? If so, how do I fix it so the proper response code will be returned on our Linux server? Thanks for your time. A: OK, I found a solution. Not sure its the most elegant (I would rather use CURL for everything) but it works on the Linux server: @file_get_contents($img, NULL, stream_context_create(array('http'=>array('method' => "HEAD",'follow_location' => 0,'timeout'=>7)))); if (!empty($http_response_header)){ $code = ""; sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code); if($code == "401"){ $found = TRUE; $this->_httpBasicAuthImages = TRUE; }} I hope this helps anyone else encountering the same issue. More details about the new functionality can be found on the following page: http://hakre.wordpress.com/2011/09/17/head-first-with-php-streams/
{ "language": "en", "url": "https://stackoverflow.com/questions/7571875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lookup Field order I have a lookup field for a list of GMT time zones and I would like to define the order that the items appear on the new item and update item forms so that I can show on the dropdown box: GMT +1 GMT +2 GMT +3 instead of GMT +1 GMT +10 GMT +11 GMT +12 GMT +3 As much as I know, the lookup fields order the items alphabetically, is there a way to modify this order? A: You can use a custom lookup field that allows to choose a list view to load data from (e.g. SharePoint Filtered Lookup Field) and sort data in the view appropriately. I cannot test it, since I don't have access to SharePoint at the moment, but adding a space for 1-digit timezones might do the trick to: GMT +1 GMT +2 GMT +3 ... GMT +10 GMT +11 If that doesn't work, consider: GMT +01 GMT +02 GMT +03 ... GMT +10 GMT +11
{ "language": "en", "url": "https://stackoverflow.com/questions/7571878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does Eclipse Link work together with Vertica i'm currently testing vertica. Since vertica has a jdbc driver it should be possible to get it working. Is there a simple way to get Eclipse link to support vertica? Are there alternative orm framework (like hibernate) that support it? A: As long as you have a compliant JDBC driver EclipseLink should work with Vertica. Some features such as DDL generation, may require a custom DatabasePlatform class, which you could create if required. Most features should work with the generic DatabasePlatform. Are you encountering any specific issues? A: According to the Vertica Support Hibernate queries works with the org.hibernate.dialect.PostgreSQLDialect while this is true there are still some problems (exspecially with hbm2ddl) that can only be fixed with a custom dialect. Among those are: * *data type mapping: there are no 4 byte datatypes, so the default java int mapping to int4 doesn't work. same goes for several other types. *no indexes: for obvious reasons vertica doesn't know create index, if your model contains @index annotations, remove them not sure how far postgres is from vertica but with my own custom dialect that inherits the postgres dialect everything works so far. A: We recently tried to get Hibernate working with vertica unsuccessfully. One of the problems was an inexistent dialect for that combination. After consulting a Vertica consultant the answer was that there is no plans to provide this sort of support as ORMs like hibernate and a DB like Vertica provide different approaches for data storage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: onListItemClick that shows description toast when title is clicked not sure if I am on the correct section, but I needed help for my school project. Currently I am doing a listview that display the titles of the latest school news, whenever I click any of the title, I want it to toast the description of the selected title correspondingly. Anyone can help me on it? Thank you package sp.buzz.rss; import java.util.ArrayList; import android.app.ListActivity; import android.os.Bundle; import android.util.EventLogTags.Description; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import sp.buzz.rss.tools.*; public class StringRss extends ListActivity { HttpFetch a = new HttpFetch(); /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); String strOrg = a .DownloadText("http://www.sp.edu.sg/wps/wcm/connect/lib-spws/Site-SPWebsite/?srv=cmpnt&source=library&cmpntname=MNU-MobileRSSFeed-SPBuzz-Shine"); int start = strOrg.indexOf("<title>"); int end = strOrg.indexOf("</title>"); int startdesc = strOrg.indexOf("<![CDATA["); int enddesc = strOrg.indexOf("]]>"); int count = 0; ArrayList<String> value = new ArrayList(); ArrayList<String> cData = new ArrayList(); String title = strOrg.substring(start + 7, end); String description = strOrg.substring(startdesc + 9, enddesc); // Toast.makeText(this, title, Toast.LENGTH_LONG).show();// first title Toast.makeText(this, description, Toast.LENGTH_LONG).show();// first // desc // value.add(title); // count++; cData.add(description); String newContent = strOrg.substring(end + 5); String newDesc = strOrg.substring(enddesc + 3); start = newContent.indexOf("<title>"); end = newContent.indexOf("</title>"); startdesc = newDesc.indexOf("<![CDATA["); enddesc = newDesc.indexOf("]]>"); title = newContent.substring(start + 7, end); description = newDesc.substring(startdesc + 9, enddesc); // Toast.makeText(this, title, Toast.LENGTH_LONG).show();// second title Toast.makeText(this, description, Toast.LENGTH_LONG).show();// second // desc value.add(title); cData.add(description); count++; while (true) { newContent = newContent.substring(end + 5); newDesc = newDesc.substring(enddesc + 3); start = newContent.indexOf("<title>"); end = newContent.indexOf("</title>"); startdesc = newDesc.indexOf("<![CDATA["); enddesc = newDesc.indexOf("]]>"); if (start == -1 || end == -1) { break; } else if (startdesc == -1 || enddesc == -1) { break; } title = newContent.substring(start + 7, end); description = newDesc.substring(startdesc + 9, enddesc); // Toast.makeText(this, description, Toast.LENGTH_LONG).show();// // for count++; value.add(title); cData.add(description); /* * Toast.makeText(this, "Value array: " + title, Toast.LENGTH_LONG) * .show();// for debugging */ // Toast.makeText(this, description, Toast.LENGTH_LONG).show();// // for // description } // Create an array of Strings, that will be put to our ListActivity String[] names = new String[count]; String[] desc = new String[count]; // Create an ArrayAdapter, that will actually make the Strings above // appear in the ListView for (int i = 0; i < names.length; i++) { names[i] = value.get(i); } for (int i = 0; i < desc.length; i++) { desc[i] = cData.get(i).replaceAll("</P>", "\n") .replaceAll("<P>", ""); } this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names)); } static String title = ""; static String desc = ""; @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked Object o = this.getListAdapter().getItem(position); title = o.toString(); Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG) .show(); } } A: You can replace the method protected void onListItemClick with by putting into onCreate the code below. If it isn't working. ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String title = ((TextView) view).getText(); Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG) .show(); }}); Also I'm surprised that infinite while loop is working. You should do that part using threading otherwise the later parts of the method won't be reached. A: String title = (String) parent.getItemAtPosition(position); Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG) .show();
{ "language": "en", "url": "https://stackoverflow.com/questions/7571891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any way I can 'stream' a PDO query result 'into' the output buffer, instead of storing it into a string? There's little to be added, if you see the title of this question. I've got a query that retrieves a single row from a MySQL table, and I'm interested in a particular column, which is a BLOB. I would like PHP to write it into the output buffer, instead of storing ~500 KB into a string (which furthermore I'm not sure would be binary-safe). PDOStatement functions like: string PDOStatement::fetchColumn ([ int $column_number = 0 ] ) don't help me. Can you help giving me at least a direction? Thanks in advance. P.S.: I know storing ~500 KB stuff inside a DB table is not good, but it's not my choice, I just have to stick with it. A: I strongly believe the batch processing with Doctrine or any kind of iterations with MySQL (PDO or mysqli) are just an illusion. @dimitri-k provided a nice explanation especially about unit of work. The problem is the miss leading: "$query->iterate()" which doesn't really iterate over the data source. It's just an \Traversable wrapper around already fully fetched data source. An example demonstrating that even removing Doctrine abstraction layer completely from the picture, we will still run into memory issues: echo 'Starting with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n"; $pdo = new \PDO("mysql:dbname=DBNAME;host=HOST", "USER", "PW"); $stmt = $pdo->prepare('SELECT * FROM my_big_table LIMIT 100000'); $stmt->execute(); while ($rawCampaign = $stmt->fetch()) { // echo $rawCampaign['id'] . "\n"; } echo 'Ending with memory usage: ' . memory_get_usage(true) / 1024 / 1024 . " MB \n"; Output: Starting with memory usage: 6 MB Ending with memory usage: 109.46875 MB Here, the disappointing getIterator() method: namespace Doctrine\DBAL\Driver\Mysqli\MysqliStatement /** * {@inheritdoc} */ public function getIterator() { $data = $this->fetchAll(); return new \ArrayIterator($data); } You can use my little library to actually stream heavy tables using PHP Doctrine or DQL or just pure SQL. However you find appropriate: https://github.com/EnchanterIO/remote-collection-stream A: See this page. This loads the data into a stream, which can then be used with f* functions, including outputting directly to the browser with fpassthru. This is the example code from that page: <?php $db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2'); $stmt = $db->prepare("select contenttype, imagedata from images where id=?"); $stmt->execute(array($_GET['id'])); $stmt->bindColumn(1, $type, PDO::PARAM_STR, 256); $stmt->bindColumn(2, $lob, PDO::PARAM_LOB); $stmt->fetch(PDO::FETCH_BOUND); header("Content-Type: $type"); fpassthru($lob); ?> The key here is that after $stmt->execute(), you call $stmt->bindColumn('columnName', $stream, PDO::PARAM_LOB);, then call $stmt->fetch(PDO::FETCH_BOUND) to get the row (where the values are stored into the bound PHP variables). This is how I used it in Drupal, tested and working; it includes a lot of extra cache handling that should speed up your clients and only requires you to keep track of the Last-Modified time of your blobs: <?php $rfc2822_format = 'D, d M Y H:i:s e'; // This is basically the Drupal 7 way to create and execute a prepared // statement; the `->execute()` statement returns a PDO::Statement object. // This is the equivalent SQL: // SELECT f.fileType,f.fileSize,f.fileData,f.lastModified // FROM mfiles AS f WHERE fileID=:fileID // (with :fileID = $fileID) $statement = db_select('mfiles', 'f') ->fields('f', array('fileType', 'fileSize', 'fileData', 'lastModified')) ->condition('fileID', $fileID, '=') ->execute(); // All of the fields need to be bound to PHP variables with this style. $statement->bindColumn('fileType', $fileType, PDO::PARAM_STR, 255); $statement->bindColumn('fileSize', $fileSize, PDO::PARAM_INT); $statement->bindColumn('fileData', $fileData, PDO::PARAM_LOB); $statement->bindColumn('lastModified', $lastModified, PDO::PARAM_STR, 19); $success = false; // If the row was fetched successfully... if ($statement->fetch(PDO::FETCH_BOUND)) { // Allow [public] caching, but force all requests to ask the server if // it's been modified before serving a cache [no-cache]. header('Cache-Control: public no-cache'); // Format the Last-Modified time according to RFC 2822 and send the // Last-Modified HTTP header to aid in caching. $lastModified_datetime = DateTime::createFromFormat('Y-m-d H:i:s', $lastModified, new DateTimeZone('UTC')); $lastModified_formatted = $lastModified_datetime->format($rfc2822_format); header('Last-Modified: ' . $lastModified_formatted); // If the client requested If-Modified-Since, and the specified date/time // is *after* $datetime (the Last-Modified date/time of the API call), give // a HTTP/1.1 304 Not Modified response and exit (do not output the rest of // the page). if (array_key_exists('HTTP_IF_MODIFIED_SINCE', $_SERVER)) { // Ignore anything after a semicolon (old browsers sometimes added stuff // to this request after a semicolon). $p = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE'], 2); // Parse the RFC 2822-formatted date. $since = DateTime::createFromFormat($rfc2822_format, $p[0]); if ($lastModified_datetime <= $since) { header('HTTP/1.1 304 Not Modified'); exit; } } // Create an ETag from the hash of it and the Last-Modified time, and send // it in an HTTP header to aid in caching. $etag = md5($lastModified_formatted . 'mfile:' . $fileID); header('ETag: "' . $etag . '"'); // If the client requested If-None-Match, and the specified ETag is the // same as the hashed ETag, give a HTTP/1.1 304 Not Modified response and // exit (do not output the rest of the page). if (array_key_exists('HTTP_IF_NONE_MATCH', $_SERVER) && $etag == str_replace('"', '', stripslashes($_SERVER['HTTP_IF_NONE_MATCH']))) { header('HTTP/1.1 304 Not Modified'); exit; } // Set the content type so that Apache or whatever doesn't send it as // text/html. header('Content-Type: ' . $fileType); // Set the content length so that download dialogs can estimate how long it // will take to load the file. header('Content-Length: ' . $fileSize); // According to some comments on the linked page, PDO::PARAM_LOB might // create a string instead of a stream. if (is_string($fileData)) { echo $fileData; $success = true; } else { $success = (fpassthru($fileData) !== false); } } ?> Aside: If you need to provide a filename, a quick and dirty solution is to add the filename to the actual URL referencing the file; for http://example.com/fileurl.php, use http://example.com/fileurl.php/filename.jpg. This may not work if something is already interpreting the path info (like Drupal); the "better" solution is to send the header Content-Disposition: attachment; filename=filename.jpg, but this also prevents clients from viewing the image directly in the browser (although this may be a good thing depending on your situation).
{ "language": "en", "url": "https://stackoverflow.com/questions/7571892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Android: How to have a single (main) Activity instance or retrieve the Activity instance that I need? I am developing an Android app that execute a thread and update the GUI via a GUI Handler on GUI Activity. I need that the thread runs also when the user put the app in background. This is done! My problem is that I want to return to the Activity that was running before when the user return to it by app history or by apps launcher. Instead many often Android launch a new Activity instance. I have tried with application property "launchMode" ("SingleTop", "SingleInstance", "SingleTask"), but I can't obtain my goal. An alternative method could be that I open a notification from every Activity that run a thread, but how can I do to open the Activity "linked" to that notification? I hope in your help Thank you Edit: sample code for simplicity I have put all code in a single class. If you try this app, press the button on the bottom and the thread starts. Now if you go to home open other apps, you can see that the thread is again running, you see the toast (this is what I want), Then if you return on my app, or by clicking notification or by launcher or by app history, a new instance can be created and I lost the previous running. How can I solve this? How can I return always on running activity? TestThreadActivity.java package tld.test; import java.util.ArrayList; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ListView; import android.widget.Toast; import android.widget.ToggleButton; public class TestThreadActivity extends Activity { private static final int NOTIFY_THREAD_IS_RUNNING = 1; private MyRunnable myRunnable; private Thread myThread; // List of all message private ArrayList<String> responseList = new ArrayList<String>(10); // ListView adapter private ArrayAdapter<String> responseListAdapter; /** * Called when the activity is first created. **/ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); responseListAdapter = new ArrayAdapter<String>(this, R.layout.list_item, responseList); ListView listViewResponse = (ListView) findViewById(R.id.listViewResponse); listViewResponse.setAdapter(responseListAdapter); ToggleButton toggleButton = (ToggleButton) findViewById(R.id.startStopBtn); toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) startThread(); else stopThread(); } }); } /** * Create and start the thread **/ private void startThread() { // Clear listview responseList.clear(); responseListAdapter.notifyDataSetChanged(); if (myRunnable == null) myRunnable = new MyRunnable(guiHandler); myThread = new Thread(myRunnable, "myThread-" + System.currentTimeMillis()); myThread.start(); notifyThread(); Toast.makeText(this, "Thread Started", Toast.LENGTH_SHORT).show(); } /** * Stop the thread **/ private void stopThread() { myRunnable.stop(); cancelNotifyThread(); Toast.makeText(this, "Thread Stopped", Toast.LENGTH_SHORT).show(); } /** * Crea una notifica sulla barra di stato */ private void notifyThread() { int icon = R.drawable.icon; // default icon from resources CharSequence tickerText = "Thread is running"; // ticker-text long when = System.currentTimeMillis(); // notification time Context context = getApplicationContext(); // application Context CharSequence contentTitle = getString(R.string.app_name); // expanded // message // title CharSequence contentText = "Thread is running..."; // expanded message // text Intent notificationIntent = new Intent(this, this.getClass()); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); // the next two lines initialize the Notification, using the // configurations above Notification notification = new Notification(icon, tickerText, when); notification.flags |= Notification.FLAG_ONGOING_EVENT; notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); NotificationManager notificationManager = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)); notificationManager.notify(NOTIFY_THREAD_IS_RUNNING, notification); } /** * Clear previous notification */ private void cancelNotifyThread() { NotificationManager notificationManager = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)); notificationManager.cancel(NOTIFY_THREAD_IS_RUNNING); } // My GUI Handler. Receive message from thread to put on Activity's listView final private Handler guiHandler = new Handler() { @Override public void handleMessage(Message msg) { String newMsg = (String) msg.obj; // Add message to listView responseList.add(newMsg); responseListAdapter.notifyDataSetChanged(); // and show a toast to view that is running also when it is not in // foreground. Toast.makeText(TestThreadActivity.this, newMsg, Toast.LENGTH_SHORT) .show(); super.handleMessage(msg); } }; /** * Simple runnable. Only wait WAIT_INTERVAL milliseconds and send a message * to the GUI **/ public class MyRunnable implements Runnable { public static final int WHAT_ID = 1; private static final int WAIT_INTERVAL = 5000; private boolean isRunning; private int counter; private Handler guiHandler; public MyRunnable(Handler guiHandler) { super(); this.guiHandler = guiHandler; } public void stop() { isRunning = false; } @Override public void run() { counter = 0; isRunning = true; while (isRunning) { // Pause try { Thread.sleep(WAIT_INTERVAL); } catch (InterruptedException e) { } // Notify GUI Message msg = guiHandler.obtainMessage(WHAT_ID, "Thread is running: " + (++counter) + " loop"); guiHandler.sendMessage(msg); } } } } layout\main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:layout_width="match_parent" android:id="@+id/listViewResponse" android:layout_height="0dip" android:layout_weight="1.0" android:transcriptMode="normal"></ListView> <ToggleButton android:id="@+id/startStopBtn" android:layout_height="wrap_content" android:layout_width="match_parent" android:textOn="@string/toggleBtnStop" android:textOff="@string/toggleBtnStart"></ToggleButton> </LinearLayout> layout\list_item.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="fill_parent" android:padding="10dp" android:textSize="16sp" > </TextView> values\strings.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">TestThread</string> <string name="toggleBtnStart">Start Thread</string> <string name="toggleBtnStop">Stop Thread</string> </resources> A: I have solved! The problem was the Back button that destroy the activity. Then I have override onBackPressed method and ask user if quit or leave activity running. Moreover I have set launchMode="singleTop" that is what I need. It was easier than I thought ;) But I have a doubt: How could app running after destroy? The toast was visible also after thath back button was pressed. What is destroyed then?
{ "language": "en", "url": "https://stackoverflow.com/questions/7571897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSIS Pass Datasource Between Control Flow Tasks I'm having troubles solving this little problem, hopefully someone can help me. In my SSIS package I have a data flow task. There's several different transforms, merges and conversions that happen in here. At the end of the dataflow task, there is two datasets, one that contains two numbers that need to be compared, and another dataset that contains a bunch of records. Ideally, I would like to have these passed onto a whole new data flow task (separate sequence container) where I can do some validation work on it and separate the logic. I cant for the life of me figure out how to do it. Iv tried looking into scripting and storing the datasets as variables, but I'm not sure this is the right way to do it. The next step is to export the large dataset as a spreadsheet, but before this happens i need to compare the two numbers from the other dataset and ensure they're correct. A: To pass data flowing in one dataflow to another, You have to have a temporary location. This means that You have to put data in destination in one dataflow and then read that data in another dataflow. You can put data in number of destinations: * *database table *raw file *flat file *dataset variable (recordset destination) *any other destination component that you can read from with corresponding source component or by writing script or whatever Raw files are meant to be used for cases like this. They are binary and as such they are extremely fast to write to and read from. In case You insist to use recordset destination take a look at http://consultingblogs.emc.com/jamiethomson/archive/2006/01/04/SSIS_3A00_-Recordsets-instead-of-raw-files.aspx because there is no recordset source component. A: A Data Flow Task needs to have a destination; a Data Flow Task likewise is NOT a destination. Otherwise the data doesn't go anywhere in the pipeline. From my experience, your best bets are to: 1) Pump the data into staging tables in SQL Server, and then pick up the validations from there. 2) Do the validations in the same Data Flow task.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does the startup time of mobile Couchbase make impractical? I have just started exploring Couchbase Mobile for Android and have been impressed with how far it has progressed. It would be nice to have an alternative to Android's SQLite which would involve less boilerplate code. The biggest issue I have experienced so far is the startup time of CouchDB. I created a simple app which just starts the database and logs the startup time. The very first time the app is run, it takes 10 seconds between the call to start it and the callback indicating CouchDB is ready (on a Samsung Captivate). If the app is killed and restarted, this time reduces to 5 seconds which isn't too bad. I am concerned that this will impact usability, even if a splash screen and/or progress dialog is being displayed. I would like to know how people are handling this long startup time. Does it have a big impact on usability? Is there a way to make it manageable? A: Use TouchDB Couchbase Lite instead of Couchbase Mobile. It will cut the startup time from 5-10 seconds to 100 miliseconds. Read the Why-TouchDB document referenced below for the trade offs (It is not an exact replacement) and more detailed information. Here a paraphrase of the startup time related information from https://github.com/couchbaselabs/TouchDB-iOS/wiki/Why-TouchDB%3F Couchbase Mobile's code size (~4MB) and startup time (5-10 sec on typical devices) are serious problems, which deter some developers. TouchDB meets the following requirements: Quick startup time on relatively-slow CPUs; ideally 100ms or less. Edit: TouchDB has been renamed Couchbase Lite A: Are you using the latest version? They have recently reduced the install time by a significant amount. A: The sentiment from others using Couchbase is that the times I am seeing might be slightly high and not unreasonable to have a user wait for it to load. There is further discussion on the Mobile Couchbase list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python - how to find all intersections of two strings? How to find all intersections (also called the longest common substrings) of two strings and their positions in both strings? For example, if S1="never" and S2="forever" then resulted intersection must be ["ever"] and its positions are [(1,3)]. If S1="address" and S2="oddness" then resulted intersections are ["dd","ess"] and their positions are [(1,1),(4,4)]. Shortest solution without including any library is preferable. But any correct solution is also welcomed. A: This can be done in O(n+m) where n and m are lengths of input strings. The pseudocode is: function LCSubstr(S[1..m], T[1..n]) L := array(1..m, 1..n) z := 0 ret := {} for i := 1..m for j := 1..n if S[i] = T[j] if i = 1 or j = 1 L[i,j] := 1 else L[i,j] := L[i-1,j-1] + 1 if L[i,j] > z z := L[i,j] ret := {} if L[i,j] = z ret := ret ∪ {S[i-z+1..z]} return ret See the Longest_common_substring_problem wikipedia article for more details. A: Here's what I could come up with: import itertools def longest_common_substring(s1, s2): set1 = set(s1[begin:end] for (begin, end) in itertools.combinations(range(len(s1)+1), 2)) set2 = set(s2[begin:end] for (begin, end) in itertools.combinations(range(len(s2)+1), 2)) common = set1.intersection(set2) maximal = [com for com in common if sum((s.find(com) for s in common)) == -1 * (len(common)-1)] return [(s, s1.index(s), s2.index(s)) for s in maximal] Checking some values: >>> longest_common_substring('address', 'oddness') [('dd', 1, 1), ('ess', 4, 4)] >>> longest_common_substring('never', 'forever') [('ever', 1, 3)] >>> longest_common_substring('call', 'wall') [('all', 1, 1)] >>> longest_common_substring('abcd1234', '1234abcd') [('abcd', 0, 4), ('1234', 4, 0)] A: Batteries included! The difflib module might have some help for you - here is a quick and dirty side-by-side diff: >>> import difflib >>> list(difflib.ndiff("never","forever")) ['- n', '+ f', '+ o', '+ r', ' e', ' v', ' e', ' r'] >>> diffs = list(difflib.ndiff("never","forever")) >>> for d in diffs: ... print {' ': ' ', '-':'', '+':' '}[d[0]]+d[1:] ... n f o r e v e r A: Well, you're saying that you can't include any library. However, Python's standard difflib contains a function which does exactly what you expect. Considering that it is a Python interview question, familiarity with difflib might be what the interviewer expected. In [31]: import difflib In [32]: difflib.SequenceMatcher(None, "never", "forever").get_matching_blocks() Out[32]: [Match(a=1, b=3, size=4), Match(a=5, b=7, size=0)] In [33]: difflib.SequenceMatcher(None, "address", "oddness").get_matching_blocks() Out[33]: [Match(a=1, b=1, size=2), Match(a=4, b=4, size=3), Match(a=7, b=7, size=0)] You can always ignore the last Match tuple, since it's dummy (according to documentation). A: I'm assuming you only want substrings to match if they have the same absolute position within their respective strings. For example, "abcd", and "bcde" won't have any matches, even though both contain "bcd". a = "address" b = "oddness" #matches[x] is True if a[x] == b[x] matches = map(lambda x: x[0] == x[1], zip(list(a), list(b))) positions = filter(lambda x: matches[x], range(len(a))) substrings = filter(lambda x: x.find("_") == -1 and x != "","".join(map(lambda x: ["_", a[x]][matches[x]], range(len(a)))).split("_")) positions = [1, 2, 4, 5, 6] substrings = ['dd', 'ess'] If you only want substrings, you can squish it into one line: filter(lambda x: x.find("_") == -1 and x != "","".join(map(lambda x: ["_", a[x]][map(lambda x: x[0] == x[1], zip(list(a), list(b)))[x]], range(len(a)))).split("_")) A: def IntersectStrings( first, second): x = list(first) #print x y = list(second) lst1= [] lst2= [] for i in x: if i in y: lst1.append(i) lst2 = sorted(lst1) + [] # This above step is an optional if it is required to be sorted alphabetically use this or else remove it return ''.join(lst2) print IntersectStrings('hello','mello' )
{ "language": "en", "url": "https://stackoverflow.com/questions/7571904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Using UNICODE character values in C++ How do you use unicode in C++ ? Im aware of wchar_t and wchar_t* but I want to know how you can assign value using only Unicode Values, similar to the way a character can be assigned by equating the variable to the ASCII value: char a = 92; Im uysing the MinGW compiler, if it makes a difference. A: Exactly the same way: wchar_t a = 97; wchar_t xi = 0x03be; // ξ A: It can be as simple as: wchar_t a=L'a'; wchar_t hello_world[]=L"Hello World"; // Or if you really want it to be (old school) C++ and not C std::wstring s(L"Hello World"); // Or if you want to (be bleeding edge and) use C++11 std::u16string s16(u"Hello World"); std::u32string s32(U"Hello World for the ∞ᵗʰ time");
{ "language": "en", "url": "https://stackoverflow.com/questions/7571907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: visual studio and .net 3.5 I have multiple versions of .Net installed on my machine. I need my current Visual Studio project to use .net 3.5 dlls, is there an automatic way of doing this? Or do I need to manually remove and add references? Also I am missing a lot of dlls in .net 3.5. Appreciate the help, Bruce A: .net 3.5 is not a complete framework, it is an addition to .net 3, which is an extension of .net 2 (adding WCF etc) Wikipedia's .NET 3.5 article Right click the project and select properties and select the Target Framework from the drop down. A: Change IIS entry as following: 1. In IIS select your local website 2. Right click and select properties 3. In ASP.Net tab select ASP.Net version as 3.5 Configure VS for debugging: 1.Open web project in Visual studio 2. Select Website ->start Options 3. Choose Build from left hand menu and select Target Framework as .Net Framework 3.5 This should take care of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a function in c++ to output to designated source I want to have a function that outputs certain pieces of information to a specific designated source that is inputted to the function. In code, what I mean is: function output( source ) { source << "hello" << endl; } where source can be a ofstream or cout. So that I can call this function like so: output(cout) or ofstream otp ("hello"); output(otp) My question is, how do I characterize source to make this work? It's fair to assume that source will always be a member of the std class Thanks! A: void output(std::ostream &source) { source << "hello" << std::endl; } or even: template <T> void output(T &source) { source << "hello" << std::endl; } A: Write your function as: std::ostream& output(std::ostream& source ) { return source << "hello" << endl; } Then you can use it as: output(cout); //and ofstream otp ("hello"); output(otp); //and output(output(cout)); output(output(output(cout))); output(output(output(output(cout)))); //and even this: output(output(output(output(cout)))) << "weird syntax" << "yes it is" ; By the way, if the output function has many lines, then you can write it as: std::ostream& output(std::ostream& source ) { source << "hello" << endl; source << "world" << endl; //.... return source; } The point is that it should return source. In the earlier version, the function returns source. A: You should pass an std::ostream& as argument A: function output( source ) { source << "hello" << endl; } If this is a member function, the point of which is to dump data about objects of the class of which it is a member, consider renaming it to operator<<. So, instead of class Room { ... // usage myRoom.output(otp) void output(std::ostream& stream) { stream << "[" << m_name << ", " << m_age << "]"; } }; rather, try this: class Room { ... // usage opt << myRoom << "\n" friend std::ostream& operator<<(std::ostream& stream, const Room& room) { return stream << "[" << room.m_name << ", " << room.m_age << "]"; } }; That way, you can display the state of your class using a more natural syntax: std::cout << "My Room: " << myRoom << "\n"; instead of the klunky std::cout << "My Room: "; myRoom.output(std::cout); std::cout << "\n"; A: IMHO, redirecting output should be done at the user level. Write your C++ like this: cout << "hello" << endl; And when executing the application, user can redirect the output to whatever he wants, say a file: myapp > myfile
{ "language": "en", "url": "https://stackoverflow.com/questions/7571910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Dynamic SQL concatenation Having an issue concatenating the following statement. Basically I want the length column to add inches after but it will not run. I am going to create a function out of this in the future but unable to get past this step. What gives? declare @column varchar(255) declare @sql varchar(5000) declare @additional varchar(500) set @column = 'length' set @additional = 'inches' select @sql = 'select distinct ps.p_c_id, ' select @sql = @sql + @column + ' '+@additional+ ' ' + ' as value' select @sql = @sql select @sql = @sql + ' from dbo.Product ps inner join dbo.ProductAttributes psa on psa.p_s_id = ps.p_s_id where ps.p_c_id is not null and ' + @column + ' is not null' exec (@sql) A: You are concatenating, what i'm assuming is an int or float value to a string ' inches'...have to cast the "length" value as a varchar... just select your @sql next time to see the resulting syntax and it should jump out at you. here is changes that should work BTW...look at implementing EXEC sp_executesql ...makes dynamic sql less suseptable to injection by using parameters, etc... look up in Books OnLine Sorry...eating Crow...sp_executesql does not protect from injection just improves performance in general...see article MSDN SQL Injection declare @column varchar(255) declare @sql varchar(5000) declare @additional varchar(500) set @column = 'psa.length' set @additional = 'inches' select @sql = 'select distinct ps.p_c_id, ' select @sql = @sql + 'CAST(' + @column + ' AS varchar(10)) + ' + ''' '+@additional+ ''' ' + ' as value' select @sql = @sql select @sql = @sql + ' from dbo.Product ps inner join dbo.ProductAttributes psa on psa.p_s_id = ps.p_s_id where ps.p_c_id is not null and ' + @column + ' is not null' --select @sql AS [ExecutableSQL] exec(@sql) A: Your output is; select distinct ps.p_c_id, length inches as value from dbo.Product ps inner join dbo.ProductAttributes psa on psa.p_s_id = ps.p_s_id where ps.p_c_id is not null and length is not null So it looks like a missing , between length inches assuming you want both; select @sql = @sql + @column + ','+ @additional+ ' ' + ' as value'
{ "language": "en", "url": "https://stackoverflow.com/questions/7571914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding image to Toast? Is it possible to programmatically add an image to a toast popup? A: Yes, you can add imageview or any view into the toast notification by using setView() method, using this method you can customize the Toast as per your requirement. Here i have created a Custom layout file to be inflated into the Toast notification, and then i have used this layout in Toast notification by using setView() method. cust_toast_layout.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/relativeLayout1" android:background="@android:color/white"> <TextView android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="PM is here" android:gravity="center" android:textColor="@android:color/black"> </TextView> <ImageView android:layout_height="wrap_content" android:layout_width="fill_parent" android:src="@drawable/new_logo" android:layout_below="@+id/textView1" android:layout_margin="5dip" android:id="@+id/imageView1"> </ImageView> <TextView android:id="@+id/textView2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="This is the demo of Custom Toast Notification" android:gravity="center" android:layout_below="@+id/imageView1" android:textColor="@android:color/black"> </TextView> </RelativeLayout> CustomToastDemoActivity.java LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.cust_toast_layout, (ViewGroup)findViewById(R.id.relativeLayout1)); Toast toast = new Toast(this); toast.setView(view); toast.show(); A: Simply, Use the following: Toast toast = new Toast(myContext); ImageView view = new ImageView(myContext); view.setImageResource(R.drawable.image_icon); toast.setView(view); toast.show(); A: I think this is better that we show text of Toast on the image which we pass to the makeImageToast function... so I shades Knickedi codes and : public class utility { public static Toast makeImageToast(Context context, int imageResId, CharSequence text, int length) { Toast toast = Toast.makeText(context, text, length); View rootView = toast.getView(); LinearLayout linearLayout = null; View messageTextView = null; // check (expected) toast layout if (rootView instanceof LinearLayout) { linearLayout = (LinearLayout) rootView; if (linearLayout.getChildCount() == 1) { View child = linearLayout.getChildAt(0); if (child instanceof TextView) { messageTextView = (TextView) child; ((TextView) child).setGravity(Gravity.CENTER); } } } // cancel modification because toast layout is not what we expected if (linearLayout == null || messageTextView == null) { return toast; } ViewGroup.LayoutParams textParams = messageTextView.getLayoutParams(); ((LinearLayout.LayoutParams) textParams).gravity = Gravity.CENTER; // convert dip dimension float density = context.getResources().getDisplayMetrics().density; int imageSize = (int) (density * 25 + 0.5f); int imageMargin = (int) (density * 15 + 0.5f); // setup image view layout parameters LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(imageSize, imageSize); imageParams.setMargins(0, 0, imageMargin, 0); imageParams.gravity = Gravity.CENTER; // setup image view ImageView imageView = new ImageView(context); imageView.setImageResource(imageResId); imageView.setLayoutParams(imageParams); // modify root layout linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.setBackgroundResource(imageResId); linearLayout.setGravity(Gravity.CENTER); linearLayout.setHorizontalGravity(Gravity.CENTER); linearLayout.setHorizontalGravity(Gravity.CENTER); //addView(imageView, 0); return toast; } } and this is use of it: utility.makeImageToast(getApplicationContext(), R.drawable.your_image,"your_text",Toast.LENGTH_LONG).show(); A: You can create any view programmatically (since I am assuming you are asking on how to do this WITHOUT using a LayoutInflater) and call setView on the Toast you made. //Create a view here LinearLayout v = new LinearLayout(this); //populate layout with your image and text or whatever you want to put in here Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(v); toast.show(); A: Knickedi's solution is good, but if you only need an icon next to the text you can make use of the fact that the Toast has a pre-defined TextView with the same ID and set the icon on the TextView: Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); TextView tv = (TextView) toast.getView().findViewById(android.R.id.message); if (null!=tv) { tv.setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0); tv.setCompoundDrawablePadding(context.getResources().getDimensionPixelSize(R.dimen.padding_toast)); A: There's always the possibility to create a custom layout. There was one fact which I disliked about that: It breaks the system default toast UI. This could differ on different platforms and implementations. There's no simple way to use the system default resource so I decided to hack the toast and force an image into it. Hint: You can get the default resource like this: Toast.makeToast(context, "", 0).getView().getBackground() Here's a helper which will display an image in front of the toast message: Helper.makeImageToast(context, R.drawable.my_image, "Toast with image", Toast.LENGTH_SHORT).show() I use that to indicate success, info or error. Makes a toast information nicer and more expressive... (It's worth mentioning that the hack bases on the fact that the internal toast is using a LinearLayout so isn't system and implementation independent. See comments.) public static Toast makeImageToast(Context context, int imageResId, CharSequence text, int length) { Toast toast = Toast.makeText(context, text, length); View rootView = toast.getView(); LinearLayout linearLayout = null; View messageTextView = null; // check (expected) toast layout if (rootView instanceof LinearLayout) { linearLayout = (LinearLayout) rootView; if (linearLayout.getChildCount() == 1) { View child = linearLayout.getChildAt(0); if (child instanceof TextView) { messageTextView = (TextView) child; } } } // cancel modification because toast layout is not what we expected if (linearLayout == null || messageTextView == null) { return toast; } ViewGroup.LayoutParams textParams = messageTextView.getLayoutParams(); ((LinearLayout.LayoutParams) textParams).gravity = Gravity.CENTER_VERTICAL; // convert dip dimension float density = context.getResources().getDisplayMetrics().density; int imageSize = (int) (density * 25 + 0.5f); int imageMargin = (int) (density * 15 + 0.5f); // setup image view layout parameters LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(imageSize, imageSize); imageParams.setMargins(0, 0, imageMargin, 0); imageParams.gravity = Gravity.CENTER_VERTICAL; // setup image view ImageView imageView = new ImageView(context); imageView.setImageResource(imageResId); imageView.setLayoutParams(imageParams); // modify root layout linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.addView(imageView, 0); return toast; } A: Toast aa = Toast.makeText(getBaseContext(), "OPEN",Toast.LENGTH_SHORT); ImageView cc = new ImageView(getBaseContext()); cc.setImageResource(R.drawable.a); aa.setView(cc); aa.show(); A: class CustomToast extends AppCompatActivity { Button custom_toast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_toast); custom_toast = (Button) findViewById(R.id.customToast); custom_toast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LayoutInflater inflater=getLayoutInflater(); View layout=inflater.inflate(R.layout.custom_toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); TextView toastTextView=(TextView) findViewById(R.id.toastTextView); ImageView toastimageview=(ImageView) findViewById(R.id.toastImageView); toastTextView.setText("Custom toast in android"); toastimageview.setImageResource(R.drawable.ic_launcher_background); Toast toast=new Toast(CustomToast.this); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: Any JavaScript templating library/system/engine/technique that returns a DOM fragment? I have to make a high speed web app and I need a JavaScript templating library/system/engine/technique that returns a DOM Fragment instead of a String containing HTML. Of course it should have some similar language as Resig's Micro-Templating I am expecting something like this after compilation: function myTemplate(dataToRender){ var fragment = document.createDocumentFragment(); fragment = fragment.appendChild(document.createElement('h1')); fragment.appendChild(document.createTextNode(dataToRender.title)); fragment = fragment.parentNode; fragment = fragment.appendChild(document.createElement('h2')); fragment.appendChild(document.createTextNode(dataToRender.subTitle)); fragment = fragment.parentNode; return fragment; } Is there any option? Edit: Template function should not concatenate HTML strings. It decreases speed. JQuery templates are working with strings internally. So Resig's Micro-Templating. Edit2: I just did a benchmark on jsPerf. It is the first benchmark I did in JavaScript so some check it out(I am not sure if it's correct). A: Check out jquery templates. http://api.jquery.com/category/plugins/templates/ It let's you create html fragments with keywords like "if", "each", etc and undeclared variables. Then you can call "tmpl" on a fragment from JavaScript with some values, and a DOM element is returned. A: I don't know if this is what you're searching for, but Underscore.js has a template utility. Also, jquery can return the DOM of a matched element. A: You could create individual objects that represent regions of your page or even go down as far as the individual element level, and do all this without resorting to DOM scripting which will be super slow. For instance: function buttonFrag(data) { this.data = data; } buttonFrag.prototype = (function() { return { _html : function(h) { h.push("<h1>",data.title,"</h1>"); h.push("<h2>",data.subTitle,"</h2>"); }, render : function(id) { var html = []; this._html(html); document.getElementById.innerHTML = html.join(""); } } })(); To implement this, you'd simply create a new object then invoke its render method to an id on your page: var titleFragObj = new titleFrag({title: "My Title",subTitle: "My Subtitle"); titleFragObj.render("someId"); Of course you could get a bit more creative about the render method and use something like jQuery to write to a selector, then use the .html or .append methods like this: render : function(selectorString, bAppend) { var html = []; this._html(html); var htmlString = html.join(""); var destContainer = $(selectorString); if (bAppend) { destContainer.append(htmlString); } else { destContainer.html(htmlString); } } In that case you'd just provide a selector string and whether or not you want to append to the end of the container, or completely replace its contents: titleFragObj.render("#someId",true); You could even go so far as to create a base object from which all your fragments descend from, then all you'd do is override the _html method: function baseFragement(data) { this.data = data; } baseFragment.prototype = (function() { return { _html : function() { //stub }, render : function(selectorString, bAppend) { var html = []; this._html(html); var htmlString = html.join(""); var destContainer = $(selectorString); if (bAppend) { destContainer.append(htmlString); } else { destContainer.html(htmlString); } } }; })(); Then all descendants would look something like this: function titleFrag(data) { baseFragment.call(this,data); } titleFrag.prototype = new baseFragment(); titleFrag.prototype._html = function() { h.push("<h1>",data.title,"</h1>"); h.push("<h2>",data.subTitle,"</h2>"); } You could create an entire library of little fragment generators that descend from that common base class. A: I had a go at this in this jsFiddle. Replacing a chunk of content is fastest when using DOM methods, but setting innerHTML isn't cripplingly slower and probably acceptable if your templates aren't very complex and you won't lose too much time in the string manipulation. (This isn't very surprising, "dealing with broken HTML quickly" is kind of what browsers are supposed to do and innerHTML is an ancient and popular property that probably had lots of optimisation go into it.) Adding another join() step in the innerHTML method also didn't really slow it down. Conversely, using jQuery.tmpl() /and/ the DOM fragment method was orders of magnitude slower in Chrome on Mac. Either I'm doing something wrong in the dom_tmpl function, or deep-cloning DOM nodes is inherently slow. I commented out the append tests because they froze up the tab process when you run the whole suite - thousands through tens of thousands of nodes shoved into a document probably confuse Chrome somehow. Appending with innerHTML alone ended up glacially slow because the string ends up being really huge. The conclusion would seem to be: unless done stupidly or on very large strings, concatenating strings in a templating library likely isn't going to be what makes it slow, while trying to be clever with cloning chunks of the DOM will. Also, jQuery.tmpl() handled 2000-ish ops/sec on my computer, and 500-ish on my iPhone 4, this is likely "fast enough" if you're targetting these platforms. It was also in the same ballpark as the DOM fragment function making the latter largely pointless. If you mostly need to replace the content of existing nodes and your templates aren't very large, use Underscore.js's templating and innerHTML. Underscore.js seems to do ten passes through the whole string, so if your templates /are/ large this could be an issue. If you need to append to existing nodes, you can avoid serialising and reparsing the existing content by creating a wrapper element, seting its innerHTML, then append the wrapper element to the target node. If you really want speed or your templates are crazy large, you'll probably have to do something like having a server-side script precompile your templates into Javascript that creates the respective nodes. (Disclaimer: I don't claim to be any good at constructing test cases and benchmarks and only tested this in WebKit, you should tailor this to your use case and get a more relevant set of numbers.) Update: I updated my jsFiddle benchmark to not use any jQuery features, in case its presence (user data on nodes etc.) was the cause of DOM node cloning being slow. Didn't help much.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows Service Hosted WCF Service Getting "Access Denied" When Trying To Read a File I have created a windows service for the sole purpose of hosting a WCF service. In the WCF service I have a method that when accessed by the client reads the registry for a path to a file. The method then reads the contents of a file and sends back the contents. Do to the business case where the file is being stored (and subsequently read) it is not located within the same directory as the WCF service. When trying to access the file I get an access denied error. I thought that the easiest solution was to change the account under which my windows service was running. I changed the account to LOCAL SERVICE and NETWORK SERVICE. I provided full security permissions to the directory in question for those credentials and was still unable to read the file! My next thought was since these machines are on the same domain that I could use impersonation to read the file. I have tried that setup, but now my client can't find my WCF service. What is wrong with my configuration for my service that is preventing me from either reading the file or accessing the service? Here is my App.config from the service: <?xml version="1.0"?> <configuration> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="TransportCredWSBinding"> <security mode="Transport"> <transport clientCredentialType="Windows" /> </security> </binding> </wsHttpBinding> </bindings> <services> <service name="AMS.CRSS.Service"> <host> <baseAddresses> <add baseAddress="https://localhost:8000/CRSS/service"/> <add baseAddress="http://localhost:8000/CRSS/service"/> </baseAddresses> </host> <!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/CRSS/service --> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="TransportCredWSBinding" contract="AMS.Core.Services.IService"/> <!-- the mex endpoint is exposed at https://localhost:8000/CRSS/service/mex --> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true--> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="False" httpsHelpPageEnabled="true"/> <serviceCredentials> <clientCertificate> <authentication mapClientCertificateToWindowsAccount="true" /> </clientCertificate> </serviceCredentials> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> My thought is that the WCF service is running under different credentials than the Windows Service which is its host. Am I wrong here? I suppose I could try giving "Everyone" access to the folder and seeing if that works. EDIT: Here is the client code that I am using to connect to the service: public static CRSSClient GetClientInstance(string clientHost) { UriBuilder ub = new UriBuilder("https", clientHost, 8000); ub.Path = "CRSS/service"; WSHttpBinding binding = new WSHttpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; CRSSClient client = new CRSSClient(binding, new EndpointAddress(ub.Uri)); client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; return client; } Here is the method which I am invoking from the client: [OperationBehavior(Impersonation = ImpersonationOption.Required)] public string ReadCAMConfig() { string camConfigText = null; string camConfigFileLocation = GetCAMConfigLocationFromReistry(); EventLog.WriteEntry("CRSS", "Reading CAM File: " + camConfigFileLocation + CAM_FILENAME); WindowsIdentity identity = ServiceSecurityContext.Current.WindowsIdentity; using (identity.Impersonate()) { try { if (File.Exists(camConfigFileLocation + CAM_FILENAME)) { camConfigText = File.ReadAllText(camConfigFileLocation + CAM_FILENAME); } } catch (Exception e) { EventLog.WriteEntry("CRSS", e.ToOutputString(), EventLogEntryType.Error); } } return camConfigText; } A: When debugging one of your service calls, what does WindowsIdentity.GetCurrent() return to you? I imagine you have an impersonation issue here; if it's not the service account, then you have impersonation enabled for the operation/service (note, the client side settings don't dictate impersonation, client & server have to match) in which case you have to give permission to all of the users that you are impersonating. Or you could just indicate that you want to identify the user, but not exactly impersonate. If the user is your service account, then you have to double-check the effective permissions on the files you are trying to open for the account your service is running under.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: use javascript to display label when checkbox is checked in an asp.net repeater I have an asp.net repeater that has 4 columns populated by a dataset that is pulled from a sql server. In one of the fields is a checkbox and all the others are labels. one field is called "type". Each record will be one of two types. What I would like to do is use javascript to check if a check box is checked and if so display the count for the "type" in a textbox. for example there would be two textboxes one would display "type 1 has 3 checked" and the other would display "type 2 has 3 checked". I currently have a Javascript function (see below) that counts all the checkboxes that are checked and displays a count in a text box, but I would like to be able to keep track of the count for each type. Is there any way in javascript I can capture the type when it is checking if the checkbox is checked. JavaScript function checkrpt() { var inputs = document.getElementsByTagName('input'); var count = 0 for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == "checkbox") { if (inputs[i].checked == true) count += 1; } if (count > 6) { inputs[i].checked = false; } } if (count > 0) { document.getElementById('txtSelectionStatus').value = count + ' items have been selected'; } else { document.getElementById('txtSelectionStatus').value = 'No items have been selected'; } if (count > 6) { document.getElementById('txtSelectionStatus').value = 'You can only select 6 itmes'; } } ASP:Repeater <asp:repeater id="rptStep1Data" runat="server"> <HeaderTemplate> <table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr style="backgound-color:#DDDDDD;"> <td width="150px" align="center" class="tableheader"><b>Add To Grid</b></td> <td width="100px" class="tableheader" align="center"><b>Distance</b></td> <td width="400px" align="left" class="tableheader"><b>Address</b></td> <td width="100px" align="center" class="tableheader"><b>Type</b></td> </tr> <tr> <td colspan="4"> <div style="overflow:scroll; overflow-x:hidden; height: 300px; width: 100%"> <table width="100%" border="1" cellpadding="0" cellspacing="0"> </HeaderTemplate> <ITEMTEMPLATE> <tr> <td width="148px" align="center" class="content"> <asp:checkbox id="chkSelected" runat="server" onClick="javascript:checkrpt()" Checked='<%# makeChecked(Container.DataItem("Selected")) %>' /> </td> <td width="100px" align="center" class="content"> <asp:label id="lblDistance" runat="server" Text='<%# Container.DataItem("Distance") %>' /> </td> <td width="390px" align="left" style="padding-left:10px" class="content"> <asp:label id="lblAddress" runat="server" Text='<%# Container.DataItem("Address") %>' /> </td> <td width="100px" align="center" class="content"> <asp:label id="lblType" runat="server" Text='<%# Container.DataItem("Type") %>' /> </td> </tr> </ITEMTEMPLATE> <ALTERNATINGITEMTEMPLATE> <tr> <td align="center" class="content"> <asp:checkbox id="chkSelected" runat="server" onClick="javascript:checkrpt()" Checked='<%# makeChecked(Container.DataItem("Selected")) %>' /> </td> <td align="center" class="content"> <asp:label id="lblDistance" runat="server" Text='<%# Container.DataItem("Distance") %>' /> </td> <td align="left" style="padding-left:10px" class="content"> <asp:label id="lblAddress" runat="server" Text='<%# Container.DataItem("Address") %>' /> </td> <td align="center" class="content"> <asp:label id="lblGLA" runat="server" Text='<%# Container.DataItem("Type") %>' /> </td> </tr> </ALTERNATINGITEMTEMPLATE> <FooterTemplate> </table> </div> </td> </tr> </table> </FooterTemplate> </asp:repeater> A: Try using onClientClick= "checkrpt()" instead of onClick event of checkbox. onClientClick runs client side javascript code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: counting with conditions in mysql im a bit stuck in a quite simple query i have these 4 columns in the table id1 (unique), id2 (can repeat) , updated (boolean), updated_on what i want now is to get a summary in the form id2, count of updates , max (updated_on) in short i want the result sorted by the recent updated_on while counting all rows for this id2 where update=1 and for ids that donot have any update=1, show 0, with the max updated_on ______________________ id2|_count__|___date__ 1 | 0 | 11/03/05, 3 | 5 | 11/03/04, 6 | 3 | 11/03/03, 2 | 0 | 11/03/02, i used this query : select id2, count(updated),max(updated_on) from table where updated=1 group by need_id_to but this query doesnot bring results where count would be 0 (for obvious reasons because im adding a condition in the where clause) A: A boolean field is 1 for true and 0 for false. You can use this to get the count of all updated = true rows. SELECT id2 , SUM(updated) as updates ,MAX(updated_on) as last_update FROM table1 GROUP BY id2 ORDER BY last_update DESC A: select id2, count(case when updated=1 then updated else null end) updates_count, max(updated_on) last_updated from table group by id2 order by last_updated desc A: select id2, SUM(CASE WHEN updated=1 THEN 1 ELSE 0 END) AS UpdatedCount, max(updated_on) from table group by id2
{ "language": "en", "url": "https://stackoverflow.com/questions/7571930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Mobile Hash Navigation not Working On Mobile Devices? When I run a jQuery Mobile page in Safari on a Mac everything runs fine. However when I run it on an iPad/iPod and select links on the page that are supposed to navigate to different pages it doesn't work. If I navigate directly to any given page (e.g., index.html#PageId), it works, but if I select a link, the hash tag does not get appended to the URL and the displayed page doesn't change. Any thoughts? A: This turned out to be some the result of some buried code that was intercepting the touch events and handling them incorrectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Printing numbers of the form 2^i * 5^j in increasing order How do you print numbers of form 2^i * 5^j in increasing order. For eg: 1, 2, 4, 5, 8, 10, 16, 20 A: This is actually a very interesting question, especially if you don't want this to be N^2 or NlogN complexity. What I would do is the following: * *Define a data structure containing 2 values (i and j) and the result of the formula. *Define a collection (e.g. std::vector) containing this data structures *Initialize the collection with the value (0,0) (the result is 1 in this case) *Now in a loop do the following: * *Look in the collection and take the instance with the smallest value *Remove it from the collection *Print this out *Create 2 new instances based on the instance you just processed * *In the first instance increment i *In the second instance increment j *Add both instances to the collection (if they aren't in the collection yet) *Loop until you had enough of it The performance can be easily tweaked by choosing the right data structure and collection. E.g. in C++, you could use an std::map, where the key is the result of the formula, and the value is the pair (i,j). Taking the smallest value is then just taking the first instance in the map (*map.begin()). I quickly wrote the following application to illustrate it (it works!, but contains no further comments, sorry): #include <math.h> #include <map> #include <iostream> typedef __int64 Integer; typedef std::pair<Integer,Integer> MyPair; typedef std::map<Integer,MyPair> MyMap; Integer result(const MyPair &myPair) { return pow((double)2,(double)myPair.first) * pow((double)5,(double)myPair.second); } int main() { MyMap myMap; MyPair firstValue(0,0); myMap[result(firstValue)] = firstValue; while (true) { auto it=myMap.begin(); if (it->first < 0) break; // overflow MyPair myPair = it->second; std::cout << it->first << "= 2^" << myPair.first << "*5^" << myPair.second << std::endl; myMap.erase(it); MyPair pair1 = myPair; ++pair1.first; myMap[result(pair1)] = pair1; MyPair pair2 = myPair; ++pair2.second; myMap[result(pair2)] = pair2; } } A: This is well suited to a functional programming style. In F#: let min (a,b)= if(a<b)then a else b;; type stream (current, next)= member this.current = current member this.next():stream = next();; let rec merge(a:stream,b:stream)= if(a.current<b.current) then new stream(a.current, fun()->merge(a.next(),b)) else new stream(b.current, fun()->merge(a,b.next()));; let rec Squares(start) = new stream(start,fun()->Squares(start*2));; let rec AllPowers(start) = new stream(start,fun()->merge(Squares(start*2),AllPowers(start*5)));; let Results = AllPowers(1);; Works well with Results then being a stream type with current value and a next method. Walking through it: * *I define min for completenes. *I define a stream type to have a current value and a method to return a new string, essentially head and tail of a stream of numbers. *I define the function merge, which takes the smaller of the current values of two streams and then increments that stream. It then recurses to provide the rest of the stream. Essentially, given two streams which are in order, it will produce a new stream which is in order. *I define squares to be a stream increasing in powers of 2. *AllPowers takes the start value and merges the stream resulting from all squares at this number of powers of 5. it with the stream resulting from multiplying it by 5, since these are your only two options. You effectively are left with a tree of results The result is merging more and more streams, so you merge the following streams 1, 2, 4, 8, 16, 32... 5, 10, 20, 40, 80, 160... 25, 50, 100, 200, 400... . . . Merging all of these turns out to be fairly efficient with tail recursio and compiler optimisations etc. These could be printed to the console like this: let rec PrintAll(s:stream)= if (s.current > 0) then do System.Console.WriteLine(s.current) PrintAll(s.next());; PrintAll(Results); let v = System.Console.ReadLine(); Similar things could be done in any language which allows for recursion and passing functions as values (it's only a little more complex if you can't pass functions as variables). A: For an O(N) solution, you can use a list of numbers found so far and two indexes: one representing the next number to be multiplied by 2, and the other the next number to be multiplied by 5. Then in each iteration you have two candidate values to choose the smaller one from. In Python: numbers = [1] next_2 = 0 next_5 = 0 for i in xrange(100): mult_2 = numbers[next_2]*2 mult_5 = numbers[next_5]*5 if mult_2 < mult_5: next = mult_2 next_2 += 1 else: next = mult_5 next_5 += 1 # The comparison here is to avoid appending duplicates if next > numbers[-1]: numbers.append(next) print numbers A: So we have two loops, one incrementing i and second one incrementing j starting both from zero, right? (multiply symbol is confusing in the title of the question) You can do something very straightforward: * *Add all items in an array *Sort the array Or you need an other solution with more math analysys? EDIT: More smart solution by leveraging similarity with Merge Sort problem If we imagine infinite set of numbers of 2^i and 5^j as two independent streams/lists this problem looks very the same as well known Merge Sort problem. So solution steps are: * *Get two numbers one from the each of streams (of 2 and of 5) *Compare *Return smallest *get next number from the stream of the previously returned smallest and that's it! ;) PS: Complexity of Merge Sort always is O(n*log(n)) A: I visualize this problem as a matrix M where M(i,j) = 2^i * 5^j. This means that both the rows and columns are increasing. Think about drawing a line through the entries in increasing order, clearly beginning at entry (1,1). As you visit entries, the row and column increasing conditions ensure that the shape formed by those cells will always be an integer partition (in English notation). Keep track of this partition (mu = (m1, m2, m3, ...) where mi is the number of smaller entries in row i -- hence m1 >= m2 >= ...). Then the only entries that you need to compare are those entries which can be added to the partition. Here's a crude example. Suppose you've visited all the xs (mu = (5,3,3,1)), then you need only check the @s: x x x x x @ x x x @ x x x x @ @ Therefore the number of checks is the number of addable cells (equivalently the number of ways to go up in Bruhat order if you're of a mind to think in terms of posets). Given a partition mu, it's easy to determine what the addable states are. Image an infinite string of 0s following the last positive entry. Then you can increase mi by 1 if and only if m(i-1) > mi. Back to the example, for mu = (5,3,3,1) we can increase m1 (6,3,3,1) or m2 (5,4,3,1) or m4 (5,3,3,2) or m5 (5,3,3,1,1). The solution to the problem then finds the correct sequence of partitions (saturated chain). In pseudocode: mu = [1,0,0,...,0]; while (/* some terminate condition or go on forever */) { minNext = 0; nextCell = []; // look through all addable cells for (int i=0; i<mu.length; ++i) { if (i==0 or mu[i-1]>mu[i]) { // check for new minimum value if (minNext == 0 or 2^i * 5^(mu[i]+1) < minNext) { nextCell = i; minNext = 2^i * 5^(mu[i]+1) } } } // print next largest entry and update mu print(minNext); mu[i]++; } I wrote this in Maple stopping after 12 iterations: 1, 2, 4, 5, 8, 10, 16, 20, 25, 32, 40, 50 and the outputted sequence of cells added and got this: 1 2 3 5 7 10 4 6 8 11 9 12 corresponding to this matrix representation: 1, 2, 4, 8, 16, 32... 5, 10, 20, 40, 80, 160... 25, 50, 100, 200, 400... A: First of all, (as others mentioned already) this question is very vague!!! Nevertheless, I am going to give a shot based on your vague equation and the pattern as your expected result. So I am not sure the following will be true for what you are trying to do, however it may give you some idea about java collections! import java.util.List; import java.util.ArrayList; import java.util.SortedSet; import java.util.TreeSet; public class IncreasingNumbers { private static List<Integer> findIncreasingNumbers(int maxIteration) { SortedSet<Integer> numbers = new TreeSet<Integer>(); SortedSet<Integer> numbers2 = new TreeSet<Integer>(); for (int i=0;i < maxIteration;i++) { int n1 = (int)Math.pow(2, i); numbers.add(n1); for (int j=0;j < maxIteration;j++) { int n2 = (int)Math.pow(5, i); numbers.add(n2); for (Integer n: numbers) { int n3 = n*n1; numbers2.add(n3); } } } numbers.addAll(numbers2); return new ArrayList<Integer>(numbers); } /** * Based on the following fuzzy question @ StackOverflow * http://stackoverflow.com/questions/7571934/printing-numbers-of-the-form-2i-5j-in-increasing-order * * * Result: * 1 2 4 5 8 10 16 20 25 32 40 64 80 100 125 128 200 256 400 625 1000 2000 10000 */ public static void main(String[] args) { List<Integer> numbers = findIncreasingNumbers(5); for (Integer i: numbers) { System.out.print(i + " "); } } } A: If you can do it in O(nlogn), here's a simple solution: Get an empty min-heap Put 1 in the heap while (you want to continue) Get num from heap print num put num*2 and num*5 in the heap There you have it. By min-heap, I mean min-heap A: As a mathematician the first thing I always think about when looking at something like this is "will logarithms help?". In this case it might. If our series A is increasing then the series log(A) is also increasing. Since all terms of A are of the form 2^i.5^j then all members of the series log(A) are of the form i.log(2) + j.log(5) We can then look at the series log(A)/log(2) which is also increasing and its elements are of the form i+j.(log(5)/log(2)) If we work out the i and j that generates the full ordered list for this last series (call it B) then that i and j will also generate the series A correctly. This is just changing the nature of the problem but hopefully to one where it becomes easier to solve. At each step you can either increase i and decrease j or vice versa. Looking at a few of the early changes you can make (which I will possibly refer to as transforms of i,j or just transorms) gives us some clues of where we are going. Clearly increasing i by 1 will increase B by 1. However, given that log(5)/log(2) is approx 2.3 then increasing j by 1 while decreasing i by 2 will given an increase of just 0.3 . The problem then is at each stage finding the minimum possible increase in B for changes of i and j. To do this I just kept a record as I increased of the most efficient transforms of i and j (ie what to add and subtract from each) to get the smallest possible increase in the series. Then applied whichever one was valid (ie making sure i and j don't go negative). Since at each stage you can either decrease i or decrease j there are effectively two classes of transforms that can be checked individually. A new transform doesn't have to have the best overall score to be included in our future checks, just better than any other in its class. To test my thougths I wrote a sort of program in LinqPad. Key things to note are that the Dump() method just outputs the object to screen and that the syntax/structure isn't valid for a real c# file. Converting it if you want to run it should be easy though. Hopefully anything not explicitly explained will be understandable from the code. void Main() { double C = Math.Log(5)/Math.Log(2); int i = 0; int j = 0; int maxi = i; int maxj = j; List<int> outputList = new List<int>(); List<Transform> transforms = new List<Transform>(); outputList.Add(1); while (outputList.Count<500) { Transform tr; if (i==maxi) { //We haven't considered i this big before. Lets see if we can find an efficient transform by getting this many i and taking away some j. maxi++; tr = new Transform(maxi, (int)(-(maxi-maxi%C)/C), maxi%C); AddIfWorthwhile(transforms, tr); } if (j==maxj) { //We haven't considered j this big before. Lets see if we can find an efficient transform by getting this many j and taking away some i. maxj++; tr = new Transform((int)(-(maxj*C)), maxj, (maxj*C)%1); AddIfWorthwhile(transforms, tr); } //We have a set of transforms. We first find ones that are valid then order them by score and take the first (smallest) one. Transform bestTransform = transforms.Where(x=>x.I>=-i && x.J >=-j).OrderBy(x=>x.Score).First(); //Apply transform i+=bestTransform.I; j+=bestTransform.J; //output the next number in out list. int value = GetValue(i,j); //This line just gets it to stop when it overflows. I would have expected an exception but maybe LinqPad does magic with them? if (value<0) break; outputList.Add(value); } outputList.Dump(); } public int GetValue(int i, int j) { return (int)(Math.Pow(2,i)*Math.Pow(5,j)); } public void AddIfWorthwhile(List<Transform> list, Transform tr) { if (list.Where(x=>(x.Score<tr.Score && x.IncreaseI == tr.IncreaseI)).Count()==0) { list.Add(tr); } } // Define other methods and classes here public class Transform { public int I; public int J; public double Score; public bool IncreaseI { get {return I>0;} } public Transform(int i, int j, double score) { I=i; J=j; Score=score; } } I've not bothered looking at the efficiency of this but I strongly suspect its better than some other solutions because at each stage all I need to do is check my set of transforms - working out how many of these there are compared to "n" is non-trivial. It is clearly related since the further you go the more transforms there are but the number of new transforms becomes vanishingly small at higher numbers so maybe its just O(1). This O stuff always confused me though. ;-) One advantage over other solutions is that it allows you to calculate i,j without needing to calculate the product allowing me to work out what the sequence would be without needing to calculate the actual number itself. For what its worth after the first 230 nunmbers (when int runs out of space) I had 9 transforms to check each time. And given its only my total that overflowed I ran if for the first million results and got to i=5191 and j=354. The number of transforms was 23. The size of this number in the list is approximately 10^1810. Runtime to get to this level was approx 5 seconds. P.S. If you like this answer please feel free to tell your friends since I spent ages on this and a few +1s would be nice compensation. Or in fact just comment to tell me what you think. :) A: I'm sure everyone one's might have got the answer by now, but just wanted to give a direction to this solution.. It's a Ctrl C + Ctrl V from http://www.careercup.com/question?id=16378662 void print(int N) { int arr[N]; arr[0] = 1; int i = 0, j = 0, k = 1; int numJ, numI; int num; for(int count = 1; count < N; ) { numI = arr[i] * 2; numJ = arr[j] * 5; if(numI < numJ) { num = numI; i++; } else { num = numJ; j++; } if(num > arr[k-1]) { arr[k] = num; k++; count++; } } for(int counter = 0; counter < N; counter++) { printf("%d ", arr[counter]); } } A: The question as put to me was to return an infinite set of solutions. I pondered the use of trees, but felt there was a problem with figuring out when to harvest and prune the tree, given an infinite number of values for i & j. I realized that a sieve algorithm could be used. Starting from zero, determine whether each positive integer had values for i and j. This was facilitated by turning answer = (2^i)*(2^j) around and solving for i instead. That gave me i = log2 (answer/ (5^j)). Here is the code: class Program { static void Main(string[] args) { var startTime = DateTime.Now; int potential = 0; do { if (ExistsIandJ(potential)) Console.WriteLine("{0}", potential); potential++; } while (potential < 100000); Console.WriteLine("Took {0} seconds", DateTime.Now.Subtract(startTime).TotalSeconds); } private static bool ExistsIandJ(int potential) { // potential = (2^i)*(5^j) // 1 = (2^i)*(5^j)/potential // 1/(2^1) = (5^j)/potential or (2^i) = potential / (5^j) // i = log2 (potential / (5^j)) for (var j = 0; Math.Pow(5,j) <= potential; j++) { var i = Math.Log(potential / Math.Pow(5, j), 2); if (i == Math.Truncate(i)) return true; } return false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Action specific JS Script just like view scripts By default, every action has its specific view script like index.phtml for index action. However more to this, I also want to have js script specifics to actions as well. like index.js for index action. I tried to use $this -> view -> headScript() -> prependScript('myjsfile.js');, but the script is added to top and not at the bottom as I was hoping for. I suppose a helper would do the trick. but i dont know how to create it. or there is a better solution of what i am hoping for. Even though I appendFile from the action, the files which are appended from the layout file always seems to come at last. Which is not what I want, I want files in the layout file to be loaded first and then the script provided in the action method. A: try $this->view->headScript()->appendFile('myjsfile.js'); instead of prepend! you can altough define an order for the files: $this->headScript()->offsetSetFile(1, 'myjsfile1.js') ->offsetSetFile(2, 'myjsfile2.js');
{ "language": "en", "url": "https://stackoverflow.com/questions/7571936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to delete items from a std::vector given a list of indices I have a vector of items items, and a vector of indices that should be deleted from items: std::vector<T> items; std::vector<size_t> indicesToDelete; items.push_back(a); items.push_back(b); items.push_back(c); items.push_back(d); items.push_back(e); indicesToDelete.push_back(3); indicesToDelete.push_back(0); indicesToDelete.push_back(1); // given these 2 data structures, I want to remove items so it contains // only c and e (deleting indices 3, 0, and 1) // ??? What's the best way to perform the deletion, knowing that with each deletion, it affects all other indices in indicesToDelete? A couple ideas would be to: * *Copy items to a new vector one item at a time, skipping if the index is in indicesToDelete *Iterate items and for each deletion, decrement all items in indicesToDelete which have a greater index. *Sort indicesToDelete first, then iterate indicesToDelete, and for each deletion increment an indexCorrection which gets subtracted from subsequent indices. All seem like I'm over-thinking such a seemingly trivial task. Any better ideas? Edit Here is the solution, basically a variation of #1 but using iterators to define blocks to copy to the result. template<typename T> inline std::vector<T> erase_indices(const std::vector<T>& data, std::vector<size_t>& indicesToDelete/* can't assume copy elision, don't pass-by-value */) { if(indicesToDelete.empty()) return data; std::vector<T> ret; ret.reserve(data.size() - indicesToDelete.size()); std::sort(indicesToDelete.begin(), indicesToDelete.end()); // new we can assume there is at least 1 element to delete. copy blocks at a time. std::vector<T>::const_iterator itBlockBegin = data.begin(); for(std::vector<size_t>::const_iterator it = indicesToDelete.begin(); it != indicesToDelete.end(); ++ it) { std::vector<T>::const_iterator itBlockEnd = data.begin() + *it; if(itBlockBegin != itBlockEnd) { std::copy(itBlockBegin, itBlockEnd, std::back_inserter(ret)); } itBlockBegin = itBlockEnd + 1; } // copy last block. if(itBlockBegin != data.end()) { std::copy(itBlockBegin, data.end(), std::back_inserter(ret)); } return ret; } A: std::sort() the indicesToDelete in descending order and then delete from the items in a normal for loop. No need to adjust indices then. A: It might even be option 4: If you are deleting a few items from a large number, and know that there will never be a high density of deleted items: Replace each of the items at indices which should be deleted with 'tombstone' values, indicating that there is nothing valid at those indices, and make sure that whenever you access an item, you check for a tombstone. A: I would go for 1/3, that is: order the indices vector, create two iterators into the data vector, one for reading and one for writting. Initialize the writing iterator to the first element to be removed, and the reading iterator to one beyond that one. Then in each step of the loop increment the iterators to the next value (writing) and next value not to be skipped (reading) and copy/move the elements. At the end of the loop call erase to discard the elements beyond the last written to position. BTW, this is the approach implemented in the remove/remove_if algorithms of the STL with the difference that you maintain the condition in a separate ordered vector. A: It depends on the numbers you are deleting. If you are deleting many items, it may make sense to copy the items that are not deleted to a new vector and then replace the old vector with the new vector (after sorting the indicesToDelete). That way, you will avoid compressing the vector after each delete, which is an O(n) operation, possibly making the entire process O(n^2). If you are deleting a few items, perhaps do the deletion in reverse index order (assuming the indices are sorted), then you do not need to adjust them as items get deleted. A: Since the discussion has somewhat transformed into a performance related question, I've written up the following code. It uses remove_if and vector::erase, which should move the elements a minimal number of times. There's a bit of overhead, but for large cases, this should be good. However, if you don't care about the relative order of elements, then this will not be all that fast. #include <algorithm> #include <iostream> #include <string> #include <vector> #include <set> using std::vector; using std::string; using std::remove_if; using std::cout; using std::endl; using std::set; struct predicate { public: predicate(const vector<string>::iterator & begin, const vector<size_t> & indices) { m_begin = begin; m_indices.insert(indices.begin(), indices.end()); } bool operator()(string & value) { const int index = distance(&m_begin[0], &value); set<size_t>::iterator target = m_indices.find(index); return target != m_indices.end(); } private: vector<string>::iterator m_begin; set<size_t> m_indices; }; int main() { vector<string> items; items.push_back("zeroth"); items.push_back("first"); items.push_back("second"); items.push_back("third"); items.push_back("fourth"); items.push_back("fifth"); vector<size_t> indicesToDelete; indicesToDelete.push_back(3); indicesToDelete.push_back(0); indicesToDelete.push_back(1); vector<string>::iterator pos = remove_if(items.begin(), items.end(), predicate(items.begin(), indicesToDelete)); items.erase(pos, items.end()); for (int i=0; i< items.size(); ++i) cout << items[i] << endl; } The output for this would be: second fourth fifth There is a bit of a performance overhead that can still be reduced. In remove_if (atleast on gcc), the predicate is copied by value for each element in the vector. This means that we're possibly doing the copy constructor on the set m_indices each time. If the compiler is not able to get rid of this, then I would recommend passing the indices in as a set, and storing it as a const reference. We could do that as follows: struct predicate { public: predicate(const vector<string>::iterator & begin, const set<size_t> & indices) : m_begin(begin), m_indices(indices) { } bool operator()(string & value) { const int index = distance(&m_begin[0], &value); set<size_t>::iterator target = m_indices.find(index); return target != m_indices.end(); } private: const vector<string>::iterator & m_begin; const set<size_t> & m_indices; }; int main() { vector<string> items; items.push_back("zeroth"); items.push_back("first"); items.push_back("second"); items.push_back("third"); items.push_back("fourth"); items.push_back("fifth"); set<size_t> indicesToDelete; indicesToDelete.insert(3); indicesToDelete.insert(0); indicesToDelete.insert(1); vector<string>::iterator pos = remove_if(items.begin(), items.end(), predicate(items.begin(), indicesToDelete)); items.erase(pos, items.end()); for (int i=0; i< items.size(); ++i) cout << items[i] << endl; } A: Basically the key to the problem is remembering that if you delete the object at index i, and don't use a tombstone placeholder, then the vector must make a copy of all of the objects after i. This applies to every possibility you suggested except for #1. Copying to a new list makes one copy no matter how many you delete, making it by far the fastest answer. And as David Rodríguez said, sorting the list of indexes to be deleted allows for some minor optimizations, but it may only worth it if you're deleting more than 10-20 (please profile first). A: Here is my solution for this problem which keeps the order of the original "items": * *create a "vector mask" and initialize (fill) it with "false" values. *change the values of mask to "true" for all the indices you want to remove. *loop over all members of "mask" and erase from both vectors "items" and "mask" the elements with "true" values. Here is the code sample: #include <iostream> #include <vector> using namespace std; int main() { vector<unsigned int> items(12); vector<unsigned int> indicesToDelete(3); indicesToDelete[0] = 3; indicesToDelete[1] = 0; indicesToDelete[2] = 1; for(int i=0; i<12; i++) items[i] = i; for(int i=0; i<items.size(); i++) cout << "items[" << i << "] = " << items[i] << endl; // removing indeces vector<bool> mask(items.size()); vector<bool>::iterator mask_it; vector<unsigned int>::iterator items_it; for(size_t i = 0; i < mask.size(); i++) mask[i] = false; for(size_t i = 0; i < indicesToDelete.size(); i++) mask[indicesToDelete[i]] = true; mask_it = mask.begin(); items_it = items.begin(); while(mask_it != mask.end()){ if(*mask_it){ items_it = items.erase(items_it); mask_it = mask.erase(mask_it); } else{ mask_it++; items_it++; } } for(int i=0; i<items.size(); i++) cout << "items[" << i << "] = " << items[i] << endl; return 0; } This is not a fast implementation for using with large data sets. The method "erase()" takes time to rearrange the vector after eliminating the element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Answer password to keytool in batch files i need use keytool and jarsigner to sign a lot o files here in many folders. Each time i start sign theses files i need delete the .cert and keystore file to recreate it. Im on development enviroment and using fake passwd to sign it, after application working the infra people will take care of sign it, i havent access to real certificates. When i was typing and the keytool -import ....... ,after enter, ask for password i simply type it but in batch it become a problem. Im on windows 7 here. I was tried keytool -import ....... < passHere and keytool -import ....... | passHere, too but it doesn't work. I want turn sign most automatic possible. There is someone telling about use it programatically here but i simply need it on a bat file. The password is a fixed value inside batch file. There is a way to give passwd inline to keytool? Is possible set an enviroment variable in 'run time' to feed keytool password? how do it ? There is a way to give passwd inside bath to keytool? I see this but dont help because i'm not a asm developer and not sure if it match problem and im wondering if there is something more simple. Thanks A: This command works for me (tested it with keytool from jdk 1.6.0.24): keytool -import -noprompt -file PathToCertificate -alias SomeCertificateAlias -keystore PathToKeyStore -storepass KeyStorePassword A: I needed batch creation of a keystore since I don't have access to the remote machine and need to create the keystore automatically. I tried this command (with the -noprompt and -storepass options), but it still asked for a password. I got around this doing an echo <password> | keytool ... with the same options as the other answer, which worked. A: I needed to create JKS keystores with keys from a PKCS12 store. This worked for me: echo <passphrase>| keytool.exe -importkeystore -srckeystore <source_pkcs12> -srcstoretype pkcs12 -destkeystore <jks_store> -deststoretype JKS -storepass <store_passphrase> -noprompt The trick was to not have a space between the passphrase and the | pipe symbol, otherwise keytool considers the space part of the passphrase.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Is there a way to focus a popover for a Safari extension? Just wanted to know if anyone knew how to put the focus on a popover for a Safari extension. Currently, the popover acts as if the window is inactive. This prevents any mouseover events from working and trying to type in any input field is difficult because there is no flashing cursor. A: According to a post on the Safari developer forums, this is a known issue with Lion and they are looking into it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using PHP to grab data from an XML feed when 2 or more fields have the same name I am having some issues getting this to work, I have a massive XML feed which I am putting into a MYSQL Database using PHP. One XML article looks like this... <Article Created="10:49:51" ID="800737873"> <Heading>Week in review: Mobile, Google+ and Facebook grab headlines</Heading> <Date>23/09/2011</Date> - <Contents> - <![CDATA[ This week NewsReach has been busy at ad:tech, speaking to lots of people about how we can help websites with targeted online newsfeeds, landing pages and other copy.<br/><br/>But we still found time to keep our finger on the pulse of the wider digital world and bring those stories straight to our readers.<br/><br/>This week saw a big focus on mobile marketing, with several industry commentators highlighting the importance of the channel for online communications.<br/><br/>&lt;promo&gt;At NewsReach we can provide quality content for all online marketing platforms - call Jacey on 02075172240 to learn more.&lt;/promo&gt;Digital trainer <a href="http://www.newsreach.co.uk/nr/online-marketing/marketings-future-is-mobile">Rob Thurner noted</a> that mobile allows businesses to &quot;unlock new segments of consumers&quot;, while research by Head London highlighted the importance of good mobile websites.<br/><br/><a href="http://www.newsreach.co.uk/nr/online-marketing/mobile-websites-should-aid-integrated-experience">Report authors suggested</a> that mobile websites should not simply copy the desktop version's content and functionality, but should be designed in line with what mobile users want.<br/><br/>Mobile devices, in particular smartphones, are integral to young adults, according to a <a href="http://www.newsreach.co.uk/nr/online-marketing/internet-integral-to-young-consumers">study by Cisco</a>. The telecoms systems provider found under-30s regard it as vitally important to be able to access the internet on the go.<br/><br/>After about two months in limited field trial stage, <a href="http://www.newsreach.co.uk/nr/social-media-marketing/google-opens-doors-and-rolls-out-search">Google+ is now available to anyone</a> who wants to sign up. Google also rolled out a new search function, which will allow users to get personalised web search results within the social network.<br/><br/>And after much speculation, <a href="http://www.directnews.co.uk/news/facebook-overhauls-profiles-with-timeline-$21378257.htm">Facebook announced yesterday</a> that it will overhaul users' profile pages by introducing a virtual scrapbook that allows members to chronicle their life in one place. <br/><br/><em>Written by <a href="http://uk.linkedin.com/in/karenwebber">Karen Webber</a>, Deputy Head of News Feeds</em> ]]> </Contents> - <Summary> - <![CDATA[ The future is mobile, while social networks continue their battle for supremacy. ]]> </Summary> - <Picture Orientation="Landscape" PhotoTag="Mobile, Google+ and Facebook grab headlines" Ratio="1.00" PhotoID="7036189"> <PhotoTag>Mobile, Google+ and Facebook grab headlines</PhotoTag> - <Large Width="500" Height="500"> <URL>http://pictures.directnews.co.uk/liveimages/mobile+google+and+facebook+grab+headlines_3166_800737873_1_0_7036189_500.jpg</URL> </Large> - <Medium Width="300" Height="300"> <URL>http://pictures.directnews.co.uk/liveimages/mobile+google+and+facebook+grab+headlines_3166_800737873_1_0_7036189_300.jpg</URL> </Medium> - <Small Width="100" Height="100"> <URL>http://pictures.directnews.co.uk/liveimages/mobile+google+and+facebook+grab+headlines_3166_800737873_1_0_7036189_100.jpg</URL> </Small> </Picture> - <Categories> <Category ID="800089637">Online Marketing</Category> <Category ID="800089646">ZHEADER</Category> <Category ID="800092440">ZREVIEW</Category> </Categories> </Article> The part that I want to specifically talk about is this: - <Categories> <Category ID="800089637">Online Marketing</Category> <Category ID="800089646">ZHEADER</Category> <Category ID="800092440">ZREVIEW</Category> </Categories> As you can see I have 3 Categories and 3 ID attributes. When getting the data using this method: $feed = new SimpleXMLElement('newsreacharchive2011.xml', null, true); foreach($feed as $article) // loop through { $category = mysql_real_escape_string("{$article->Categories->Category}"); $categoryID = mysql_real_escape_string("{$article->Categories->Category['ID']}"); } I only get the 1st of the 3 categories, so I am looking for some help getting hold of the next two categories, I dont know if I need to do a while loop within the foreach loop to get them or what, but im stuck so I hope someone can help. Thanks. ------- EXTENSION ------- I have just tried this $feed = new SimpleXMLElement('newsreacharchive2011.xml', null, true); foreach($feed as $article) // loop through { $i = 0; while($i < 3) { $category[$i] = mysql_real_escape_string("{$article->Categories->Category}"); $categoryID[$i] = mysql_real_escape_string("{$article->Categories->Category['ID']}"); $i++; } } and it still does not work A: $article->Categories->Category is an array with entries for each <Category> element in the XML. In this case, there are three Category elements, so you need to iterate over each one. $feed = new SimpleXMLElement('newsreacharchive2011.xml', null, true); foreach($feed as $article) // loop through { foreach($article->Categories->Category as $category) { $categoryName = mysql_real_escape_string((string)$category); $categoryID = mysql_real_escape_string((string)$category['ID']); // add to database } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make your Service-Reference proxy URL dynamic? I have a web reference to web-service: using (var client = new GetTemplateParamSoapClient("GetTemplateParamSoap")) { TemplateParamsKeyValue[] responsArray = client.GetTemplatesParamsPerId( CtId, tempalteIds.ToArray()); foreach (var pair in responsArray) { string value = FetchTemplateValue(pair.Key, pair.Value); TemplateComponentsData.Add(pair.Key, value); } } Tried to change a web-reference url from c# code: as advice here: 1) http://www.codeproject.com/KB/XML/wsdldynamicurl.aspx 2) How to call a web service with a configurable URL 3) http://aspalliance.com/283_Setting_Web_Service_References_Dynamically But I get symbol is missing when trying to do: client.Url In addition I couldn't find a property of "Url_behavior" A: It sounds like you've already added the service reference, but here's a walkthrough on adding, updating and removing service references. Once you've got one of those in your project, you can alter the endpoint URI with one of the constructor overloads, as John Saunders said above. To do this, you'll need to know the name of the endpoint in your config file. For instance, after you add your service you might have elements like this in your config file: <endpoint address="http://bleh.com/services/servicename.asmx" binding="basicHttpBinding" bindingConfiguration="ServiceNameSoap" contract="ServiceReference1.ServiceNameSoap" name="ServiceNameSoap" /> Given that endpoint, you can change the address at runtime by using the following overload: var proxy = new ServiceReference1.ServiceNameSoapClient("ServiceNameSoap", "http://new-address.com/services/servicename.asmx"); You can also do it after construction, but that becomes a little bit harder. If you need to do so, see the documentation on the Endpoint property and the associated type ServiceEndpoint.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ASP.NET ReportViewer body borders/lines How can I add borders to the body section of a report? I have lines on the left and right side of the body section (top to bottom), as well as "middle of the page" markers that intersect these lines. I want these lines to repeat on each page of the report, which contains numerous subreports. I tried creating a hidden table in the body, and then told the lines to repeat with the table. However, the top to bottom lines on the left and right show up only on the first page, while the small middle markers show up after all subreport content. Any advice on how to add repeating, free form lines to a report body is appreciated. I am using Visual Studio 2008 Professional on .NET 3.5 using ASP.NET WebForms. Thanks. A: Your body must have a List Item. You can add on the properties box the BorderColor, BorderStyle and BorderWidht
{ "language": "en", "url": "https://stackoverflow.com/questions/7571956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirecting users with JavaScript disabled So, given the following markup, if a users browser has JavaScript disabled, they will be redirected to an alternate page that either attempts to emulate the sites functionality without JavaScript (perhaps a dynamically rendered page), or a warning page, informing the user that JavaScript must be enabled to use the site <!doctype html> <html> <head> <!-- If the browser has javascript disabled, the browser will be redirected--> <!-- to a page that does not require javascript to function, or informs the--> <!-- the user of the requirement for javascript to be enabled--> <noscript> <meta http-equiv="refresh" content="5; url=/warning.html"/> </noscript> <title> Page Title </title> </head> <body> <script> // rich client logic </script> </body> </html> Judging by this html5 validator as well as the w3c validator it would appear that the above is valid html5. I'm considering using this technique to manage users that do not have JavaScript enabled and thereby cannot use the single page application I'm planning, but I haven't seen it before and was wondering if (a) has anyone used this technique in production before and care to share their experiences (b) can anyone offer up any valuable criticism as to why I shouldn't consider using this technique? Right now its looking like a viable option to me, but I'm not wholly confident of the potential side effects (such as the conditions under which a browser would NOT respect the redirect). A: can anyone offer up any valuable criticism as to why I shouldn't consider using this technique? You have a very fragile system. If the JS fails for any reason, it will break completely. Search engines could spider both versions of the site and link people to the "wrong" one. So don't do that. Use feature detection and build on things that work. A: I use this technique and it works perfectly well. I just add this line to the no JavaScript page: <META NAME="ROBOTS" CONTENT="NOINDEX, FOLLOW"> I used to disagree with this approach and recommend progressive enhancement but it just doesn't make sense to do this any more because: 1: About 1% of users will disable JavaScript, its a lot more than 1% more work to support them. (last years stats see: http://developer.yahoo.com/blogs/ydn/posts/2010/10/how-many-users-have-javascript-disabled/) 2: There isn't always any alternative to javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Scala -- How to use Functors on non-Function types? While reading the description of Functors on this blog: https://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/ there is a generic definition of Functor and a more specific one: trait GenericFunctor[->>[_, _], ->>>[_, _], F[_]] { def fmap[A, B](f: A ->> B): F[A] ->>> F[B] } trait Functor[F[_]] extends GenericFunctor[Function, Function, F] { final def fmap[A, B](as: F[A])(f: A => B): F[B] = fmap(f)(as) } Clearly this means Functors can be used with other higher-kinded types besides Function objects. Could someone please give an example or explain how or why or in what scenario that would be done? Namely, what would another implementation of GenericFunctor be in Scala -- that uses a different type constructor from Function? Thanks! EDIT: Just to clarify: object Functor { def fmap[A, B, F[_]](as: F[A])(f: A => B)(implicit functor: Functor[F]): F[B] = functor.fmap(as)(f) implicit object ListFunctor extends Functor[List] { def fmap[A, B](f: A => B): List[A] => List[B] = as => as map f } } scala> fmap(List(1, 2, 3))(x => x + 1) res0: List[Int] = List(2, 3, 4) Just to clarify, according to my understanding ListFunctor implements the 1-arg fmap in GenericFunctor while the code in the repl transcript calls the fmap in Trait Functor, which in turn calls an fmap implementation (e.g. in ListFunctor). This doesn't change the overall question, just thought it would help people trying to provide answers. Any insights provided would be appreciated. A: In your example Functor is an endofunctor in the category of Scala types with Function1 as arrows. There are other categories. For example, imagine a category in which the objects are Scala types, and there is an arrow A >~> B if B is a subtype of A. This category in Scalaz is called Liskov. There is a "forgetful" functor from the Liskov category to the Function1 category: import scalaz._ import Scalaz._ trait Forget[F[-_]] extends GenericFunctor[>~>, Function1, F] { def fmap[A, B](f: A >~> B): F[A] => F[B] = fa => f.subst(fa) } Note that you can build some interesting functors by fixing one or more of the arguments to GenericFunctor. For example... A constant functor maps every object in one category to a single object in another: type ConstantFunctor[->>[_, _], ->>>[_, _], C] = GenericFunctor[->>,->>>,({type F[x] = C})#F] // def fmap[A, B](f: A ->> B): C ->>> C An endofunctor maps a category to itself: type EndoFunctor[->>[_, _], F[_]] = GenericFunctor[->>, ->>, F] // def fmap[A, B](f: A ->> B): F[A] ->> F[B] An identity functor maps every object and arrow to itself: type IdentityFunctor[->>[_, _]] = EndoFunctor[->>, ({type F[x] = x})#F] // def fmap[A, B](f: A ->> B): A ->> B And of course, your Functor trait is just an EndoFunctor in the Function1 category. type Functor[F[_]] = EndoFunctor[Function1, F] // def fmap[A, B](f: A => B): F[A] => F[B] A: You can imagine a functor which lifts an instance of Either[A,B] into an Either[F[A],F[B]] where F can be a List, Option, etc. EDIT Implementation example: trait GenericFunctor[->>[_, _], ->>>[_, _], F[_]] { def fmap[A, B](f: A ->> B): F[A] ->>> F[B] } trait EitherFunctor[F[_]] extends GenericFunctor[Either,Either,F] object ListFunctor extends EitherFunctor[List] { def fmap[A,B]( f: Either[A,B] ): Either[List[A],List[B]] = f match { case Left(a) => Left( List(a) ) case Right(b) => Right( List(b) ) } } EDIT2 Another (maybe useful) example is with a functor with goes from a PartialFunction (type ->>) to a Function (type ->>>): trait PartialFunctor[F[_]] extends GenericFunctor[PartialFunction,Function,F] { final def fmap[A, B](as: F[A])(f: PartialFunction[A,B]): F[B] = fmap(f)(as) } object OptionFunctor extends PartialFunctor[Option] { def fmap[A,B]( f: PartialFunction[A,B] ): Option[A] => Option[B] = (opt:Option[A]) => opt match { case Some(a) => f.lift(a) case None => None } } object ListFunctor extends PartialFunctor[List] { private def mapPartial[A,B]( f: PartialFunction[A,B], as: List[A] ): List[B] = as match { case Nil => Nil case h :: t => if( f isDefinedAt h ) f(h) :: mapPartial( f, t ) else mapPartial( f, t ) } def fmap[A,B]( f: PartialFunction[A,B] ): List[A] => List[B] = (lst:List[A]) => mapPartial(f, lst) } This second example allows to implement the collect operation as defined in Scala collections: def collect[A,B,F[_]]( as: F[A] ) ( pf: PartialFunction[A,B] ) ( implicit functor: PartialFunctor[F] ) = functor.fmap( as )( pf ) A: Data.Category is a good source for examples of things like this (in Haskell). Partially translating one of the instances from http://hackage.haskell.org/packages/archive/data-category/0.4.1/doc/html/src/Data-Category-Functor.html: type OpFun[A, B] = B => A case class OpFunctor[F[_]](functor: Functor[F[_]]) extends GenericFunctor[OpFun, OpFun, F] { def fmap[A, B](f: B => A): F[B] => F[A] = fb => functor.fmap(fb)(f) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: WPF Combobox deriving from derived doesn't work HOPEFULLY, someone strong in WPF knows what's going on... The scenario I've sampled below is also applicable to others too, like textbox, command buttons, etc... I'm playing with creating custom user controls... Ex: working with a simple Combobox. In one project class library LibA I've created some samples derived from... ex: TextBox, ComboBox, Window, etc. A second library LibB I'm creating another class derived from ex: Combobox in LibA... Otherwise, no problem.... done similar thing in C# WinForms with no problems. Now, the problem, I drag the control (from LibB) onto the first "Window" (native so no derivation issues) of the app, save and run. The derived library doesn't even hit its constructor which I just put a simple command just test it was getting created properly worked or not, but its not... In the XAML of the form, it is properly referencing both namespace projects, so I know that appears correct. So, I then created a derived combobox in the same original LibA, put that on the form, and IT properly went into the constructor. Here's a snippet of what I have going on. namespace LibA { public class MyCombo1 : ComboBox { public MyCombo1() { ToolTip = "this is my base declaration"; } } public class MyCombo1b : MyCombo1 { public MyCombo1b() : base() { ToolTip = "this constructor IS reached"; } } } In a separate project (library), using FirstLibraryThatHas_MyCombo1 namespace LibB { public class OtherLibCombobox : MyCombo1 { public OtherLibCombobox() : base() { ToolTip = "this version is NOT being recognized in the window"; } } } So, neither of these are visually designed, they are all in code only... In addition, I've done it with the TextBox control too, same results... It doesn't stop in the debugger... Any ideas? Although I've changed actual names from sample, here's a brand new window, one with original class declaration AND one with the DERIVED version.. Here's a full XAML test window <Window x:Class="MyProject.TestWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="TestWindow" Height="300" Width="300" xmlns:my="clr-namespace:WPFGUI;assembly=WPFGUI" xmlns:my1="clr-namespace:DerivedControls;assembly=DerivedControls"> <Grid> <my:MyComboBoxClass Name="MyComboBoxInWindow" HorizontalAlignment="Left" Height="23" Width="120" /> <my1:cboDerivedComboClass Name="cboDerivedComboInWindow" Height="23" HorizontalAlignment="Left" Width="120" /> </Grid> </Window> A: I've tried and failed to reproduce the problem. I think you have a different problem, though. If you use the xaml above - the number two combobox will completely cover the first - thus you will not be able to get the tooltip... Also, check that all assemblies target the same framework version. A: Isn't this making a circular reference? You call MyDerivedControl that is in another assembly, and DerivedControl needs the primary assembly because it inherits a type you defined there. And then, you try to display it in a window from the primary assembly? Try to clean and rebuild your project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why can I run SSIS Fuzzy Grouping from Visual Studio but not the deployed package? I have written an SSIS package to create a Fuzzy Grouping. I can run it from Visual Studio targeting any of my servers and it will run without any problem. If I try to run the dtsx by remoting to any of those servers, I get the PRODUCTLEVELTOLOW error when the Fuzzy Grouping component executes. I'm running SQL Server 2005 Standard on all servers. I've read that SQL Server 2005 Enterprise is necessary to make use of Fuzzy Grouping and some other components. That fits with the error message, but if this is true why does it work from Visual Studio? Thank you. EDIT: Are there other methods out there to create a fuzzy grouping? Perhaps someone with experience with SSIS components could say whether creating a similar component would be an option? A: As you have correctly identified, Fuzzy Grouping transformation is an Enterprise Edition (or greater) feature. The reason for Enterprise level features being available is that MS exposes the full set of options for the developer edition which is what Visual Studio is basically using. If @Aaron Bertrand chimes in on this thread, I think he has a connect issue requesting that VS allows you to develop against the target edition so people don't get stuck developing Enterprise Edition level solutions for Standard edition feature set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why this operation with date (number of days between 2 dates) return this value? According to this question, I wrote "my code" (without Math.abs, I don't need it) : var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds var firstDate = new Date("2011", "09", "28"); // 28 september 2011 var secondDate = new Date("2011", "09", "30"); // 30 september 2011 var notti = ((secondDate.getTime() - firstDate.getTime()) / (oneDay)); if (notti < 1) notti = 1; else notti = Math.round(notti); alert(notti); and it print 2 (correct). Now, If I do this : var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds var firstDate = new Date("2011", "09", "28"); // 28 september 2011 var secondDate = new Date("2011", "10", "01"); // 01 october 2011 var notti = ((secondDate.getTime() - firstDate.getTime()) / (oneDay)); if (notti < 1) notti = 1; else notti = Math.round(notti); alert(notti); it print 4. Why 4? It should be 3... Do you know about this problem? A: The month argument in the date constructor (and other date methods) runs from [0.11] not [1..12] so: new Date("2011", "09", "28"); // 28 september 2011 is actually Fri Oct 28, not September. A: Javascript months are zero based. So October has 31 days. new Date("2011", "9", "31"); // October 31st A: Because... new Date("2011", "09", "28").toString() ... returns: Fri Oct 28 2011 00:00:00 GMT-0400 (EDT) This is because JavaScript Data is based on the Java Date object, which is a mess. See also "Puizzle 61: The Dating Game" in the book JavaPuzzlers for an explanation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActionBar Tab Selection public class TaskDetailTabHome extends Activity implements ActionBar.TabListener{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tablayout); ActionBar bar = getActionBar(); bar.addTab(bar.newTab().setText("TASK").setTabListener(this)); bar.addTab(bar.newTab().setText("COMMENT").setTabListener(this)); bar.addTab(bar.newTab().setText("FLIGHT").setTabListener(this)); bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); bar.setDisplayShowHomeEnabled(true); bar.setDisplayShowTitleEnabled(false); } @Override public void onTabReselected(Tab arg0, FragmentTransaction arg1) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // Here what I would like to do is ... // if (tabselect is TASK) // Go to Task.class // if (tabselected is COMMENT) // Go to Comment.class } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } } What do I do in onTabSelected method ? Do I need that Fragment ? A: What do I do in onTabSelected method ? Update your UI to reflect the selected tab. This could involve: * *Using the supplied FragmentTransaction to replace a fragment *Replacing the child View of a FrameLayout *Setting the active child of a ViewFlipper *Etc. Do I need that Fragment ? You do not appear to have a fragment. // Here what I would like to do is ... // if (tabselect is TASK) // Go to Task.class // if (tabselected is COMMENT) // Go to Comment.class You do not use tabs to "go to" something. You use buttons, menus, list item clicks, etc. to "go to" another activity. You use tabs to show something. That "something" could be implemented by other classes, if they are Fragments or are ViewGroups.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Averages in Sql Server Management Studio I need to get daily averages for several tags in my data. I am running into a problem with the following query that I have set up: SET NOCOUNT ON DECLARE @StartDate DateTime SET @StartDate = '20100101 00:00:00.000' SET NOCOUNT OFF SELECT TagName, DateTime, avg(Value), avg(vValue) FROM History WHERE TagName IN ('BFC_CGA_PE.qAr_Reading', 'BFC_CGA_PE.qBTU_Avg', 'BFC_CGA_PE.qBTU_Calc', 'BFC_CGA_PE.qCH4_Reading', 'BFC_CGA_PE.qCO_Reading', 'BFC_CGA_PE.qCO2_Reading', 'BFC_CGA_PE.qH2_Reading', 'BFC_CGA_PE.qN2_Reading', 'BFC_CGA_PE.qO2_Reading') AND wwRetrievalMode = 'Cyclic' AND wwVersion = 'Latest' AND DateTime >= @StartDate The error that I receive after my attempt to execute is: Msg 8120, Level 16, State 1, Line 5 Column 'History.TagName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Could someone help to develop a query to fetch daily average values for my tags? A: Try this: (GROUP BY clause added and DateTime column removed from query) SELECT TagName, /*DateTime,*/ avg(Value), avg(vValue) FROM History WHERE TagName IN ('BFC_CGA_PE.qAr_Reading', 'BFC_CGA_PE.qBTU_Avg', 'BFC_CGA_PE.qBTU_Calc', 'BFC_CGA_PE.qCH4_Reading', 'BFC_CGA_PE.qCO_Reading', 'BFC_CGA_PE.qCO2_Reading', 'BFC_CGA_PE.qH2_Reading', 'BFC_CGA_PE.qN2_Reading', 'BFC_CGA_PE.qO2_Reading') AND wwRetrievalMode = 'Cyclic' AND wwVersion = 'Latest' AND DateTime >= @StartDate GROUP BY TagName ORDER BY TagName You just need a group by for TagName. Notice I removed your DateTime column for now. Date time values are likely to be unique and therefore not good candidates for aggregation. Not without some work to isolate a section of the data time value. A: Add a GROUP BY clause. Also assuming the DateTime field is storing a date and time, you will want to aggregate by date alone to get daily average as in query below: SELECT TagName, DATEADD(D, 0, DATEDIFF(D, 0, DateTime)), avg(Value), avg(vValue) FROM History WHERE TagName IN ('BFC_CGA_PE.qAr_Reading', 'BFC_CGA_PE.qBTU_Avg', 'BFC_CGA_PE.qBTU_Calc', 'BFC_CGA_PE.qCH4_Reading', 'BFC_CGA_PE.qCO_Reading', 'BFC_CGA_PE.qCO2_Reading', 'BFC_CGA_PE.qH2_Reading', 'BFC_CGA_PE.qN2_Reading', 'BFC_CGA_PE.qO2_Reading') AND wwRetrievalMode = 'Cyclic' AND wwVersion = 'Latest' AND DateTime >= @StartDate GROUP BY TagName, DATEADD(D, 0, DATEDIFF(D, 0, DateTime))
{ "language": "en", "url": "https://stackoverflow.com/questions/7571983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how can I change the properties of the cfg.xml file? I'm trying to change the properties of the hibernate.cfg.xml file programmatically here's what I did : public class NewHibernateUtil { private final SessionFactory sessionFactory; String host; String database; String username; String password; NewHibernateUtil(String host,String database,String username,String password){ this.host=host; this.database=database; this.username=username; this.password=password; AnnotationConfiguration ac=new AnnotationConfiguration().configure(); ac.setProperty("connection.url", "jdbc:mysql://"+host+"/"+database+""); ac.setProperty("connection.username", username); ac.setProperty("connection.password", password); sessionFactory = ac.buildSessionFactory(); } public SessionFactory getSessionFactory() { return sessionFactory; } } but This doesn't work,it always uses the old properties in the hibernate.cfg.xml file. A: I guess you need to specify full names of the properties when setting them manually: ac.setProperty("hibernate.connection.url", "jdbc:mysql://"+host+"/"+database+""); ac.setProperty("hibernate.connection.username", username); ac.setProperty("hibernate.connection.password", password);
{ "language": "en", "url": "https://stackoverflow.com/questions/7571984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript: XHR not handling multiple async requests Hi I am trying to access one resource multiple times with with different parameters In this case requesting var domains = [ 'host1', 'host2' ]; var requests = new Array(); for ( i in domains ) { requests[i]=new request(domains[i]); } function request(site) { var url = 'get_remote_status.php?host='+site; var queues = {}; http_request = new XMLHttpRequest(); http_request.open("GET", url, true, 'username', 'password'); http_request.onreadystatechange = function () { var done = 4, ok = 200; if (http_request.readyState == done && http_request.status == ok) { queues = JSON.parse(http_request.responseText); var queuesDiv = document.getElementById('queues'); print_queues(queues, queuesDiv, site); } }; http_request.send(null); } However, only one of of the requests is being handled by the code lambda. Chromium reports that both requests have been received and is viewable in the resourced pane. Also if I make the request synchronous then it works fine. However this is not acceptable to the release code as a request may timeout. Thanks A: Define http_request using var. Currently, you're assigning the XHR object to a global variable. Because of this, your script can only handle one XHR at a time. Relevant erroneous code: function request(site) { var url = 'get_remote_status.php?host='+site; var queues = {}; http_request = new XMLHttpRequest(); Proposed change: function request(site) { var url = 'get_remote_status.php?host='+site; var queues = {}; var http_request = new XMLHttpRequest(); //VAR VAR VAR !!! When you omit var before a variable, the variable will be defined in the global (window) scope. If you use var before a variable, the variable is defined within the local scope (in function request, in this case). A: In fact it is possible to run multiple async xhr call but you have to give them an unique id as parameter to be able to store and load them locally in your DOM. For example, you'd like to loop on an array and make a ajax call for each object. It's a little bit tricky but this code works for me. var xhrarray={}; for (var j=0; j<itemsvals.length; j++){ var labelval=itemsvals[j]; // call ajax list if present. if(typeof labelval.mkdajaxlink != 'undefined'){ var divlabelvalue = '<div id="' + labelval.mkdid + '_' + item.mkdcck + '" class="mkditemvalue col-xs-12 ' + labelval.mkdclass + '"><div class="mkdlabel">' + labelval.mkdlabel + ' :</div><div id="'+ j +'_link_'+ labelval.mkdid +'" class="mkdvalue">'+labelval.mkdvalue+'</div></div>'; mkdwrapper.find('#' + item.mkdcck + ' .mkdinstadivbody').append(divlabelvalue); xhrarray['xhr_'+item.mkdcck] = new XMLHttpRequest(); xhrarray['xhr_'+item.mkdcck].uniqueid=''+ j +'_link_'+ labelval.mkdid +''; console.log(xhrarray['xhr_'+item.mkdcck].uniqueid); xhrarray['xhr_'+item.mkdcck].open('POST', labelval.mkdajaxlink); xhrarray['xhr_'+item.mkdcck].send(); console.log('data sent'); xhrarray['xhr_'+item.mkdcck].onreadystatechange=function() { if (this.readyState == 4) { console.log(''+this.uniqueid); document.getElementById(''+this.uniqueid).innerHTML = this.responseText; } }; } } You have to set each xhr object in a global variable object and define a value xhrarray['xhr_'+item.mkdcck].uniqueid to get its unique id and load its result where you want. Hope that will help you in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to select all tags for a post with a given tag in MySQL? Assume I have three tables: posts, tags, and posts_tags. Posts store all the posts in my blog, tags stores all the different tags, and posts_tags stores the relationship between the two. For example, if the post with the id 2 is tagged with a tag with the id 3, posts_tags would store this relationship. I want to construct a query where I can get all the posts tagged with a given id, and the other tags associated with those posts. For example, I want to be able to find all the posts tagged with 'programming' and all other tags associated with that post in one query. Currently, I am using two queries: one to find the posts tagged with a given tag, and one to find all tags for those posts. Is there any way to combine these queries into just one query? A: This query will return all posts that have the tag :search_tag and a second column listing, in a comma-delimited string, all other tags (not including the one you searched for) that apply to that post. If the post has only the tag you request, it will appear in the list but the "additional_tags" column will be NULL). SELECT posts.id, GROUP_CONCAT(post_tags.tag) AS additional_tags FROM posts LEFT OUTER JOIN post_tags ON posts.id = post_tags.post_id WHERE posts.id IN (SELECT post_id FROM post_tags WHERE tag = :search_tag) AND post_tags.tag <> :search_tag GROUP BY posts.id A: Suppose your "programming" id is 1 and u want to get all posts with tag id 1 Select * from posts where tag_id in (select id from tag where id=1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Serialization with control over Attribute and Element without System.Serialization? I need to transform quickly some object into an XML string. If my project would not been in Silverlight, I would simply use the [Serializable] attribute with [XmlElement] and [XmlAttribute]. Unfortunately, this is not available in Silverlight. I can't use DataContract because it does not give the control of if the property need to be attribute or element tag. So, what is my other option? I can do manually the XML using Linq-To-Xml but is there anything else more fast? A: In terms of performance, XmlWriter (fast, non-cached, forward-only) with self-implemented serialization is preferable. A: Another option is to use System.Xml.Serialization.XmlSerializer .
{ "language": "en", "url": "https://stackoverflow.com/questions/7571990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Side bar height not expanding with floated content I have a parent div with two child divs. One of the divs is a sidebar, the other, content area. I am trying to get the sidebar to extend all the way down when the content area is longer than the sidebar. Any idea how to do this ? Here's a fiddle illustrating the problem. A: You can do it with a technique called faux columns. The idea is that you apply a background to #main-content. Since your columns are both floated you also need a clearing element at the end of #main-content to make it expand to the full height of both columns. HTML: <div id="main-content"> <div id="side-bar"></div> <div id="content-right"></div> <div class="clear"></div> </div> CSS: #main-content { background-color: #eee; } #content-right { background-color: #fff; } .clear { clear: both; } The above causes it to look like your #side-bar is the full height of the content column. Here's your fiddle updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Mail: Sending ÅÄÖ characters? I'm trying to send a mail containing ÅÄÖ characters (Swedish). I've tried changing the mail header to UTF-8 and iso-8859-1, none of which works. I've also tried wrapping the text in utf8_encode() as well as mb_encode_mimeheader(), with no success. In some cases i get chinese characters instead, not really what i want. I just tried using htmlentities() with no result. $values = array( 'name' => $this->input->post('name'), 'email' => $this->input->post('email'), 'ref' => $this->input->post('ref'), 'sex' => $this->input->post('sex'), 'age' => $this->input->post('age'), 'question' => $this->input->post('msg'), 'ip' => $_SERVER['REMOTE_ADDR'] ); $to = '@live.se'; $subject = $values['name'] . ' har skickat en fråga!'; $message = 'Namn:'.$values['name']." \r\n"; $message .= "\r\nEmail:".$values['email']." \r\n"; $message .= "\r\nKön:".(($values['sex'] == 'f') ? 'Kvinna' : 'Man')." \r\n"; $message .= "\r\nÅlder:".$values['age']." \r\n"; $message .= "\r\nReferensnummer:".$values['ref']." \r\n"; $message .= "\r\nMeddelande: \r\n".$values['question']; $headers = 'From: noreply@.se' . "\r\n" . 'Content-type: text/html; charset=iso-8859-1' . "\r\n" . 'Reply-To: ' .$this->input->post('email') . "\r\n" . 'X-Mailer: PHP/' . phpversion(); $message = htmlentities($message); if(@mail($to, $subject, $message, $headers)) { if($this->input->is_ajax_request()) { echo 1; }else { $data['message']['header'] = 'Tack så mycket!'; $data['message']['content'] = 'Din fråga skickades utan problem! Jag återkommer snarast möjligt.'; echo $this->load->view('includes/header', array(), true); echo $this->load->view('message', $data['message'], true); echo $this->load->view('includes/footer', array(), true); } }else { $fail = true; } A: I don't know if this is the best way to achieve this. But I used to use mail like this: mail($to, "=?utf-8?B?".base64_encode($subject)."?=", $message, $headers); A: While trying to figure this out, i remembered i was using Codeigniter, and thought maybe, just maybe, codeigniter had a built in Email library. And, it turns out it does! So i gave it a shot, and found out it had a serious bug in it. Luckily, i found a fixed version of the file here: http://codeigniter.com/forums/viewthread/87108/P15/#753867 And now it works. I don't know exactly what codeigniter does to make it work, but i'm glad it does! tl;dr: i don't have a real solution to the problem. A: A very old thread, but did not seem to have a good answer. If the encoding of the page which contains the form is encoded as utf-8, then the function utf8_decode("your åäö-text"); is your friend. A: This. $message = preg_replace('/[^(\x20-\x7F)]*/','', $message);
{ "language": "en", "url": "https://stackoverflow.com/questions/7571994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does the Square app have a custom URL scheme? In my iOS app, as part of the mobile payments options, I'd like to direct users who have the Square app installed on their device to use this as a payment option. Is there a custom URL scheme that Square uses that would allow me to launch their app from within mine? A: Yes, the Square app does have a custom URL schema you can call: square:// You can also see if the application is installed by the following method: - (BOOL)isSquareInstalled { return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"square://"]]; } A: The Square Pay app uses the URL Scheme square-pay://
{ "language": "en", "url": "https://stackoverflow.com/questions/7571997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to create generic enum? I'm trying to define generic enum, but have problems with it: private enum Stick<T>{ A, B, C; private Stack<T> disks = new Stack(); public void print(){ System.out.println(this.name() + ": " + disks); } public T pop(){ return disks.pop(); } public void push(T element){ disks.push(element); } }; Is it possible at all? A: Enums are constants. So Stack disks can not be "stack of whatever type the client of the enum wants". It has to be of fixed type. The point of having fields in an enum is to be able to hold additional information about each element. For example, in the case of a stack, this could be A("a", "b"), B("b", "c", "d") - each element specify what items are loaded in its stack (the example requires a varargs constructor). But their type is strictly specified, it cannot be <T>. The error that the eclipse compiler shows is clear: Syntax error, enum declaration cannot have type parameters However, you can do something like that: enum Foo { A("foo", "bar"), B(0, 1, 2); private Stack<?> stack; private <T> Foo(T... args) { stack = new Stack<T>(); stack.addAll(Arrays.asList(args)); } public <T> Stack<T> getStack() { return (Stack<T>) stack; } } And then: Stack<String> stack1 = Foo.A.getStack(); Stack<Integer> stack2 = Foo.B.getStack(); System.out.println(stack1); System.out.println(stack2); Results in: [foo, bar] [0, 1, 2] Update: Since your comment about your goal - the hanoi towers should not be enums, because their values are changing. Instead, you should use the enums as keys to a Map, where the values are the stacks. I admit that it looks tempting to use a field of the enum to do that, but it is not a good practice. Enums better be constant. Of course, you can use my example above to achieve your initial goal, but I'd recommend a Map. A: No, but Enums can implement interfaces. May be that helps you. A: This could help. Basically, you need this: public interface Stick<E extends Enum<E>> A: There is a draft for generic enums here: http://openjdk.java.net/jeps/301 Hope it makes it into Java 10!
{ "language": "en", "url": "https://stackoverflow.com/questions/7572001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: android ImageView hyperlink coords I want to implement a functionality in which when particular area of an image set in an ImageView will result in calling an intent. Similar to HTML coords hyperlinks <img src ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap" /> <map name="planetmap"> <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" /> <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury" /> <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus" /> </map> I want to implement this even in an zoomed image. Heres what I have search and found leads on: I will have to use an SurfaceView with appropriate logic in onTouch(); Similar functionality is there on mapViews get projection method. similar to that but should be to a bitmap loaded. A: Another possible approach is create yourself a view that uses a transparent 9 patch as its background. Set it to whatever size and position you need and call your intent from its onClickListener(). This is achieve the same effect from the users perspective. Edit: If you want multiple active at the same time you'd have to use multiple transparent views. If you only want 1 active at a time you could reuse the same one and just change the size / position of it. Since using this approach will create extra views you are going to take a slight performance hit. If you are looking to maximize preformance doing something like you've mentioned above where you attach an OnTouchListener and have your logic inside the onTouch callback. You could creat Rect objects to represent your touch areas and call Rect.intersect() to see if the touch event position intersects one of your rect areas. This would likely give you better overall performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting DataContext within UserControl is affecting bindings in parent I have a basic UserControl that sets its DataContext to itself for ease of binding: <UserControl x:Class="MyControlLib.ChildControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" DataContext="{Binding RelativeSource={RelativeSource Self}}"> </UserControl> This is used in a parent XAML file like this: <UserControl x:Class="MyControlLib.ParentControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ctrl="clr-namespace:MyControlLib"> <ctrl:ChildControl x:Name="ChildName" PropertyOnChild="{Binding PropertyInParentContext}"/> </UserControl> For some reason, this gives a binding error that seems to indicate that the DataContext of the parent control is getting affected by the child control setting its own DataContext. System.Windows.Data Error: 40 : BindingExpression path error: 'PropertyInParentContext' property not found on 'object' ''ChildControl' (Name='ChildName')'. BindingExpression:Path=PropertyInParentContext; DataItem='ChildControl' (Name='ChildName'); target element is 'ChildControl' (Name='ChildName'); target property is 'PropertyOnChild' (type 'whatever') Why is "PropertyInParentContext" being looking for in the child control rather than in the parent's DataContext? If I remove the DataContext="{Binding RelativeSource={RelativeSource Self}} from the child control, then things operate how I would expect. Am I missing something obvious here? A: Self means the UserControl, so when you set the DataContext to Self, you are setting the DataContext to the UserControl object. The correct syntax for binding to a Control's DataContext would be {Binding RelativeSource={RelativeSource Self}, Path=DataContext}, however since the DataContext is inherited by the Parent, this binding is totally unncessary in any situation. Also, if you bind your DataContext to Self.DataContext, you would essentially be creating a loop where a value is bound to itself. A: The declaration of your control and the instantiation are basically manipulating the same object, all the properties that are set in the declaration are also set on every instance. So if the properties were "visible" so to speak: <UserControl x:Class="MyControlLib.ParentControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ctrl="clr-namespace:MyControlLib"> <ctrl:ChildControl x:Name="ChildName" DataContext="{Binding RelativeSource={RelativeSource Self}}" PropertyOnChild="{Binding PropertyInParentContext}"/> </UserControl> This is why you do not set the DataContext of UserControls, it will override the inherited DataContext (and even obfuscate the fact that there is a different context). If you want to bind to properties of the UserControl in its declaration then name the control and use ElementName or RelativeSource-bindings instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: LINQ Select distinct from a List? I have the following list: class Person { public String Name { get; set; } public String LastName { get; set; } public String City { get; set; } public Person(String name, String lastName, String city) { Name = name; LastName = lastName; City = city; } } ... personList.Add(new Person("a", "b", "1")); personList.Add(new Person("c", "d", "1")); personList.Add(new Person("e", "f", "2")); personList.Add(new Person("g", "h", "1")); personList.Add(new Person("i", "j", "2")); personList.Add(new Person("k", "l", "1")); How do I retrieve a list of persons differing from the city name? Expecting Results: An Array/Collection of lists (persons) differing from the city name: result[0] = List<Person> where city name = "1" result[1] = List<Person> where city name = "2" result[n] = List<Person> where city name = "whatever" A: You could use LINQ to group the persons list by city: var groupedPersons = personList.GroupBy(x => x.City); foreach (var g in groupedPersons) { string city = g.Key; Console.WriteLine(city); foreach (var person in g) { Console.WriteLine("{0} {1}", person.Name, person.LastName); } } A: In addition to Darin Dimitrov's answer, here is the same in query syntax: var groupByCityQuery = from person in personList group person by person.City into grouping select grouping; A: Judging by this comment: No, I wan't a list containing all the Persons that contains 1 as a city and another that contains 2 as a city... We can do something like this: var city1People = personList.Where(x => x.city == "1").ToList(); var city2People = personList.Where(x => x.city == "2").ToList(); if this is something more dynamic, like you're going to have N cities and want an individual list of people per city, you're going to need to return a collection of lists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: JAR-Level (Assembly-Level) Class Scoping in Java In C#, if I want a class to be visible to any class within that assembly (DLL), I simply scope it as internal (which is the default). How can I do this in Java? In Java, I've noticed the default/internal scoping is package level, not JAR level. This is a problem for me, since I have a library that has several sub-packages with different responsibilities (view, controller, etc.) and can't put them in the same package. As an example, I have two classes like com.stackoverflow.main.first.One and com.stackoverflow.main.second.Two, both of which should be able to instantiate each other. Edit: I don't want the class to be public and visible from anyone who references it. It's an internal class only. I'm creating an API for consumption, and of primary importance to me is which classes can be seen by consumers of my JAR. A: Java has no concept of library-level scoping. Make the classes public or use a factory. A: To accomplish what you want, you'll have to use some mix of a factory pattern to create the classes you want to expose and leave the private classes package private. Usually, I've done this: * *create the public interface for the API in a package like com.foo.bar a la public interface Foo {} *create a factory class that exposes a create method a la: public class FooFactory{ public Foo buildFoo(){ return new FooImpl(); } *create FooImpl as a package private class - class FooImpl implements Foo{} *Document package to indicate proper usage. It's not perfect, but until the JSR about module scoping progresses, it's probably the closest you can get in java. If you want to ensure that FooImpl doesn't get inappropriately extended, be sure it is marked final. A: sounds as simple as you have to use the public access modifier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: IE9: Validation message not getting cleared I am using an upload control which accepts only image files.If I select any non-image files I will be showing a validation error message "File type is invalid". The upload control i use is as follows <UC:UploadControl runat="server" ID="file_logo" IsRequired="false" ReqValidationGroup="jpg" onkeypress="Javascript:CheckNumeric(event);" RequiredFieldMessage="Please upload Image file" CheckFileType="true" Width="870" Height="100" CheckDimension="false" RegexpFieldMessage="File type is invalid." FileFormats="gif,GIF,jpg,JPG,jpeg,JPEG" RegDisplay="true" /> I use another link to clear the error validation message. The code is <a href='javascript:chkFileTypes("ctl00_mainContentPlaceHolder_file_logo_uploadfiles");clearInvalidLabel("ctl00_mainContentPlaceHolder_file_logo_uploadfiles")' >Clear File</a><br /> My Javascript function used to clear validation message is function clearInvalidLabel(control) { if (control == "ctl00_mainContentPlaceHolder_file_logo_uploadfiles") $("span[id$='file_logo_regexpType']").hide(); if (control == "ctl00_mainContentPlaceHolder_PopUp_logo_uploadfiles") $("span[id$='PopUp_logo_regexpType']").hide();} Now if I again select an improper file using UploadControl, the error validation message is not getting displayed(Only in IE9). It works perfectly in other browsers. Please help me out. Thanks. A: Hard-coding IDs is easy to break. Try using the ClientID to access the control in JavaScript. <a href='javascript:chkFileTypes("<%=UploadFilesControl.ClientID%>");clearInvalidLabel("<%=UploadFilesControl.ClientID%>")'>Clear File</a> I would use the ClientID to get the validation labels too: $("#<%=regexpType.ClientID%>").hide();
{ "language": "en", "url": "https://stackoverflow.com/questions/7572012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JS: external loading I have lot of pages in different domains that need to include some .js .css and html. I want to "remotely" update the included code. So in those static pages I tought placing: <script src="http://centraldomain.com/include.js" type="text/javascript"></script> then in that file do: document.write('<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script><div id="results"></div>'); $('#result').load('http://domain.com/include-rest.html'); and in that html place all the html I want to insert in those pages, eg: <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/cupertino/jquery-ui.css" type="text/css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> some html without <head> or <body> Is this the best approach to take? Is there any cross domain or XSS attack security issue I'm not taking into account? Thanks A: Instead of managing your code loading using external resources, you can instead import a single file an use a resource loader to manage dependancies. Rather than having external scripts execute code (tripping same origin policies), you can manage everything in one place and side-step any cross domain issues. yepnope.js is an asynchronous resource that would help. You can use test for whatever site your on, import files necessary, then test what site your on to determine if you need to execute any further code. Take a look at http://yepnopejs.com/ -- here's a quick look. yepnope([{ test : /* boolean(ish) - Something truthy that you want to test */, yep : /* array (of strings) | string - The things to load if test is true */, nope : /* array (of strings) | string - The things to load if test is false */, both : /* array (of strings) | string - Load everytime (sugar) */, load : /* array (of strings) | string - Load everytime (sugar) */, callback : /* function ( testResult, key ) | object { key : fn } */, complete : /* function */ }, ... ]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7572022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to have a "Time" Schema in Mongoose? I know I can do Date. but what about Time? A: Are you just trying to get created at/updated at timestamps? If so you can use mongoose-types to add that as a plugin. Or you could use a mixed type I suppose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extend SoapException I am stuck trying to extend SoapException in order to add two additional string attributes. I have a Web-Service method that should throw CustomSoapException derived from SoapException and I want to catch that CustomSoapException in web service client. But when I try to expose CustomSoapException to web service client by adding [XmlInclude(typeof(CustomSoapException))] property to my WebMethod, my ASMX web service fails upon start-up with the message: Cannot serialize member System.Exception.Data of type System.Collections.IDictionary, because it implements IDictionary. If someone can show me how to properly serialize Data property of IDictionary type inside of my CustomSoapException so it can be correctly exposed to web service client. I don't even intend to put any data inside Data property. Maybe it can be somehow removed completely from extended class altogether to avoid the need to serialize it. Here's my code for CustomSoapException: [Serializable] public class CustomSoapException : SoapException, ISerializable { private string customExceptionType; private string developerMessage; private string userMessage; public override System.Collections.IDictionary Data { get { return base.Data; } } public CustomSoapException(): base() { } public string GetDeveloperMessage() { return developerMessage; } public string GetCustomExType() { return customExceptionType; } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } public CustomSoapException(SerializationInfo info, StreamingContext context) : base(info, context) { } public CustomSoapException(string usrMessage, string devMessage, string customExType) : base(usrMessage, SoapException.ServerFaultCode) { customExceptionType = customExType; developerMessage = devMessage; userMessage = usrMessage; } } Here's my WebMethod code inside of asmx.cs file: [WebMethod(EnableSession = true)] [XmlInclude(typeof(CustomSoapException))] public void testCustomExceptionPassing() { throw new CustomSoapException("user message", "developer message","customException"); } Web service client code: try { Srv.testCustomExceptionPassing(); } catch (SoapException ex) { string devMessage = (ex as Srv.CustomSoapException).GetDeveloperMessage(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WPF resizing, * vs Auto I have a XAML with 2 columns in a Grid and I have a button that when I click it, in the code behind, I set the visibility to collapse, and want to resize the other half of the screen to try to take up the whole screen. The collapsing part works, and the RHS then shifts over to the LHS, but it does not take up the entire screen. I tried using both the Auto and Star to resize in HidePlots, but it never takes the full screen. I thought if I collapsed the LHS, and set the column to * for the RHS, it would take up the whole screen. Any thoughts? Thanks. Here's some code to make it more clear: <Grid Grid.Row="1" x:Name="ExpandableGrid"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"></ColumnDefinition> <ColumnDefinition Width="1.5*"></ColumnDefinition> </Grid.ColumnDefinitions> <Grid Grid.Column="0" x:Name="TableGrid"> <Grid.RowDefinitions> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <GroupBox Grid.Row="0" Grid.Column="0" x:Name="SampleViewGroupBox" Header="SampleView" HorizontalAlignment="Stretch" FontFamily="Arial" FontSize="12" Margin="5,0,5,0" > <ContentControl Content="{Binding LayoutManager.SampleView}" Height="Auto" Width="Auto"/> </GroupBox> <Button x:Name="TableButton" HorizontalAlignment="Right" Content="Button" Width="15" Height="15" VerticalAlignment="Top" Margin="0,0,-2,0" Click="MaxButton_Click" Grid.Column="0" Grid.Row="0"/> </Grid> <Grid Grid.Column="1" x:Name="BaseViewGrid"> <Grid.RowDefinitions> <RowDefinition Height="*"></RowDefinition> </Grid.RowDefinitions> <GroupBox Grid.RowSpan="2" Grid.Column="1" Name="BaseViewGroupBox" Header="PLOTS" Margin="5,0,5,0" > <ContentControl Content="{Binding LayoutManager.ConsensusView}" Height="Auto" Width="Auto" /> </GroupBox> </Grid> </Grid> private void MaxButton_Click(object sender, RoutedEventArgs e) { UIElement senderElement = (UIElement)sender; if (_tableMinimized) { HideTables(false); _tableMinimized = false; ((Button)senderElement).Style = (Style)FindResource("DashboardDetailsButton"); } else { HideTables(true); _tableMinimized = true; ((Button)senderElement).Style = (Style)FindResource("DashboardDetailsButtonReverse"); } } private void HideTables(bool hide) { if (hide) { foreach (UIElement child in TableGrid.Children) child.Visibility = Visibility.Collapsed; for (int i = 0; i < ExpandableGrid.ColumnDefinitions.Count; i++) ExpandableGrid.ColumnDefinitions[i].Width = GridLength.Auto; ExpandableGrid.ColumnDefinitions[1].MinWidth = 500; for (int i = 0; i < ExpandableGrid.RowDefinitions.Count; i++) ExpandableGrid.RowDefinitions[i].Height = GridLength.Auto; TableButton.Visibility = Visibility.Visible; } else { foreach (UIElement child in TableGrid.Children) child.Visibility = Visibility.Visible; for (int i = 0; i < ExpandableGrid.ColumnDefinitions.Count; i++) ExpandableGrid.ColumnDefinitions[i].Width = new GridLength(1, GridUnitType.Star); for (int i = 0; i < ExpandableGrid.RowDefinitions.Count; i++) ExpandableGrid.RowDefinitions[i].Height = new GridLength(1, GridUnitType.Star); } } Edit: I tried to also change one line to: ExpandableGrid.ColumnDefinitions[1].MinWidth = System.Windows.SystemParameters.PrimaryScreenWidth-20; instead of the hard-coded 500 value, it looks correct. However, if I try to click the button again to revert back to normal, the RHS takes up the bulk of the screen without getting back to its original position. A: Your current column definition says to make Column B equal to 1.5 times the size of Column A, so even if ColumnB's content is hidden, the column will still take up 3/5 of the screen. Change it so the column that collapses has a Width="Auto", and set it's Content's Width equal to whatever size it should be when it's expanded. If you want to keep the 1.5* default width, I'd recommend using something like a MathConverter to figure out what size it should be based on the parent Grid's width. I have the code for one posted here <Grid x:Name="ParentGrid"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"></ColumnDefinition> <ColumnDefinition Width="Auto"></ColumnDefinition> </Grid.ColumnDefinitions> <Grid x:Name="RHS" Grid.Column="0" /> <!-- Collapse this Grid --> <Grid x:Name="LHS" Grid.Column="1" Width="{Binding ElementName=ParentGrid, Path=ActualWidth, Converter={StaticResource MathConverter}, ConverterParameter=((@VALUE/5)*3)}" /> </Grid> A: You need to set column 0 to be whatever you desire (Auto, 150, etc...) and set column 1 to be *. It looks like your Grid is also within a Grid, so the parent's behavior also has to be taken into account.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# | DataGridView set column type programmatically I am building a program that loads an xml to a datagridview, But I need to add 2 more columns one with buttons and one with images. How can I add them here: ? DataSet data = new DataSet(); string p = System.IO.Path.Combine(Application.StartupPath, "payday.xml"); data.ReadXml(p); this.dataGrid.DataSource = data; this.dataGrid.DataMember = "costumer"; int i = 0; foreach (DataGridViewColumn column in this.dataGrid.Columns) { if (column.Name == "Name" || column.Name == "Status" || column.Name == "URL" || column.Name == "type" || column.Name == "Last-Checked-Pay") { column.Visible = true; column.Width = (int)(dataGrid.Width * .2) + (column.Name.Length / 2); } else { //I tried to do it here: //dataGrid.Columns[i+1].CellType = new DataGridViewButtonColumn(); //dataGrid.Columns[i+1].HeaderCell. } i++; } A: This will help with adding to the column collection (although you can shorthand the add by implicitly adding to the collection using Add on the DataGridView). As far as adding data goes, you will likely want to add using the row binding event so you can populate those columns. The other option is add the information needed to the dataset and then bind the newly added columns (fields). The first option dinks with the DataGridView programatically, while the second allows you to add a declarative set up for the DataGridView and massages the data that is bound. Which to choose? If the DataGridView always has these fields, I would massage the data. If the added columns only appear some of the time, I would alter the DataGridView programmatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Session control Various controllers at the same page in Symfony 2? i'm trying to control the session to forbid the access to some pages of my web app. The way is simple, a boolean session variable. The thing is there's one page for every action, but, i think is not elegant at all to ask in every action if the user is logged or not. How can i do this elegantly in a MVC architecture? It looks crappy this way. I was thinking that there is a parent action that redirects to the final one, the one that renders the page, is it right? maybe i could make the check there. public function createAction(Request $request){ $sess = $this->getRequest()->getSession(); if ($sess->get('logged') == true) { // ---- ACTION CODE GOES HERE ---- // } } A: In Symfony2, if the sections of the site that need authorization are under the same path, you can use the access_control section in the security configuration: # app/config/security.yml security: # ... access_control: - { path: ^/secured/area, roles: ROLE_USER } You can find more ways to secure your app in the book
{ "language": "en", "url": "https://stackoverflow.com/questions/7572039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to 'flush' UI Thread actions before continue execution I've got a problem in Android with runOnUiThread. I start an AsyncTask (inside an Activity) that waits for a while, and after calls the method showDialog(id). After this call, it sleeps for another while, and finishes calling the method dismissDialog(id). This is the code: public class MyActivity extends Activity { ... protected class StartWaiting extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... arg0) { try { Thread.sleep(2500); } catch (InterruptedException e) { e.printStackTrace(); } // Show dialog runOnUiThread(new Runnable() { @Override public void run() { showDialog(PROGRESS_DIALOG_LOADING); } }); try { Thread.sleep(2500); } catch (InterruptedException e) { e.printStackTrace(); } // Dismiss dialog runOnUiThread(new Runnable() { @Override public void run() { dismissDialog(PROGRESS_DIALOG_LOADING); } }); return null; } @Override protected void onPostExecute(Void arg) { new StartServices().execute(); } } } Unfortunately, the behaviour is different from what I want to do: showDialog() and dismissDialog() are called one immediately after the other. I think that the reason why this happens is that the UI Thread execute both actions "when it can", that is at the end of sleeping actions. Well, does it exist some "flushUI()" method that force a thread (in this case, the UI Thread) to execute every action before continue? A: You could just add a synchronization point in your thread, using a CountDownLatch for instance: final CountDownLatch latch = new CountDownLatch(1); view.post(new Runnable() { public void run() { try { // Do stuff on the UI thread } finally { latch.countDown(); } } }); try { if (!latch.await(CAPTURE_TIMEOUT, TimeUnit.MILLISECONDS)) { return; } } catch (InterruptedException e) { // Handle exception }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }