text
stringlengths
8
267k
meta
dict
Q: Android Library integration to Eclipse Alright, this is probably a pretty dumb question but I'm not sure how to go about doing it. I am trying to integrate the Android Billing Library from Github https://github.com/robotmedia/AndroidBillingLibrary The only instructions in the readme are: Add this library to your project. I have only ever integrated .jar files. This comes as a zip and when unzipped has a bunch of folders and classes located inside it. How do I "Add this library" to my project? A: It looks like download package available from your GitHub link contains the source code of several projects from Eclipse/ADT workspace. So, you can unzip the package and then just import those projects into your Eclipse workspace. After that you can add AndroidBillingLibrary project as dependency from your project properties / Java Build Path configuration panel.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Partial xml response from web service via ksoap2 I'm new in both Android and Java (use to develop in C# before) and I'm quite desperate on this. I'm using ksoap2 to contact a .NET Web Service to get xml data. My code is simple and it works well if the xml is small: soapEnvelope.setOutputSoapObject(request); SoapPrimitive response = (SoapPrimitive) soapEnvelope.getResponse(); String xmlResponse = response.toString(); this is a simple way to get the response, which is a simple xml string. But when the xml is large, it gets truncate, and I suppose it is because the response is kept in memory. I read some other people having this problem, but I didn't find a solution that really helps me; probably I miss the necessary knowledge to manage the question, and this is confirmed by the fact that navigating the variables on Eclipse I found that the data is fully there, I only did't know how to reach it... can somebody help me? how can i get the missing part of the response? I need to save the response locally? Need to cycle an InputStream? help, please... A: In debugger windows Eclipse will not show all the array elements. If you are able to see them all when you expand the array then they are all there for your program to use. If you are suspecting large response, SAX is the right way to parse it EDIT: As Manfred explains in this answer, response.toString() is a bad idea because KSoap has already done the parsing. A: You should use the getResponse method of the envelope and parse the SoapObject tree for whatever you need. Using bodyIn and parsing that with SAX adds a second parsing.. if you do that you might as well not use ksoap2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS App crashes on phone, works flawlessly in iPhone simulator What is the best way to debug that? It just "crashes" on the phone, no message, nothing. Simulator is doing just fine. Happens on only one of the UIViewController's, not sure why... A: I suggest you to add NSZombieEnabled and set it to YES in your enviornment, you can set this in Project->Edit active executable->(go to Agruments tab) and add to Variables to be set in enviornment, so you can see(if you are lucky) where is the problem. Remember to remove it before the upload of your app on the store. You could also download this app from the store. A: Attach the debugger when running on the device, see if it is produced that case. Otherwise, check the device logs in the organizer. Logs are left on the device when the app crashes. They can be symbolicated to find out this information. A: Have you gone out of your way to completely clean out prior installations of your app when installing the new version? Inconsistencies between remnants of the old version installed on the real device and the new install can lead to this situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pdf security with flash script, possible? My friend asked whether it's possible to set time limits on pdf files, so a pdf can't be opened after a date. I searched and found some software that can make this but they cost $$$$. As far as i know swf can be embedded into pdf.(i am .net programmer so i am not a flash, pdf expert) I wonder if this can be done: Create an actionscript(and embed it into a pdf), which kills acrobat reader when opening the pdf after a date. Also any other ideas are welcome. Thanks for reading and your help. A: Such security is worthless as it's removed and bypassed easily. Just change time on your computer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# shift operator overload is there a reason for the type of the second operand must be int? ... // I would like to do this public static StringList operator<<(StringList list, string s) { list.Add(s); return list; } // but only int is supported... ... EDIT: Just for sure... I can overload operator* for get (for example) List of string class MyString { string val; public MyString(string s) { val = s; } public static List<string> operator*(MyString s, int count) { List<string> list = new List<string>(); while (count-- > 0) { list.Add(s.val); } return list; } } ... foreach (var s in new MyString("value") * 3) { s.print(); // object extension (Console.WriteLine) } // output: // value // value // value ... but cannot overload left shift, well known from C++ std (overloaded for output), because it was unclear? Of course, it's just a decision of C# designers. Still it can be overloaded on something unexpected/unclear (with int). Really the reason is that it was made an unclear code? A: Yes. It's because the language specification requires it: When declaring an overloaded shift operator, the type of the first operand must always be the class or struct containing the operator declaration, and the type of the second operand must always be int. The language designers didn't have to make that decision - it would have been possible for them to remove that restriction if the wanted to - but I think this part of the specification explains their reasoning for this (and other) restrictions on operator overloading: While it is possible for a user-defined operator to perform any computation it pleases, implementations that produce results other than those that are intuitively expected are strongly discouraged. They probably wanted the bitshift operators to always behave like bitshift operators, and not as something completely surprising. A: Because you want your code to look like c++? Why not an extension method .Append( item ) that returns the source list. public static class ListExtensions { public static List<T> Append<T>( this List<T> source, T item ) { if (source == null) { throw new NullArgumentException( "source" ); } source.Add(item); return source; } } Used as: var list = new List<string>(); list.Append( "foo" ) .Append( "bar" ) .Append( "baz" );
{ "language": "en", "url": "https://stackoverflow.com/questions/7586887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Theme Dialog Layout and XML Strings I have a layout, main.xml. When you click the button describeButton, it opens a new theme.dialog layout called checklist.xml. On checklist.xml, users are given a series of check boxes they can use to describe a picture. After they check as many check boxes as they please, they can click the okButton to go back to the main.xml layout. So here are my questions: * *How do I take the check boxes that users selected, turn the selections into a string, and store it as a string in the strings.xml file? *How do I code the okButton on checklist.xml to close the layout, which in turn will return the users to main.xml? Thank you for your help. Edit Here's the code I'm using at the moment: public class Descriptor extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.checklist); final CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1); Button selOK = (Button) findViewById(R.id.selectOK); selOK.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (checkBox1.isChecked()) { // add a string to an existing string in strings.xml } // repeat this if statement for all checkboxes // execute something to close this layout } }); } } A: Are you talking about res/values/strings.xml? After you compile an APK you cannot change the XML files. During compilation the XML files are used to generate an R.java file which is a java implementation of your XML files. These files are actual java source that you can't change or alter. One way to achieve what I think you are trying to do is to attach a listener to the checkboxes and then keep track of when a user checks or un-checks a box. Here is an example of a dialog with radio buttons from the Android Docs for Dialogs. It should be pretty simple to convert to checkboxes by using builder.setMultiChoiceItems instead of builder.setSingleChoiceItems. In fact here is a link to the multiChoiceItems method doc. final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create(); With regards to your second question, your OkButton can just close the dialog. In your main activity can setup an array of booleans with one boolean for every string you are going to display. Then in your the onClick method can change the individual boolean values based upon which checkboxes are checked. Then when the dialog closes you can examine the array of booleans to see what checkboxes the users checked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: anchors are not working in mootools Sortables I have created a table using mootools sortables to implement drag and drop functionality. Inside my table some of the columns has hyperlink and textboxes.When I click on hyperlink/input box it always calls Sortable's callback like onComplete. How do I make hyperlink/input Elements working inside Sortable.I have tried to use handle property of Sortable but problem with this property is that it takes only one element.If I have to use multiple columns of of row as handle then what I need to do ?Do I have any hope ? Thanks in advance. A: It's not true you can only use one element as a handle. You can specify a handle by using CSS selectors in the handle option. This then refers relative to the 'sortable' (the element to be sorted). So suppose within your sortable item (like an <li> html element) your handle is a <span> with the class my-handle, you could do: var mySortables = new Sortables('#list-1', { handle: '.my-handle' }); I think it's neater to solve it like that, instead of stopping event propagation of events you didn't want in the first place. A: I was able to solve the problem by adding following code in domready to prevent event bubbling. document.getElements("a").addEvents({ click: function(e) { if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7586892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use the data in the selected rows in GridView and show that list on another page? I am writing a web site in Visual Studio, something like an on-line library. I have a GridView on the first page that presents all of the books available from the data source and some other properties also contained in the data source. The GridView contains check boxes and the user can choose which books he wants to order by checking a box. My question is how can I use the data in the selected rows, the list of books with their properties and show that list on another page, so that the user is able to know which items he has selected? I tried with a for loop on the FirstPage: for (int i = 0; i < GridView1.Rows.Count; i++) { int bookID = (int)GridView1.DataKeys[i][0]; CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox"); if (cb.Checked) { purchaseProductList.Add(bookID); Response.Redirect("SecondPage.aspx?bookID" + i + "=" + bookID); } } and then on the SecondPage: for (int i = 0; i < 10; i++) { if (Request.QueryString["bookID" + i] != null) { DataRow row; row = dtBooks.NewRow(); row["ID"] = Request.QueryString["bookID" + i]; dtBooks.Rows.Add(row); } } GridView1.DataSource = dtBooks; GridView1.DataBind(); but it didn't work. Any help? Thank you in advance. A: you can use session to keep selected ids List<string> ids = new List<string>(); for (int i = 0; i < GridView1.Rows.Count; i++) { int bookID = (int)GridView1.DataKeys[i][0]; CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox"); if (cb.Checked) { purchaseProductList.Add(bookID); ids.Add(bookID); } } Session["Ids"] = ids; Response.Redirect("SecondPage.aspx"); from second page you can access session and load those ids to grid var list = (List<string>)Session["Ids"]; foreach (string id in list) { DataRow row; row = dtBooks.NewRow(); row["ID"] = Request.QueryString["bookID" + id]; dtBooks.Rows.Add(row); } GridView1.DataSource = dtBooks; GridView1.DataBind();
{ "language": "en", "url": "https://stackoverflow.com/questions/7586894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create DOM element with jQuery I have a function $(document).ready(function () { $("#btnhighlight").click(function () { var htext = $("#txthighlighttext").val(); $("#lstCodelist option").each(function () { var sp = $(this).text(); var sp1 = sp.split(' '); $.each(sp1, function (i, l) { if (l == htext) { var boldText = "<div style=\"background-color: yellow; display: inline; font-weight: bold;\">" + htext + "</div>"; $(document).append(boldText); } }); }); }); }); I updated the code but no luck. Here in this code I need to create a l has a DOM element to apply color yellow to that. please can any body help me out how to create a dom element. Thanks A: I didn't understand where does l is in your current code. Anyway, you can create a DOM element with jQuery like this: var myel = $('<div class="someclass"></div>'). Then you can append myel to wherever you want in the DOM using function like .appendTo(), .after(), etc. EDIT You seem to be trying to highlight some words inside an <option> element. I have doubts if that is going to work on all browsers, since form elements are a little tricky when it comes to CSS. You can try something like this (untested): $(document).ready(function () { $("#btnhighlight").click(function () { var htext = $("#txthighlighttext").val(); $("#lstCodelist option").each(function () { var sp = $(this).text(); var re = new RegExp("\\b" + htext + "\\b") sp = sp.replace(re, '<span class="highlighted">$1</span>', "gi"); $(this).html(sp); }); }); }); You also need some CSS on your page, defining the style for .highlighted UPDATE AFTER CHAT I got something working using a <p> instead of <option>, to rule out the problem of form element styling: http://jsfiddle.net/GTydh/3/ The updated js (in case fiddle is deleted): $(document).ready(function () { $("#btnhighlight").click(function () { var htext = $("#txthighlighttext").val(); //$("#lstCodelist option").each(function () { $("p").each(function () { var sp = $(this).text(); var re = new RegExp("\\b(" + htext + ")\\b") var sOpen = "<span class='highlight'>"; var sClose = "</span>"; var newhtml = sp.replace(re, sOpen + "$1" + sClose, "gi"); $(this).html(newhtml); }); }); }); A: Something like this? $(document).append($('<div />').css('color', 'yellow')); That will append a new div with a colour of yellow to the document. If you need to add it to a specific element just use $('#myselector') instead of $(document) A: Its quite simple var newEl = $('<div THE_ATTRIBUTES_YOU_WANT></div>'); $('THE_ELEMENT_YOU_WANT_TO_APPEND_OR_ADD').append(newEl);
{ "language": "en", "url": "https://stackoverflow.com/questions/7586896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do CGI and mod_perl play nicely together? I've got an apache web server (without mod_perl) that's been running just fine for a long time. It has been suggested that we use mod_perl to improve the performance of some scripts. I want to go ahead and install mod_perl on the server, which seems to be a relatively straightforward process, but I'm confused by some of the stuff coming up on Google searches. If I install mod_perl (through the debian repositories), will all of my existing CGIs suddenly start "using mod_perl" and exhibiting potentially wonky behavior? Or is there some configuration in apache that needs to be done for an old CGI to "start using mod_perl"? Apologies if this is a straightforward answer but I am confused by the terminology being used in multiple ways in the documentation. A: mod_perl has to be configured in your httpd.conf to be enabled. So not every script on your server will start to use mod_perl automatically. Usually, you enable mod_perl per VHost. A usual configuration of mod_perl for a vhost looks like this: <VirtualHost some.funny-domain.com> ServerName some.funny-domain.com ServerAdmin admin@funny-domain.com DocumentRoot /data/path/to/root/ Perlrequire /data/path/to/startup.pl PerlModule Apache2::Reload PerlInitHandler Apache2::Reload PerlModule Apache2::RequestRec ScriptAlias /cgi-bin/ "/data/path/to/root/cgi-bin/" <Location /cgi-bin/> SetHandler perl-script PerlResponseHandler ModPerl::Registry PerlOptions +ParseHeaders PerlOptions +SetupEnv Options +ExecCGI </Location> CustomLog logs/access.log combined ErrorLog logs/error.log </VirtualHost> Be carefull with the automated install-process! It may enable mod_perl on the wrong host for some reason! BackUp your config and apache-installation first to be able to "roll back" easily. Comment: The line "Perlrequire /data/path/to/startup.pl" is not required. It is optional and sets some environment variables for the running scripts under the mod_perl env.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: facebook fb.ui apprequests with skip option? I am trying to use the Dialog for "Invite Friends" via Javascript SDK: function sendRequestToManyRecipients() { FB.ui({method: 'apprequests', message: 'My Great Request', }, requestCallback); } from https://developers.facebook.com/docs/reference/dialogs/requests This works fine for me in case the user selects his friends and submits. My question is how can I also add "Skip" button through this function and if I can also catch the event of clicking "Skip"...any suggestions are highly appreciated! Thanks! A: There is an ajax request fired when apprequests is called. In the callback you will find a response.to array in case if the user selects a friend. If the user does not select it is blank. A blank array in response.to is only when the user skips the dialog box.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save binary file on client in jquery .post I have handler with this code: HttpRequest request = context.Request; HttpResponse response = context.Response; if (request["Type"] != null) { try { string resultFile = null; string fileName = string.Empty; int type = Convert.ToInt32(request["Type"]); switch (type) { case 1: fileName = "InnerQuery.doc"; resultFile = GenerateInnerQuery(Id); break; case 2: fileName = "CourierQuery.doc"; resultFile = GenerateCourierQuery(Id); break; case 3: fileName = "TransportDogovor.doc"; resultFile = GenerateTransportDogovor(Id); break; case 4: fileName = "TransportQuery.doc"; resultFile = GenerateTransportQuery(Id); break; case 5: fileName = "PassQuery.doc"; resultFile = GeneratePassQuery(Id); break; } if (resultFile != null) { response.Clear(); response.AddHeader("pragma", "no-cache"); response.AddHeader("cache-control", "private"); response.CacheControl = "no-cache"; response.ContentType = "application/octet-stream"; response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", System.Web.HttpUtility.UrlPathEncode(fileName))); response.OutputStream.Write(File.ReadAllBytes(resultFile), 0, (int)(new FileInfo(resultFile)).Length); response.End(); } } catch (Exception ex) { } } On client i post data to handler with jQuery.post(): var handler = "GetWord.ashx?Type=6"; var initiationDateFrom = $("#<%=InitiationDateFromTxt.ClientID%>").val(); var initiationDateTill = $("#<%=InitiationDateTillTxt.ClientID%>").val(); var queryDateFrom = $("#<%=QueryDateFromTxt.ClientID%>").val(); var queryDateTill = $("#<%=QueryDateTillTxt.ClientID%>").val(); var queryNumber = $("#<%=NumberTxt.ClientID%>").val(); var initiator = $("#<%=InitiatorTxt.ClientID%>").val(); var state = $("#<%=StateList.ClientID%>").val(); $.post(handler, { InitiationDateFrom: initiationDateFrom, InitiationDateTill: initiationDateTill, QueryDateFrom: queryDateFrom, QueryDateTill: queryDateTill, QueryNumber: queryNumber, Initiator: initiator, State: state }, function (data) { /*here i should save my file*/ }); I recieve binary word-file in "data", but can't to save it on client. last time i use: window.location = handler; but with jQuery.post it not work. A: THIS QUESTION's ANSWERS NEEDS A BIT OF AN UPDATE I THINK I have come across following library: https://github.com/eligrey/FileSaver.js Also in my case it was as simple as following: At least here is the solution that works for me and i only needed to support it in chrome (v37). Preface: I needed to download excel file via post request. So here is how I have tackled it after reading up on few specs and q&as. In my ajax call set up, i set response type to 'blob': 'responseType': 'blob' And once successful response is received you would need to do minor DOM trickery to trigger download as follows: var downloadLink = document.createElement('a'); downloadLink.download = 'export.xlsx'; downloadLink.innerHTML = 'Download File'; downloadLink.href = window.webkitURL.createObjectURL(data); downloadLink.click(); A: When you request the data with an AJAX request, you need to handle it in JavaScript. Saving a file will not be available. Instead of using an AJAX request you need to create a form that holds your parameters. Direct the response into an hidden iframe using the target attribute and the browser will offer to save the file. A: As mentioned above, there are a number of different approaches. You may want to look at jQuery File Upload first. Secondarily, you may want to look at a couple of options that include flash in the solution ( uploadify or swfupload). I have used both in the past and they met my needs satisfactorily - but not perfectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Twig: access current template variable from within macro without passing? Is it possible to access the current template's variables from within a macro without passing the variable to the macro directly? Thanks. A: It's possible to pass all context variables to a macro: {{ macro(_context) }} _context is a special variable, which contains all currently defined variables (by name => value).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to fix url with htacces I have a url which initially http://web.com/index.php/home/funct/ and I want to change this by removing the index.php so that it becomes http://web.com/home/funct/ A: If you are using Apache server, create a file called .htaccess and put this in it: <IfModule mod_rewrite.c> RewriteEngine on # If the file/dir is NOT real go to index RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [QSA,L] </IfModule> Then just remove the reference to "/index.php/" from your links and when the server doesn't find "home/funct" it will go looking for "/index.php/home/funct".
{ "language": "en", "url": "https://stackoverflow.com/questions/7586933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Batch Scripting: Running python script on all directories in a folder I have a python script called script.py which I would like to run on all of the directories inside of a specific directory. What is the easiest way to do this using batch scripting? My assumption is some usage of the FOR command, but I can't quite make any leads to solve the problem using the command... A: Use the /d operator on for: for /D %%d in (*) do script.py %%d This assumes you only need to execute one command per directory (script.py %%d) if you need to execute more use braces (). Also I'm guessing there's an execution engine needed first, but not sure what it is for you. A multi-line example: for /D %%d in (%1) do ( echo processing %%d script.py %%d ) A: Building upon Rudu's answer, and assuming script.py is located in the same directory (say C:\Test) as the following batch script, you could also run script.py recursively on all the directories present in C:\Test: @echo off for /d /r %%d in (*) do ( echo Processing: %%d script.py "%%d" ) The FOR help available from cmd.exe does not seem to mention it supports multiple modifiers, but it works on Windows 7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL - Update multiple fields per row from the same lookup table without multiple joins I have a temp table similar to this create table #temp ( log_id int, ...some other fields, one_user_id int, two_user_id int, three_user_id int, four_user_id int, one_username varchar(50), two_username varchar(50), three_username varchar(50), four_username varchar(50) ) I start out knowing all the user ids, but then I need to look up their names in a user lookup table and update the name fields in the temp table. create table #user_lookup ( user_id int, username varchar(50) ) I know I could join to the user lookup table once for every id using a different alias to get them all, but I was looking for a slick way to do it just once. Any ideas ? EDIT: Ok, more info on the purpose for multiple users per row. The #temp table row (not all fields displayed) signifies a log entry that represents a collation of multiple actions by potentially multiple users, but all tying to that one log row. I could have duplicate log rows, one for each user who played a role, but it's easier to consume on the client side as single rows. This is why there are multiple users per row. A: I think this should work: UPDATE temp SET one_username = u1.username , two_username = u2.username , three_username = u3.username , four_username = u4.username FROM #temp as temp join #user_lookup as u1 on u1.user_id = temp.one_user_id join #user_lookup as u2 on u2.user_id = temp.two_user_id join #user_lookup as u3 on u3.user_id = temp.three_user_id join #user_lookup as u4 on u4.user_id = temp.four_user_id But I don't know why you have four users in one table... ;) A: The only other real alternative solution is to pull in the related records with an IN clause and make use of CASE statements to tie the usernames with the correct user_id's. However this is way more complicated than simply using a JOIN statement and doesn't really offer any advantage except that there aren't multiple JOIN's involved. Here is a complete working sample of how to pull data using this structure: create table #temp ( one_user_id int, two_user_id int, three_user_id int, four_user_id int, one_username varchar(50), two_username varchar(50), three_username varchar(50), four_username varchar(50) ) insert #temp (one_user_id, two_user_id, three_user_id, four_user_id) values (1, 3, 6, 7) insert #temp (one_user_id, two_user_id, three_user_id, four_user_id) values (2, 5, 8, 1) ;with User_Lookup as ( select 1 as user_id, 'abc' as username union select 2, 'def' union select 3, 'ghi' union select 4, 'jkl' union select 5, 'mno' union select 6, 'pqr' union select 7, 'stu' union select 8, 'vwx' union select 9, 'jon' union select 10, 'bob' ), Result as ( select one_user_id, two_user_id, three_user_id, four_user_id, max(case when U.user_id = one_user_id then U.username end) as one_username, max(case when U.user_id = two_user_id then U.username end) as two_username, max(case when U.user_id = three_user_id then U.username end) as three_username, max(case when U.user_id = four_user_id then U.username end) as four_username from #Temp T, User_Lookup U where U.user_id in (T.one_user_id, T.two_user_id, T.three_user_id, T.four_user_id) group by T.one_user_id, T.two_user_id, T.three_user_id, T.four_user_id ) update #temp set one_username = R.one_username, two_username = R.two_username, three_username = R.three_username, four_username = R.four_username from Result R inner join #temp T on R.one_user_id=T.one_user_id and R.two_user_id=T.two_user_id and R.three_user_id=T.three_user_id and R.four_user_id=T.four_user_id select * from #temp drop table #temp Output: one_user_id two_user_id three_user_id four_user_id one_username two_username three_username four_username 1 3 6 7 abc ghi pqr stu 2 5 8 1 def mno vwx abc
{ "language": "en", "url": "https://stackoverflow.com/questions/7586938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is int safe to read from multiple threads? I have multiple threads reading same int variable. and one thread is writing the value. I don't care about the race condition. only my concern is writing and reading int value at same time is memory safe ? and it will not result in any application crash . A: Yes, that should be all right. The only way I can envision that crashing is if one of the threads deallocates the memory backing that integer. For best results I would also make sure the integers are aligned at sizeof(int) boundaries. (Some CPUs cannot access integers at all without this alignment. Others provide weaker guarantees of atomicity for unaligned access.) A: Yes, on x86 and x86-64, as long as the value you're reading is aligned properly. 32-bit ints, they need to be aligned on a 4-byte boundary in order for access to be atomic when reading or writing, which will almost always be the case unless you go out of your way to create unaligned ints (say, by using a packed structure or by doing casting/pointer arithmetic with byte buffers). You probably also want to declare your variable as volatile so that the compiler will generate code that will re-fetch the variable from memory every time it's accessed. That will prevent it from making optimizations such as caching it in a register when it might be altered by another thread. A: On all Linux platforms that I know of, reads and writes of aligned int's are atomic and safe. You will never read a value that wasn't written (no word tearing). You will never cause a fault or crash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Attach to executable with Visual Studio debugger What I'd really like to do is debug an executable using the Visual Studio debugger. It comes with an Attach to Process feature. Unfortunately, the target executable only lasts for a short period- much too short for me to launch the executable and then navigate through Visual Studio and attach to it. How can I command Visual Studio to launch the executable and immediately attach the debugger? A: AttachToLazy VS add-in can wait for a process to start and then attach to it. This add-in was written for VS2008 and it looks like some people were able to get it to work with 2010 by adjusting some of the properties (info under the Discussions tab).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to format a textbox as currency using code behind I have a textbox on a WPF Window (form) that is NOT "bound" using Databinding. I am looking for a way to format the textbox as Currency using code. Is that possible? A: Without any further detail: var myNumber = 45.78d; MyTextBox.Text = myNumber.ToString("C"); You can learn more about formatting numbers on MSDN.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Understanding the WMI object path format I want to write a class with similar funcionality as the .NET ManagementPath class. On MSDN is a set of articles which handles the format of object paths. However, I don't understand it yet with all special cases * *String comparisons that deal with object paths are always case-insensitive. ==> does this also apply to the values of keys when querying for object instances? *Hexadecimal constants for integers. ==> where can they occur? in values of keys only? *Boolean constants for classes with keys that take Boolean values. ==> what are the constants? true / false? 0 / 1? *An assumed local server with a partial namespace path. Thus, specifying the root and default namespace implies the root and default namespace on the local server. ==> does this only mean that if I don't specify a server, that then "." is used as server? *No white space either within an element or between elements. ==> why does the original .NET implementation allow spaces in server names then? *Embedded quotation marks in object paths are allowed but must delimit the quotation mark with escape characters, as in a C or C++ application. ==> ??? *Only decimal values are recognized as numeric portions of keys. ==> ??? *Everything on this page: http://msdn.microsoft.com/en-us/library/aa389223(v=VS.85).aspx ==> ? Well, the basic paths that I think are valid look like \\Server\Namespace \Namespace \\Server\Namespace:Class \Namespace:Class Class \\Server\Namespace:Class.KeyName=KeyValue \Namespace:Class.KeyName=KeyValue Class.KeyName=KeyValue \\Server\Namespace:Class=KeyValue \Namespace:Class=KeyValue Class=KeyValue \\Server\Namespace:Class.FirstKey=FirstValue,SecondKey=SecondValue \Namespace:Class.FirstKey=FirstValue,SecondKey=SecondValue Class.FirstKey=FirstValue,SecondKey=SecondValue \\Server\Namespace:Class=@ \Namespace:Class=@ Class=@ as well as all combinations were the \\ is replaced by a // and/or the \ between server and namespace is replaced by / Have I forgotten anything here? This is what can be extracted from MSDN. However, how may the individual tokens look like? This is what I think it may be: KeyValue = "string" <-- string 1 <-- numeric 0x1 <-- hex ?????????? <-- about the "decimal value" thing and "embedded quitation mark" thing. Also, what about whitespaces? do they have to be abreviated by %20? KeyName / Class / Server = string without : or / or \ inside and maybe only [a-z0-9_] ? Namespace = string without : or / inside and maybe only [a-z0-9_\] (.NET implementation also buggy here. accepts forward slashes regardless of "You cannot use forward slashes within namespace names." on MSDN) Also, are they allowed to start with \ and end with a : ? It would be very helpful if for each token a regular expression could be given of how it looks like. A: Probably you can get useful information seeing the source code of the class. If you want to test a string to be a match or not of a regex, you can use a tester. good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: MKMapViewDelegate derived class and delegate assignment This is probably more of an objective-c question over iOS but I've seen some example code similar to the following that I'd like to better understand. @interface MyMapView : MKMapView <MKMapViewDelegate> { // ivars specific to derived class } @property(nonatomic,assign) id<MKMapViewDelegate> delegate; @end @implementation MyMapView - (id) initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // initialize the ivars specific to this class // Q1: Why invoke super on this delegate that's also a property of this class? super.delegate = self; zoomLevel = self.visibleMapRect.size.width * self.visibleMapRect.size.height; } return self; } #pragma mark - MKMapViewDelegate methods // Q2: Why intercept these callbacks, only to invoke the delegate? - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated { if( [delegate respondsToSelector:@selector(mapView:regionWillChangeAnimated:)] ) { [delegate mapView:mapView regionWillChangeAnimated:animated]; } } @end My two questions are: 1. Why would one invoke the super.delegate and also only declare the 'delegate' as a property? 2. Why intercept all of the delegate calls only to forward them back to the delegate? I appreciate any insights. A: Apple's documentation explicitly states that you should avoid subclass MKMapView: http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html#//apple_ref/doc/uid/TP40008205 Although you should not subclass the MKMapView class itself, you can get information about the map view’s behavior by providing a delegate object. So i guess this delegate "forward" pattern is used to not break things. I use a little different approach to subclass MKMapView. To minimize breakage i use two classes. One that subclass MKMapView and just override the init/dealloc method and assign/release the delegate property to a instance of the other class. The other class is a subclass of NSObject that implements the MKMapViewDelegate protocol and will be the one that does the real work. MyMapView.h @interface MyMapView : MKMapView @end MyMapView.m // private map delegate class @interface MapDelegate : NSObject <MKMapViewDelegate> // instance is not alive longer then MKMapView so use assign to also solve // problem with circular retain @property(nonatomic, assign) MKMapView *mapView; @end @implementation MapDelegate @synthesize mapView; - (id)initWithMapView:(ReportsMapView *)aMapView { self = [super init]; if (self == nil) { return nil; } self.mapView = aMapView; return self; } // MKMapViewDelegate methods and other stuff goes here @end @implementation MyMapView - (id)init { self = [super init]; if (self == nil) { return nil; } // delegate is a assign property self.delegate = [[MapDelegate alloc] initWithMapView:self]; return self; } - (void)dealloc { ((MapDelegate *)self.delegate).mapView = nil; [self.delegate release]; self.delegate = nil; [super dealloc]; } @end The mapView property for MapDelegate class is not strictly needed but is probably useful if want to do things to the map view that that is not a result of some MKMapViewDelegate method call, timers etc. A: * *Why would one invoke the super.delegate and also only declare the 'delegate' as a property? Ans. As you are making a custom mapview it is important to call the delegates too.We are invoking the super class delegate to send control from the custom Mapview. *Why intercept all of the delegate calls only to forward them back to the delegate? Ans.At that line of code we are sending back the control to that delegate method declared in super class to do some useful thing. Hope it will solve the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Freely transforming an image to correct perspective C# newbie here so please forgive me if my terminology isn't quite correct. As part of this project, I have a user hold up a piece of paper to a webcam so I can capture, isolate and then eventually display back what they've drawn on it. I've put some restrictions on where the corners of the paper have to be in order for the program to accept it, but there's still the chance that it's distorted by perspective. Here's an example image that I've captured and isolated the paper out of: image What I want to be able to do is to distort this image so that the corners of the piece of paper are turned back into a 8.5x11-proportioned rectangle (as if the user had scanned it rather than held it up to the webcam). Rotation and skewing can only get me so far, ideally I would be able to freely transform the image, like in Photoshop. I found this example, I am basically trying to do the opposite. Curious if anyone's had to do this, before I start trying to reverse that four-point image distortion example. A: This is sometimes called a Quadrilateral warp. Disclaimer: I work for Atalasoft. Our DotImage Photo SDK can do this and it's free. Look at QuadrilateralWarpCommand. You need to know the source and destination quadrilateral.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL or LINQ for this functionality? I'm writing an SQL script to update the database of a deployed application (add a few tables and copy/update some data) to accommodate new functionality being added to the application (.NET using C#). I've written some code in the application to handle such updates (whenever a new update is available, run its .sql) which reusable for all DB updates (simply provide a new .sql). The problem I'm running into now is that I am fairly new to SQL, and have a pretty short timeline to get this update ready. The more complex part of the update could easily be written in the application, but for consistency's sake I'd like to do it in SQL. What I need to do, I've summarized as the following algorithm/pseudocode: for each category in allCategories Select * from unrankedEntities where Category = category order by (score) take top Category.cutoff insert each of these into rankedEntities with rank = 0 Select * from unrankedEntities where Category = category order by (score) DESC take top 16 - Category.cutoff insert each of these into rankedEntities with rank = null, belowcutoff=true This is the general algorithm I am trying to implement (with a couple more tweaks to be made after this part is complete). Would it be more efficient to write this in SQL or just write the LINQ to do it (resulting in changing the application's database update code for each DB update)? If SQL is the best choice, where can I find a good reference/tutorial covering the topics I would need to do this (I've looked through few different ones online, and some seem pretty simple, so I would appreciate a recommendation of a good one). Additionally, if you have any tips on improving the algorithm, I'd be happy to hear your advice. EDIT: I forgot to mention, but (score) is not a value stored in unrankedEntities. It needs to be calclulated for each entity by counting rows in another table that match a specific condition, and mulitplying by a constant and by numbers pulled from other tables. Additionally, it needs to be stored into rankedEntities to avoid all this calculation every time it is needed (often). EDIT: It has been pointed out to me that parts of the new additions to the application already contain the code necessary to do all of the data manipulation, so I will go with the simple solution of recycling that code, although the result is a less tidy update-via-sql class, as it now has an update-via-sql section and update-via-code section. A: When using LINQ to SQL in debug mode you can see the SQL it's generating, which you could copy into a script, if you need to hurry and not learn all about SQL right at this moment. See http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx EDIT: I didn't realize you were using Entity Framework. See this response to a similar question: How do I get the raw SQL underlying a LINQ query when using Entity Framework CTP 5 "code only"?. A: LINQ is perfectly fine for this, but inserts and updates each entity in a singular fashion, meaning in SQL you could update in bulk with one query, but you cannot in LINQ... it generates separate statements for each entity. So SQL has some efficiency gains. If you are more comfortable with LINQ, do it in LINQ. If you are talking thousands of objects, you may want to turn off change tracking (turned off in EF by changing the merge option) as the internal memory of changed objects will grow rather large.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'dynamic'-like java annotations? I have a pojo that is dependent on annotations. It has predefined fields as well as a Set that contains user provided fields: public class MyPOJO implements Document { private String id; private LocalString name; private LocalString desc; private List<Field> fields; public MyPOJO(final String id, final LocalString name, final LocalString desc, final List<Field> fields) { this.id = id; this.name = name; this.desc = desc; this.fields = fields; } public String getId() { return id; } @Indexed(searchable = false, stored = true) public LocalString getName() { return name; } @Indexed(searchable = true) public LocalString getDescription() { return desc; } public List<Field> getFields() { return fields; } } MyPOJO is a 'generic' object, ie, the developer (or consumer) of MyPOJO has fields that are not predefined in MyPOJO and therefore the developer needs to place these additional fields the in attribute 'fields'. The problem arises from the fact that each object in the Set fields needs to have its own annotations to indicate whether the particular field is either stored or searchable in order to remain consistent with the predefined attributes, such as name. I can think of two options: * *For each additional field, the developer will have to create an anonymous class implementing the interface Field and inside this anonymous class, the developer will declare the applicable annotations. *the Set 'fields' contains a complex object of fieldname, fieldvalue and annotations as shown below. I can't figure out how to invoke the constructor for Field. The below code does not compile but it is intended as pseudo-code to signify what I am trying to do. Field myfield1 = new Field("dateofBirth", new Date(), new ArrayList({Index.stored, Index.searchable}); Field myfield2 = new Field("model", "330i", new ArrayList({Index.stored}); There is no construct to pass annotations as a parameter: new ArrayList({Index.stored}. public class Field { private String name; private Object value; Collection<Annotation> annotations; public Field(final String name, final Object value, Collection<Annotation> annotations;) { this.name = name; this.value = value; this.annotations = Collections.unmodifiableCollection(annotations); } public String getName() { return name; } public Object getValue() { return value; } } I'm not particularly excited with either option and hoping someone can give me some pointers A: If you need an extensible object model, I'd say a POJO design is just setting yourself up for extra work as opposed to exposing a metamodel. That said, what you could do is have clients of the API subclass MyPOJO, and annotate the properties they define in their subclasses. You would then use reflection to go through all JavaBeans properties of the objects you're receiving and determine the annotations on the getters - similarly to how JPA works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java - Picture doesn't show until end of loop? In Java, I have successfully displayed an image on the screen. Now I want to make it move by running it through a for loop. The for loop runs 10 times and sleeps for 1 second each time. Instead of moving the image every second as expected, I have to wait 10 seconds, then 10 images show up. Here's my code: import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JComponent; import javax.swing.JFrame; public class ImageDraw extends JComponent { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Image img1 = Toolkit.getDefaultToolkit().getImage("player.png"); int x = 0; int y = 0; for(int i = 0;i<10;i++){ try { Thread.sleep(1000); x+=10; y+=10; g2.drawImage(img1, x, y, this); repaint(); } catch (InterruptedException e) { e.printStackTrace(); System.exit(0); } } //end for } //end paint } //end class How would I make it so the image looks as if it's moving everytime it runs through the loop? A: In addition to other suggestions: * *Never read the image in the painting method. Read the image when you construct the class or pass in the image with a setImage(...) method. *Custom painting is done by overriding the paintComponent() method, not the paint() method. A: Use a Timer for this, and get rid of the Thread.sleep(). You're running this code on the UI thread, and when you call Thread.sleep() you're putting the UI thread to sleep, which means no updating until the entire loop is complete.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Measuring WCF network traffic I have a VS2010 solution with a Silverlight frontend and a WCF service as backend. I want to measure the WCF communication network traffic. Is there a tool for this? I want to know the number of network packages and network package sizes. I only want to measure the WCF communication packages, not any web site content traffic. A: For WCF monitoring there are special performance counters available by default in the PERMON.EXE program. Read http://blogs.msdn.com/b/wenlong/archive/2007/09/07/how-to-use-performance-counters-to-diagnose-performance-of-wcf-applications.aspx for details on how to enable monitoring. A: I now use Fiddler: http://www.fiddler2.com This is a great tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: strstr faster than algorithms? I have a file that's 21056 bytes. I've written a program in C that reads the entire file into a buffer, and then uses multiple search algorithms to search the file for a token that's 82 chars. I've used all the implementations of the algorithms from the “Exact String Matching Algorithms” page. I've used: KMP, BM, TBM, and Horspool. And then I used strstr and benchmarked each one. What I'm wondering is, each time the strstr outperforms all the other algorithms. The only one that is faster sometimes is BM. Shouldn't strstr be the slowest? Here's my benchmark code with an example of benchmarking BM: double get_time() { LARGE_INTEGER t, f; QueryPerformanceCounter(&t); QueryPerformanceFrequency(&f); return (double)t.QuadPart/(double)f.QuadPart; } before = get_time(); BM(token, strlen(token), buffer, len); after = get_time(); printf("Time: %f\n\n", after - before); Could someone explain to me why strstr is outperforming the other search algorithms? I'll post more code on request if needed. A: Why do you think strstr should be slower than all the others? Do you know what algorithm strstr uses? I think it's quite likely that strstr uses a fine-tuned, processor-specific, assembly-coded algorithm of the KMP type or better. In which case you don't stand a chance of out-performing it in C for such small benchmarks. (The reason I think this is likely is that programmers love to implement such things.) A: Without seeing your code, it's hard to say exactly. strstr is heavily optimized, and usually written in assembly language. It does things like reading data 4 bytes at a time and comparing them (bit-twiddling if necessary if the alignment isn't right) to minimize memory latency. It can also take advantage of things like SSE to load 16 bytes at a time. If your code is only loading one byte at a time, it's probably getting killed by memory latency. Use your debugger and step through the disassembly of strstr -- you'll probably find some interesting things in there. A: Imagine you want to get something cleaned. You could just clean it yourself, or you could hire ten professional cleaners to clean it. If the cleaning job is an office building, the latter solution would be preferable. If the cleaning job was one window, the former would be preferable. You never get any payback for the time spent setting up to do the job efficiently because the job doesn't take very long. A: Horspool, KMP et al are optimal at minimizing the number of byte-comparisons. However, that's not the bottleneck on a modern processor. On an x86/64 processor, your string is being loaded into L1 cache in cache-line-width chunks (typically 64 bytes). No matter how clever your algorithm is, unless it gives you strides that are larger than that, you gain nothing; and the more complicated Horspool code is (at least one table lookup) can't compete. Furthermore, you're stuck with the "C" string constraint of null-termination: SOMEWHERE the code has to examine every byte. strstr() is expected to be optimal for a wide range of cases; e.g. searching for tiny strings like "\r\n" in a short string, as well as much longer ones where some smarter algorithm might have a hope. The basic strchr/memcmp loop is pretty hard to beat across the whole range of likely inputs. Pretty much all x86-compatible processors since 2003 have supported SSE2. If you disassembled strlen()/x86 for glibc, you may have noticed that it uses some SSE2 PCMPEQ and MOVMASK operations to search for the null terminator 16 bytes at a time. The solution is so efficient that it beats the obvious super-simple loop, for anything longer than the empty string. I took that idea and came up with a strstr() that beats glibc's strstr() for all cases greater than 1 byte --- where the relative difference is pretty much moot. If you're interested, check out: * *Convergence SSE2 and strstr() *A better strstr() with no ASM code If you care to see a non-SSE2 solution that dominates strstr() for target strings of more than 15 bytes, check out: which makes use of multibyte comparisons rather than strchr(), to find a point at which to do a memcmp. BTW you've probably figured out by now that the x86 REP SCASB/REP CMPSB ops fall on their ass for anything longer than 32 bytes, and are not much improvement for shorter strings. Wish Intel had devoted a little more attention to that, than to adding SSE4.2 "string" ops. For strings large enough to matter, my perf tests show that BNDM is better than Horspool, across the board. BNDM is more tolerant of "pathological" cases, such as targets that heavily repeat the last byte of a pattern. BNDM can also make use of SSE2 (128bit registers) in a way that competes with 32bit registers in efficiency and start-up cost. Source code here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Hibernate Proxy Inheritance Issue I am using the inheritance strategy table per concrete class and today I faced something very strange. I still don't know the reason for that problem but let me explain what it is... I have the following classes: @Entity @Table(name="...") @Inheritance(strategy=InheritanceType.JOINED) public class A implements Serializable{...} @Entity @Table(name="...") @PrimaryKeyJoinColumn(name="...") public class B extends A{...} Looks pretty simple, and the query i use to retrieve entries is basically this: FROM A This also returns instances of B which is what i expect. The entries are loaded into a backing bean for a view(Bean is viewscoped, persistence context has ended). The view accesses the bean via EL to retrieve the entries for a dataTable: <h:dataTable value="#{bean.entries}" var="entry">...</h:dataTable> Within the dataTable i have a commandLink like that: <h:commandLink value="click" actionListener="#{bean.doSomething}"> <f:setPropertyActionListener value="#{entry}" target="#{bean.selected}" /> </h:commandLink> The bean works with objects of type A, but the CDI-Decorator which is called when invoking the actionListener-Expression would do additional stuff if the type of the selected entry is the subclass: public void doSomething(ActionEvent event){ if(delegate.getSelected() instanceof B){ // special }else{ delegate.doSomething(event); } } And now it gets complicated. The if is entered "sometimes" but not when expected. Debugging revealed that the Object returned by delegate.getSelected() is of the type A_javassisst, EVEN when it should be an instance of B. The best thing about that is, that the toString() method returns B@123 which let me believe at first place, that the object is of type B but it's not... Now we come to my question... What the hell is happening there??? I have already thought of some serialization problems that could occur when saving the state of the dataTable, but I am not sure(Shouldn't the datatable retrieve the values returned by the value-expression and use these for walking through or would that maybe break the state?). The dataTable is a PrimeFaces datatable, have not tried the JSF datatable but it can't be primefaces' fault... All this on the following environment: * *WAS 8.0.0.1 (=> OpenWebBeans) *CODI 1.1.1 *MyFaces 2.1.1 *Hibernate 3.6.5 Thanks in advance for your help! EDIT: All my objects are of type B, means that the db contains an entry in table "b" for every entry in table "a", but sometimes I get Objects from JPA/Hibernate returned that are not instance of B!! Please I need help in this, I have no idea why this could happen!?! EDIT: My diagnosis was wrong, the returned types are the right ones! I really have a Proxy of type B and not a Proxy of type A. My problem was that the method that was decorated was invoked before the setter. This is more JSF related than Hibernate! I didn't face problems and pitfalls you reported yet, using instanceof works fine for me! A: The symptoms match a hibernate limitation. Briefly, lazy-loading proxies for polymorphic entities respond differently to instanceof than the entities they proxy. That's because the proxy is instantiated at a time the actual type of the entity is not yet known, and being a Java object, cannot change its runtime class after creation. Hibernate will return lazy-loading-proxies instead of a materialized entity if * *You explictly request a proxy with session.load() *as stand-in for an entity referenced by a single-valued, lazily fetched assocation from another loaded entity *a proxy has been previously created in the same hibernate session using the above means Case 2 is most common. I have gone as far as to write a unit test that checks my mapping for polymorphic lazy non-null single-valued associations to alert me to this possibility. There are ways to use instanceof and casts with proxies, but they are not trivial. To cast, proxy interfaces must be declared for the polymorphic entities, and all code must program against these interfaces, rather than the entity classes. Hibernate will then have a proxy implement all interfaces the entity might possibly have, allowing all casts. For instanceof, you could declare: class A { boolean isInstanceOf(Class<X extends A> clazz) { return clazz.isInstance(this); } } and then write if (entity.isInstanceOf(B.class)) { B b = (B) entity; // work with b } instead of if (entity instanceof B) { ... A: Such is the issues with hibernate when using polymorphism. In a nutshell, when trawling a hibernate model, where lazy is true, hibernate does not load the real type - loading the real type would requite a db hit and that wouldn't be lazy. If you want the real type to be returned you have to instrument the classes and set the lazy to "proxy". What this would do is not hydrate the proxy until you ask for it, only then would the db get queried to ascertain its real type - this behaviour however is only available with instrumentation on as instrumentation intercepts the call. Turn off lazy wherever you can see it and see if the behaviour changes - it should work with lazy off. This is one of the pitfalls of using hibernate. A: I think clazz.isInstance(this) works, because this is the instance of the target object. That is the difference to instanceof. Take into consideration the the object is unproxied on that call. A: Try to unproxy your object : /** * * @param <T> * @param entity * @return */ @SuppressWarnings("unchecked") public static <T> T initializeAndUnproxy(T entity) { if (entity == null) { // throw new NullPointerException("Entity passed for initialization is null"); return null; } Hibernate.initialize(entity); if (entity instanceof HibernateProxy) { entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation(); } return entity; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7586991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Extreme low-priority SELECT query in MySQL Is it possible to issue an (expensive, but low-priority) SELECT query to mySQL in such a way that if an UPDATE query appears in the queue, mySQL will immediately terminate the query, and re-append it to the end of the queue? If re-appending to the queue is not possible, I'm happy with simply killing the SELECT query. A: No, not really. I am not sure exactly what you need, but my guess is that you need to either optimize the SELECT to not lock an entire table, or get the replication going and do the SELECT on the slave rather than the master. You could theoretically find out what the MySQL process ID is of the SELECT query, and in your application send a KILL before you do any update. A: Well, sort of maybe. A client runs an application which occasionally throws out queries that completely kill performance for everything else on the server. We have monitoring and if we've got a suitable person ready to react, we can deal to that query manually, and we learn about the problems in the app by doing things that way. But to prevent major outages if noone is on the ball, we have an automated script which terminates long running queries, so the server does recover in the event that noone is available to intervene within 15 minutes. Far from ideal, but that's where things are currently at with this project, and it does prevent the occasional extended outages that used to occur. We can only move just so fast with fixing up the problem queries. Anyway, you could run something similar, that looks at the running queries and recognises when you have an update waiting on one of your large selects, and in that event it kills the select. Doing this sort of check a few times a minute is not overly expensive. I'd want to do a bit of testing before running. So, whether you can solve your problem this way depends on what your tolerance is for how long an update can be delayed. Running this every minute (as we do) is no problem at all. Running it every second would noticeably add to the overall load. You'd need to test how far you can reasonably go in between those points. This approach means some delay before the select gets pushed out of the way, but it saves you having to build this logic into potentially many different places in your application. -- Regarding breaking up your query, you're most likely better off restricting the chunks by id range from one or more tables in your query rather than by offset and limit. -- There may also be good solutions available based on partitioning your tables so that the queries don't collide as badly. Make sure you have a very good grasp on what you are doing for this though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: read variables from wp-config.php I'm busy writing a basic migration scripts for some WP sites, and i'm trying to automate creating mysql database and user credentials from reading the wp-config file how can i read the following variables from the wp-config file so that i effectively end up with 3 variables within a bash script: /** The name of the database for WordPress */ define('DB_NAME', 'somedbname'); /** MySQL database username */ define('DB_USER', 'someusername'); /** MySQL database password */ define('DB_PASSWORD', 'somerandompassword'); eg my output should effectively give me: WPDBNAME=somedbname WPDBUSER=somedbuser WPDBPASS=somerandompassword A: If you want to use wp-config details to connect to mysql you can use; mysql -u `cat wp-config.php | grep DB_USER | cut -d \' -f 4` -p`cat wp-config.php | grep DB_PASSWORD | cut -d \' -f 4` -h `cat wp-config.php | grep DB_HOST | cut -d \' -f 4` `cat wp-config.php | grep DB_NAME | cut -d \' -f 4` A: Try this: WPDBNAME=`cat wp-config.php | grep DB_NAME | cut -d \' -f 4` WPDBUSER=`cat wp-config.php | grep DB_USER | cut -d \' -f 4` WPDBPASS=`cat wp-config.php | grep DB_PASSWORD | cut -d \' -f 4` A: you can use awk: awk -F"[()']" '/^define/{printf "%s=\"%s\"\n", $3, $5;}' < foo.php This will give you: DB_NAME="somedbname" DB_USER="someusername" DB_PASSWORD="somerandompassword" Note, that this solution will work with variables containing spaces. A: find . -name "wp-config.php" -print0 | xargs -0 -r grep -e "DB_NAME" -e "DB_USER" -e "DB_PASSWORD" A: If you are trying to dump the MySQL database, you can also use wp-cli db export function: wp db export --path=PATHTOYOURWP A: Here is an example of the universal way to pass php variables to bash without the need to parse: #!/bin/bash source <(php -r 'require("wp-config.php"); echo("DB_NAME=".DB_NAME."; DB_USER=".DB_USER."; DB_PASSWORD=".DB_PASSWORD); ') mysqldump --user $DB_USER --password="$DB_PASSWORD" $DB_NAME | gzip > $DB_NAME-$(date +%Y%m%d%H%M%S).sql.gz Algorithm explanation in a few words: * *run your php *print variables as var=value *source output *use variables in bash
{ "language": "en", "url": "https://stackoverflow.com/questions/7586995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Quadratic programming solver that guarantees a boundary point? I have a problem that I have expressed as the minimization of a convex quadratic program with linear constraints. The problem is that I want to disallow any point that is strictly interior (i.e. I only find the answer useful if it is on a vertex of the feasible region. I'd like to do this without modifying the objective function. I have already considered several modifications that would make this a non-issue, but they all have the unfortunate result of making the program non-convex. By my estimation my only option for an efficient solution would be a solver that uses a penalty method to approach a solution from the outside of the feasible region. Does anyone know a decent solver for this? My current objective function is a sum of parabolic cylinders. A: Can you just find the vertices of the feasible region and then take the one which minimizes the objective function? This should just involve a bit of linear algebra and then a limited number of evaluations of the objective function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setup for high volume of database writing I am researching a project that would require hundreds of database writes per a minute. I have never dealt with this level of data writes before and I am looking for good scalable techniques and technologies. I am a comfortable python developer with experience in django and sql alchemy. I am thinking I will build the data interface on django, but I don't think that it is a good idea to go through the orm to do the amount of data writes I will require. I am definitely open to learning new technologies. The solution will live on Amazon web services, so I have access to all their tools. Ultimately I am looking for advice on database selection, data writing techniques, and any other needs I may have that I do not realize. Any advice on where to start? Thanks, CG A: Follow the trends, in other words, enter the world of NOSQL. Some technologies that are worthy include mongodb and redis. They are really fast, scalable, and with decent python drivers. For example, mongodb plays really nice with django, and has many common things with traditional SQL, like MySQL. On the other hand, redis has more "primitive" data structures but is superior in terms of speed (which of course depends somehow on the drivers). Using any of them ( or both, it's a clever idea for something glorious ) you are free ( and sometimes enforced ) to write your own "low-level" logic to accomplish your needs. A: You should actually be okay with low hundreds of writes per minute through SQLAlchemy (thats only a couple a second); if you're talking more like a thousand a minute, yeah that might be problematic. What kind of data do you have? If it's fairly flat (few tables, few relations), you might want to investigate a non-relational database such as CouchDB or Mongo. If you want to use SQL, I strongly reccommend PostgreSQL, it seems to deal with large databases and frequent writes a lot better than MySQL. It also depends how complex the data is that you're inserting. I think unfortunately, you're going to just have to try a couple things and run benchmarks, as each situation is different and query optimizers are basically magic. A: If it's just a few hundred writes you still can do with a relational DB. I'd pick PostgreSQL (8.0+), which has a separate background writer process. It also has tuneable serialization levels so you can enable some tradeoffs between speed and strict ACID compliance, some even at transaction level. Postgres is well documented, but it assumes some deeper understanding of SQL and relational DB theory to fully understand and make the most of it. The alternative would be new fangled "NO-SQL" system, which can probably scale even better, but at the cost of buying into a very different technology system. Any way, if you are using python and it is not 100% critical to lose writes on shutdown or power loss, and you need a low latency, use a threadsafe Queue.Queue and worker threads to decouple the writes from your main application thread(s).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get enum value names from int column in SQL Server database for a .NET class I am trying to query an int column which represents an enum in a .NET class. I want the result of the query to be the name of the int value. Please keep in mind that I am not trying to do this through .NET code, just working with plain SQL queries here. I could create another table with these values and their corresponding names and then join with it to get the desired result but that would mean having to maintain the values. Is there any other on-the-fly solution I can use? A: you should just be able to call myEnum.ToString() i guess to start from the beginning: int dbValue = 1; var myEnum = (myEnumType)dbValue; string enumName = myEnum.ToString();
{ "language": "en", "url": "https://stackoverflow.com/questions/7587000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JTable doesn't add header row I try to add header row to my JTable and next put table on panel. This is my sample code : Map <String, Float> tmpCart = new HashMap<String , Float>(); MainPanel.removeAll(); MainPanel.repaint(); tmpCart = cart.GetMap(); DefaultTableModel tab = new DefaultTableModel(); tab.setColumnIdentifiers(new String[] {"Name", "Price"}); for (String key : tmpCart.keySet()) tab.addRow(new Object[] {key, tmpCart.get(key)}); JTable jTab = new JTable(tab); jTab.setBounds(10, 10, 200, 200); jTab.setBackground(Color.orange); jTab.setRowHeight(25); JScrollPane pan =new JScrollPane(jTab); MainPanel.add(pan); // MainPanel.add(jTab); // pan.repaint(); How do I write it properly? //answer I try create JTable dynamically, after push button, I want get data from Hashtable, create table and put this table on panel. First step is remove all components from panel, and next create JTable using data from Hashmap` full function: private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) { Map <String, Float> tmpCart = new HashMap<String , Float>(); MainPanel.removeAll(); MainPanel.repaint(); tmpCart = cart.GetMap(); DefaultTableModel tab = new DefaultTableModel(); tab.setColumnIdentifiers(new String[] {"Name", "Price"}); for (String key : tmpCart.keySet()) tab.addRow(new Object[] {key, tmpCart.get(key)}); JTable jTab = new JTable(tab); jTab.setBounds(10, 10, 200, 200); jTab.setBackground(Color.orange); jTab.setRowHeight(25); // MainPanel.add(pan); MainPanel.add(jTab); } This code works, create table and put it on panel, but doesn't set first row with column names ( text : "Names" and "Price"). A: Can't tell exactly what you are doing from the code sample. If you are trying to dynamically update a table on a visible GUI, then there is not need to create a new table, just reset the TableModel. table.setModel( model ); If you need more help then post your SSCCE that demonstrates the problem. Edit: First step is remove all components from panel, Why are your removing components from the panel? If you need to "swap" panels, then use a CardLayout. If you need to "refresh" existing components, then just reset the model as explained above. // MainPanel.add(pan); MainPanel.add(jTab); The scrollPane should be added to the GUI, not the table. A: The table header is another component that only gets added automatically when the table is inside a JScrollPane. Your best bet is to create a JScrollPane via new JScrollPane(table) and add that to your MainPanel. The other option is to added the header directly wherever you want it, and for that you can do: panel.add(table.getTableHeader()) A: Try putting it into a JScrollPane.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to get a gif in a pdfpcell to line up with trailing text I am using iTextSharp to create a .pdf. I've got a table and in the table, I need to populate two checkboxes based on data. My code looks like this. dv is the dataview containing the data, and chkchecked and chkunchecked are gifs of a checked box and unchecked box respectively. Pdfpcell cell = new Pdfpcell(new Phrase("")); cell.AddElement ((int)dv[i]["Return_Reason"] == 6 ? chkchecked : chkunchecked); Phrase p = new Phrase ("item was not authorized for the payee") cell.AddElement (p); cell.AddElement ((int)dv[i]["Return_Reason"] == 7 ? chkchecked : chkunchecked); p = new Phrase ("item was not authorized for the amount") cell.AddElement (p); table.AddCell (cell); And this almost works. But my checkboxes are on the line above the respective text, and I want the check boxe to line up beside the text that follows it. How do I get the gif to share the line with the following text in the cell? A: The trick is to wrap the individual images in a Chunk and then wrap that and the text inside of a Paragraph. When you create a Chunk from an iTextSharp.text.Image you need to specify at least two floats representing x and y offsets. The sample below uses 0 for both but if you see your image riding too high try using a negative, like -3 for the y parameter. Also, my sample images were a little too big so I needed to scale them down. Below is a full working WinForms example targeting iTextSharp 5.1.1.0. See the code for additional comments. using System; using System.Text; using System.Windows.Forms; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; namespace Full_Profile1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { string workingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string outputFile = Path.Combine(workingFolder, "Test.pdf"); string checkedImagePath = Path.Combine(workingFolder, "checked.png"); string uncheckedImagePath = Path.Combine(workingFolder, "unchecked.png"); using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (Document doc = new Document(PageSize.LETTER)) { using (PdfWriter w = PdfWriter.GetInstance(doc, fs)) { //Open our document for writing doc.Open(); //Create images from our file paths var chkchecked = iTextSharp.text.Image.GetInstance(checkedImagePath); var chkunchecked = iTextSharp.text.Image.GetInstance(uncheckedImagePath); //Scale the images to an appropriate size (if needed) chkchecked.ScaleAbsolute(12, 12); chkunchecked.ScaleAbsolute(12, 12); //Create a Paragraph object to contain our images and text Paragraph p = new Paragraph(); //Add an image p.Add(new Chunk(chkchecked, 0, 0)); //Add some text p.Add("checked"); //Add another image p.Add(new Chunk(chkunchecked, 0, 0)); //Add some more text p.Add("checked"); //Create a one column table PdfPTable table = new PdfPTable(1); //Create a cell for the table PdfPCell cell = new PdfPCell(); //Add the paragraph to the cell cell.AddElement(p); //Add the cell to the table table.AddCell(cell); //Add the table to the document doc.Add(table); //Close the document doc.Close(); } } } this.Close(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Automated .NET tool to check for thread safety? Is there any automated tool to check C# .NET code for thread safety? p.s. It doesn't have to be perfect, but it should check for the obvious things that can be checked at compile time. A: The only thing I've seen is TypeMock's racer. It isn't compile time, but it can make some thread bugs (like deadlocking) possible to test.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Kindle Fire minSdkVersion? What is the minimum minSdkVersion to support the new Kindle Fire tablet? I've heard conflicting reports that Amazon's android is based on 2.1 (api level 7) and 2.2 (api level 8). A: Amazon has posted some info. The answer is 2.3.4 (api level 10). I, for one, am glad I don't have to go back to supporting 2.1. A: It's early right now so there's nothing concrete about which version of 2.3 it's running but MinSDKVersion 8 (which is 2.2) if you want to play it safe or 10 (2.3.3). Source A: The Kindle Fire will use: 2.3 Gingerbread
{ "language": "en", "url": "https://stackoverflow.com/questions/7587005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Different 'development' environments for different developers We have three environments: development, staging, and production. In our configuration variables for development, we set our database to connect to 127.0.0.1 with a set username or password. However, other developers part of our team have different username and password configurations. How do we reconcile this without making development_steve, development_mark, development_amir, etc.? A: Eventually we decided to use the same local credentials for our DBs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Mapping of composite key with both elements as foreign key I have a simple Spring-Hibernate application. I have 3 classes crop, market and farmer with structure something like : class crop { private int cropId; } class market { private int marketId; } class farmer { private Crop crop; private Market market; } farmer table has a composite key{cropid, marketid}. Now, how do I map this relationship with composite key element cropid and marketid referencing to crop and market table respectively in the .hbm.xml file . I am quite new to hibernate and spring. Any suggestions will be of great help !! A: In the farmer.hbm.xml you need to make a composite-id like this <composite-id class="FarmerId" mapped="true"> <key-property name="cropid"/> <key-property name="marketid"/> </composite-id> and write a class FarmerID that implements Serializable and overrides equals() and hashCode() In equals() you test if the Objects are the same or have the same values and return a boolean. In hashCode() you generate a hash value and return it. @Override public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || (obj.getClass() != this.getClass())) return false; FarmerID test = (FarmerID) obj; boolean flagCrop = cropid == test.cropid; boolean flagMarket = marketid == test.marketid; return flagCrop && flagMarket; } @Override public int hashCode() { int hash = 7; hash = 31 * hash + cropid.hashCode(); hash = 31 * hash + marketid.hashCode(); return hash; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create ProgressDialog without obscuring the background window I've got a little problem. When I use the showDialog() method of my Activity, it generates a perfect ProgressDialog, but the activity on the background (as the dafault behaviour) and becomes darker. How can I avoid the darkening of my activity? A: Try this: Window window = dialog.getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
{ "language": "en", "url": "https://stackoverflow.com/questions/7587013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Finite Metric Embeddings: Good Algorithm? I have a finite metric space given as a (symmetric) k by k distance matrix. I would like an algorithm to (approximately) isometrically embed this in euclidean space R^(k-1). While it is not always possible to do exactly by solving the system of equations given by the distances I am looking for a solution that embeds with some (very small) controllable error. I currently use multidimensional scaling (MDS) with the output dimension set to (k-1). It occurs to me that in general MDS may be optimized for the situation where you are trying to reduce the ambient embedding dimension to something less then (k-1) (typically 2 or 3) and that there may be a better algorithm for my restricted case. Question: What is a good/fast algorithm for realizing a metric space of size k in R^{k-1} using euclidean distance? Some parameters and pointers: (1) My k's are relatively small. Say 3 < k < 25 (2) I don't actually care if I embed in R^{k-1}. If it simplifies things/makes things faster any R^N would also be fine as long as it's isometric. I'm happy if there's a faster algorithm or one with less error if I increase to R^k or R^(2k+1). (3) If you can point to a python implementation I'll be even happier. (4) Anything better then MDS would work. A: Why not try LLE , you can also find the code there. A: Ok, as promised here a simple solution: Notation: Let d_{i,j}=d_{j,i} denote the squared distance between points i and j. Let N be the number of points. Let p_i denote the point i and p_{i,k} the k-th coordinate of the point. Let's hope I derive the algorithm correctely now. There will be some explanations afterwards so you can check the derivation (I hate it when many indexes appear). The algorithm uses dynamic programming to arrive at the correct solution Initialization: p_{i,k} := 0 for all i and k Calculation: for i = 2 to N do sum = 0 for j = 2 to i - 1 do accu = d_{i,j} - d_{i,1} - p_{j,j-1}^2 for k = 1 to j-1 do accu = accu + 2 p_{i,k}*p_{j,k} - p_{j,k}^2 done p_{i,j} = accu / ( 2 p_{j,j-1} ) sum = sum + p_{i,j}^2 done p_{i,i-1} = sqrt( d_{i,0} - sum ) done If I have not done any grave index mistakes (I usually do) this should do the trick. The idea behind this: We set the first point arbitrary at the origin to make our life easier. Not that for a point p_i we never set a coordinate k when k > i-1. I.e. for the second point we only set the first coordinate, for the third point we only set first and second coordinate etc. Now let's assume we have coordinates for all points p_{k'} where k'<i and we want to calculate the coordinates for p_{i} so that all d_{i,k'} are satisfied (we do not care yet about any constraints for points with k>k'). If we write down the set of equations we have d_{i,j} = \sum_{k=1}^N (p_{i,k} - p_{j,k} )^2 Because both p_{i,k} and p_{j,k} are equal to zero for k>k' we can reduce this to: d_{i,j} = \sum_{k=1}^k' (p_{i,k} - p_{j,k} )^2 Also note that by the loop invariant all p_{j,k} will be zero when k>j-1. So we split this equation: d_{i,j} = \sum_{k=1}^{j-1} (p_{i,k} - p_{j,k} )^2 + \sum_{k=j}^{k'} p_{i,j}^2 For the first equation we just get: d_{i,1} = \sum_{k=1}^{j-1} (p_{i,k} - p_{j,k} )^2 + \sum_{k=j}^{k'} p_i{i,1}^2 This one will need some special treatment later. Now if we solve all binomials in the normal equation we get: d_{i,j} = \sum_{k=1}^{j-1} p_{i,k}^2 - 2 p_{i,k} p_{j,k} + p_{j,k}^2 + \sum_{k=j}^{k'} p_{i,j}^2 subtract the first equation from this and you are left with: d_{i,j} - d_{i,1} = \sum_{k=1}^{j-1} p_{j,k}^2 - 2 p_{i,k} p_{j,k} for all j > 1. If you look at this you'll note that all squares of coordinates of p_i are gone and the only squares we need are already known. This is a set of linear equations that can easily be solved using methods from linear algebra. Actually there is one more special thing about this set of equations: The equations already are in triangular form, so you only need the final step of propagating the solutions. For the final step we are left with one single quadratic equation that we can just solve by taking one square root. I hope you can follow my reasoning. It's a bit late and my head is a bit spinning from those indexes. EDIT: Yes, there were indexing mistakes. Fixed. I'll try to implement this in python when I have time in order to test it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: IIS 7 w/ MVC 3 Permissions Issue I currently am in the process of deploying a MVC 3 Web App to an IIS 7 server. When I work on the web app from visual studio and deploy through development server, the web app has no problem using a custom .dll that interacts with a local server. However, when I deploy onto IIS 7, the same dll fails to pull data from the server through the dll. I am assuming this is permissions related. I have assigned the AppPool to use an account I created that is a member of the local 'Adminstrators' account. No Success. My account is a member of this group. One quirk I noticed was when I tried to modify security setting in the %WINDIR%\inetsvr folder, which holds the process that runs web server for IIS, I was unable to modify these setting even tho I am a member of the 'administrator' account. Confused about this, and have been running around in circles trying to figure this one out. Any help would be appreciated. A: Your web app's associated user definitely don't need to have access permission to %WINDIR%\inetsvr. Assuming that your website runs on C:\interpub\myWebsite and .Net 4.0, your web app's user needs to have at least reader access to following folders : * *C:\interpub\myWebsite *%windir%\Microsoft.NET\FrameWork\v4.0.30319\Temporary ASP.NET Files If you don't grant those access to those folder then it is so likely that your app won't run. Also, visit your site with a browser inside your production server and see the detailed IIS error. That might help to narrow the problem down. NOTE Also, be sure that your app pool is in integrated mode because ASP.NET MVC won't work properly under classic mode if you have extensionless Urls. It is highly likely that you will get 404.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 Active Record - loading the parent object in a has_many :through relationship I have the following class structure for an app I'm porting from php to rails: class Menu < ActiveRecord::Base has_many :menu_headers has_many :menu_items, :through => :menu_headers end class MenuHeader < ActiveRecord::Base acts_as_tree :parent_id has_many :menu_items belongs_to :menu end class MenuItem < ActiveRecord::Base belongs_to :menu_headers end How would I load the MenuHeader or Menu for a specific MenuItem? Like: ruby-1.9.2-p290 :004 > @b=Menu.find(1) #works ruby-1.9.2-p290 :005 > @b.menu_headers #works ruby-1.9.2-p290 :006 > @b.menu_items #works ruby-1.9.2-p290 :004 > @mi=MenuItem.find(1) #works ruby-1.9.2-p290 :005 > @mi.menu_headers #doesn't work ruby-1.9.2-p290 :006 > @mi.menus #doesn't work thx A: You need singular associations as follows: class MenuItem < ActiveRecord::Base belongs_to :menu_header has_one :menu, :through => :menu_header end
{ "language": "en", "url": "https://stackoverflow.com/questions/7587024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find most significant bit (MSB) I want to know which value the first bit of a byte has. For example: I have byte m = (byte) 0x8C; How could I know if the first bit is an 1 or a 0 ? Can anyone help me out ? A: Assuming you mean leftmost bit, bitwise and it with 0x80 and check if it is zero nor not: public boolean isFirstBitSet(byte b) { System.out.println((b & (byte)0x80)); return (b & (byte)0x80) < 0; } If you mean lowest order bit you will need to and with 0x01 and check a different condition: public boolean isFirstBitSet(byte b) { System.out.println((b & (byte)0x01)); return (b & (byte)0x80) > 0; } A: If the first bit is the lowest bit (ie bit 0), then if((m & 1) >0) ... should do it. In general, if ((m & (1<<N)) > 0) ... will give you whether or not bit N is set. If, however, you meant the highest bit (bit 7), then use N=7. A: It depends what you mean by "first bit". If you mean "most significant bit" you can use: // 0 or 1 int msb = (m & 0xff) >> 7; Or if you don't mind the values being 0x80 or 0, just use: // 0 or 0x80 int msb = m & 0x80; Or in fact, as a boolean: // Uses the fact that byte is signed using 2s complement // True or false boolean msb = m < 0; If you mean the least significant bit, you can just use: // 0 or 1 int lsb = m & 1; A: Use the bitwise and operator. public class BitExample { public static void main(String args[]) throws Exception { byte m = (byte)0x8C; System.out.println("The first bit is " + (m & (byte)0x01)); m = (byte)0xFF; System.out.println("The first bit is " + (m & (byte)0x01)); } } // output is... The first bit is 0 The first bit is 1 A: Its a bit of a hack but you can use if(x >> -1 != 0) // top bit set. This works for byte, short, int, long data types. However for most types the simplest approach is to compare with 0 if (x < 0) // top bit set. This works for byte, short, int, long, float, or double (Ignoring negative zero and negative NaN, most people do ;) For char type you need to know the number of bits. ;) if (ch >>> 15 != 0) // top bit set. A: This code gives you msb(most significant bit)/biggest number which is a power of 2 and less than any given number. class msb{ void main(){ int n=155;//let 110001010 int l=(Integer.toBinaryString(n)).length();//9 String w="0"+Integer.toBinaryString(i).substring(1);//010001010 i=Integer.parseInt(w,2); System.out.println(n^i);//110001010^010001010=100000000 } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Get NSWindow from kCGWindowNumber From kCGWindowNumber, how do I get NSWindow ref. I tried using: [NSApp windowWithWindowNumber:windowNumber] but I always get a null value. I need to get the NSWindow to apply [window setlevel:NSFloatingWindowLevel], that I have set the always on top of a given window. Does anyone know how to solve this problem or has any alternative solution? Thanks for the answer, but this is not the solution, I had already tried but it does not work, actually I did a test , I tried the following code: for (NSInteger i = 0; i <10000; i + +) { NSWindow * wind; wind = [NSApp windowWithWindowNumber: windowNumber]; NSLog (@ "\ n Window:% @", wind); } but the result is always the Window: (null) I have a list of window, where can i get OwnerPid Number of window ecc.. ecc... and now I need to set the always on top of some windows. The Always on top is possible set whit: [window setlevel:NSFloatingWindowLevel], window is a NSwindow object, it's real? Do you have a solution? or another idea , for my problem? A: kCGWindowNumber is a CFNumber/NSNumber, -windowWithWindowNumber: expects an NSInteger. You'll need to extract the integer out of the window number reference (with -integerValue) before passing it to -windowWithWindowNumber:.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Font size mismatched between embedded Word object and text boxes I'm developing a new Report (actually a standardized letter) in an Access 2007 db. The majority of the text in this report is static and was provided to me in a Word doc. Because this text is relatively difficult to reproduce in an Access form, I decided to just embed the Word doc itself in the Access report as an unbounded object. So now, this Access report has standard text boxes (with the customer name & address) as well as an embedded Word object (with the letter's body and signature). In theory, all this text should be the same size (Calibri font, size 9). Of course, the text in the Word object is much smaller. How can I get the font sizes to be equal between the text boxes and the Word doc? Should I just manually adjust them until everything more or less looks right? Or is there a better way?
{ "language": "en", "url": "https://stackoverflow.com/questions/7587035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Logging only insert, update and delete mysql queries I'm using a WAMP server with phpmyadmin and MySQL 5.0. I've been looking for a way to only log all insert, update and delete queries, to no avail though. I did manage to get it to auto generate logs adding the "log=C:\wamp\mysql\log\queries.log" line to the my.ini configuration file of mysql, but the log didn't log the exact queries. What i'm trying is that, whenever an insert, delete or update query happens, it logs the query in a file or in another table. Is this possible with procedures? What are my choices? A: This is achieved through the Binary Log . You enable it using the log-bin parameter. You can read the contents of a binary log using this utility, the mysqlbinlog . A: There is a workaround. You can pass the tail's output to grep, e.g. like this: tail -f /var/log/mysql/mysql.log | grep "update "
{ "language": "en", "url": "https://stackoverflow.com/questions/7587037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: svn merge not performing merge We're constantly running into an issue where the svn diff produces a diff with (for example) 5 changes, yet after the merge there are only 2 of the 5 changes in the affected file (yes, just a one-file commit). Usually when this happens when the diff changes are 50+ lines off. For example, the diff says the change starts on line 100, but if the change is actually now on line 155 (because of other changes merged in), svn merge can't (or doesn't) find the affected lines and therefore skips over / ignores the change. Questions: * *What flag can I set in svn to say "if you can't find all the things changed, throw a warning / error so I can fix it before proceeding" *Is there a way for me to tell svn merge to search more than 50 lines for a change? *If there's no way to do #2, can I specify an external diff handler, and if so, how can I do that and still get the advantage of creating and deleting files/directories that's not included in the svn diff output? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7587038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When is it appropriate to set a request-scoped variable in a JSP? In my experience, it is rarely/never necessary to set scope="request" on an EL variable. For example, I have a page that, given an item parameter, constructs a URL specific to that item based on its properties. This page is included in any page that needs to render a link to an item. (A) With request-scoped variables itemLink.jsp <%-- Accepts a parameter named 'item' --%> <c:set var="urlTemplate" value="${param['item'].urlTemplate}" /> <c:choose> <c:when test="${empty urlTemplate}"> <c:set var="itemUrl" scope="request" value="/missingProductUrl.jsp"/> </c:when> <c:otherwise> <c:url var="itemUrl" scope="request" value="${urlTemplate}"> <c:param name="id" value="${param['item'].id}"/> </c:url> </c:otherwise> </c:choose> otherPage.jsp <jsp:include page="itemLink.jsp"> <jsp:param name="item" value="${currentItem}"/> </jsp:include> <%-- 'itemUrl' has request scope --%> <a href="${itemUrl}">Item Link</a> (B) Without request-scoped variables itemLink.jsp <%-- Accepts a parameter named 'item' --%> <c:set var="urlTemplate" value="${param['item'].urlTemplate}" /> <c:choose> <c:when test="${empty urlTemplate}"> <c:set var="itemUrl" value="/missingProductUrl.jsp"/> </c:when> <c:otherwise> <c:url var="itemUrl" value="${urlTemplate}"> <c:param name="id" value="${param['item'].id}"/> </c:url> </c:otherwise> </c:choose> <c:out value="${itemUrl}"/> otherPage.jsp <c:set var="itemUrl"> <jsp:include page="itemLink.jsp"> <jsp:param name="item" value="${currentItem}"/> </jsp:include> </c:set> <%-- 'itemUrl' has page scope --%> <a href="${itemUrl}">Item Link</a> Is there any reason to use (A) over (B)? My answer is no, with the following justifications: * *With (A), you need to remember that any other page processed during the same request will see itemUrl, and so you should avoid name collisions. It also makes tracing the source of EL variables more difficult, as there's no way to find where a request-scoped variable is set except to search through all pages that are processed during the same request. *With (B), none of this is an issue because variables only ever have page scope. EDIT: Perhaps there's a better solution than (B): (C) Using a static include itemLink.jspf <%-- Accepts a parameter named 'item' --%> <c:set var="urlTemplate" value="${param['item'].urlTemplate}" /> <c:choose> <c:when test="${empty urlTemplate}"> <c:set var="itemUrl" value="/missingProductUrl.jsp"/> </c:when> <c:otherwise> <c:url var="itemUrl" value="${urlTemplate}"> <c:param name="id" value="${param['item'].id}"/> </c:url> </c:otherwise> </c:choose> otherPage.jsp <c:set var="item" value="${currentItem}"/> <%@ include page="itemLink.jsp" %> <%-- 'itemUrl' has page scope --%> <a href="${itemUrl}">Item Link</a> It's still the case that neither alternative, (B) nor (C), requires the use of a request-scoped variable. Is there some reason for using request scope that I've missed? A: This section you presented <c:set var="itemUrl"> <jsp:include page="itemLink.jsp"> <jsp:param name="item" value="${currentItem}"/> </jsp:include></c:set> would work only if the itemLink.jsp has only the value for itemUrl and nothing else (No additional html content) But hardly is that a case. Consider a case where you have a Car object in the request scope in your one.jsp and a link in this page takes you to a two.jsp which needs this same Car object. Then <c:set var="myCar" value="${requestScope.car}" scope="request"/> would do the job. This would be impossible with method(B). update: As to why it would not be possible by method(B): In your snippet jsp:include includes the response of the JSP (a text) and then that is set to itemUrl. What if you needed to assign a complex object (non textual, like Car or an ArrayList ) to a request scoped attribute ? A JSP response is typically a html text. Just putting forward an alternative, why not render this way ? <%-- Accepts a parameter named 'item' --%><c:set var="urlTemplate" value="${param['item'].urlTemplate}" /><c:choose> <c:when test="${empty urlTemplate}"> <a href value="/missingProductUrl.jsp"/> </c:when> <c:otherwise> <c:url var="itemUrl" scope="request" value="${urlTemplate}"> <c:param name="id" value="${param['item'].id}"/> </c:url> <c:out value="${itemUrl}"/> </c:otherwise></c:choose> <jsp:include page="itemLink.jsp"> <jsp:param name="item" value="${currentItem}"/></jsp:include> All said, I have hardly had situations where c:set was needed. Normally setting of any scoped attributes is done by the servlet/controller. A JSP would just get a scoped attribute and show it. If JSPs were setting scoped attributes, it would be pretty hard to maintain. And it would be better to limit the using of c:set to only setting page scoped attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Making a dice in ruby language Im coding a dice in ruby in which when i rolled it, it would either come up north south east or west. what im having trouble with is when i roll it how do i tell it to return to me one of these directions? any help would be great. A: Use Array.sample: [ 'north', 'south', 'east', 'west' ].sample A: It doesn't get much easier than %w(north south east west).sample (that's 1.9 method btw). Another thing that works in 1.8 and 1.9 is %w(north south east west)[rand(4)].
{ "language": "en", "url": "https://stackoverflow.com/questions/7587048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Not displaying after quote mark After I run my script, the input field essentially looks like this: <input type="text" value="How do you " /> Even if I slash the quotes or change them to &quot; it still doesn't work. Any suggestions? $('input').html(function() { var dataVal = 'How do you "feel" about that?'; return '<input type="text" value="' + dataVal + '" />'; }); A: Add this after the dataVal definition. dataVal = dataVal.replace(/"/g,"&quot;") It replaces all " characters by the HTML entity of a quotation mark, fixing your code. Currently, your parsed HTML looks like this: <input type="text" value="How do you "feel" about that?" />, which is translated to <input type="text" value="How do you " />. A: You may want this instead: $('input').val(function() { var dataVal = 'How do you "feel" about that?'; return dataVal; }); or just $('input').val('How do you "feel" about that?'); html is for defining the contained html of an element, whereas val is for defining the value of an input field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Batch process photoshop layer with each saved layer having a specific filename I have a layer that is a 250x250px circle. I have an action set up to duplicate this circle layer and reduce the size by 99.2% (-2px). I now need to be able to save this layer as a png file with the filename specific to the dimension of each layer - ie circle_248x248.png , circle_246x246.png and so on... I can batch save but the tricky bit is making it save with the filename specific to the dimension of the layer.. Any suggestions?? Thanks in advance! A: You could use Adobe ExtendScript to give you more control over the script and name the files programmatically. There is no way to do this with Actions. You could use the GD library if you have access to a PHP server and write a simple script to create all your images, since it's such a simple operation. for($i = 250; $i > 100; $i = $i - 2) { $im = imagecreatetruecolor($i, $i); imageantialias($im, true); $white = imagecolorallocate($im, 255, 255, 255); $black = imagecolorallocate($im, 0, 0, 0); imagefilltoborder($im, 0, 0, $white, $white); imagefilledellipse($im, $i/2, $i/2, $i, $i, $black); imagepng($im, "circle_".$i."x".$i.".png); } Sorry to immediately take the problem out of Photoshop, but this is stackoverflow...
{ "language": "en", "url": "https://stackoverflow.com/questions/7587050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Whether we can get WM_IME_* messages when we’re typing in WPF TextBox with IME? First, thanks for reading this thread and provide your suggestion. Here’s the detailed description of my question: Due to large scale of legacy code, we need to use Win32 messages. And for UI part, we need to use WPF to modernize our appearance. That part of UI need to direct keyboard messages into the old legacy component. For input messages without IME, we have used ComponentDispatcher.ThreadFilterMessage to get these messages like WM_KEYDOWN, WM_CHAR, ect. But for IME input, we can’t get the corresponding WM_IME_* messages. Do we have a way to get these messages, or at least, get all the input text which corresponds to WM_IME_* messages? We have tried several ways for that: First, WPF native methods, like OnPreviewKeyDown(), OnTextInput(). One lackage of that solution is that we can’t get the Win32 messages. And I’ve found that WPF will not respond for some special key, e.g. Space key will not cause OnTextInput() to be invoked. Second, different hooks, like SetWindowLong(), HwndSource.AddHook(). These solutions will not get the WM_IME_* messages as well. Third, use InputMethod class. I’ve tried to use InputMethod.ImeConversionMode to determine whether the user input corresponds to WM_IME_* messages. But you know it is a different way with ComponentDispatcher.ThreadFilterMessage, and against several basic laws. At the same time, I’m not sure whether there may be cases overlapped for these two ways, and whether there’re missed cases. There’re so many languages and so many kinds of input methods, each of them has different character set and punctuation (They can be combined separately), then that solution will be risky. When I’m investigating with class ImmComposition, which can be created by TextBoxBase.OnGotKeyboardFocus(), I’ve seen the hook ImmCompositionFilterMessage() is dealing with WM_IME_CHAR(0x0286), but failed to get it in my hook added after base. OnGotKeyboardFocus(): public class HookedTextBox : TextBox { protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnGotKeyboardFocus(e); InstallHook(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to iterate over unicode characters in C++? I know that to get a unicode character in C++ I can do: std::wstring str = L"\u4FF0"; However, what if I want to get all the characters in the range 4FF0 to 5FF0? Is it possible to dynamically build a unicode character? What I have in mind is something like this pseudo-code: for (int i = 20464; i < 24560; i++ { // From 4FF0 to 5FF0 std::wstring str = L"\u" + hexa(i); // build the unicode character // do something with str } How would I do that in C++? A: The wchar_t type held within a wstring is an integer type, so you can use it directly: for (wchar_t c = 0x4ff0; c <= 0x5ff0; ++c) { std::wstring str(1, c); // do something with str } Be careful trying to do this with characters above 0xffff, since depending on the platform (e.g. Windows) they will not fit into a wchar_t. If for example you wanted to see the Emoticon block in a string, you can create surrogate pairs: std::wstring str; for (int c = 0x1f600; c <= 0x1f64f; ++c) { if (c <= 0xffff || sizeof(wchar_t) > 2) str.append(1, (wchar_t)c); else { str.append(1, (wchar_t)(0xd800 | ((c - 0x10000) >> 10))); str.append(1, (wchar_t)(0xdc00 | ((c - 0x10000) & 0x3ff))); } } A: You cannot increment over Unicode characters as if it is an array, some characters are build up out of multiple 'char's (UTF-8) and multiple 'WCHAR's (UTF-16) that's because of the diacritics etc. If you're really serious about this stuff you should use an API like UniScribe or ICU. Some resources to read: http://en.wikipedia.org/wiki/UTF-16/UCS-2 http://en.wikipedia.org/wiki/Precomposed_character http://en.wikipedia.org/wiki/Combining_character http://scripts.sil.org/cms/scripts/page.php?item_id=UnicodeNames#4d2aa980 http://en.wikipedia.org/wiki/Unicode_equivalence http://msdn.microsoft.com/en-us/library/dd374126.aspx A: What about: for (std::wstring::value_type i(0x4ff0); i <= 0x5ff0; ++i) { std::wstring str(1, i); } Note that the code has not been tested, so it may not compile as-is. Also, given the platform you are working on a wstring's character unit may be 2, 4, or N bytes wide- so be intentional about how you use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Do I need to overload methods accepting const lvalue reference for rvalue references explicitly? currently I’m playing around with rvalue reference (C++11, g++ with gnu++x0) and I want to implement move semantics in my classes, because it just feels „right“. Do I need to overload each function which normally would accept const lvalue reference to benefit from the rvalue references? Let’s say this is my example class: class Person { public: Person() = default; Person(std::string &name); Person(const Person &rhs); Person(Person &&rhs); Person& operator=(const Person &rhs); Person& operator=(Person &&rhs); std::string& get_name() const; void set_name(const std::string &name); private: std::string name_; } /* snip */ void Person::set_name(const std::string &name) { this->name_ = name; } I now want to use the setter with rvalue references and eliminate unnecessary copies. Person test("Jon Doe"); test.set_name("Jon Doe2"); Do I really need to overload every method this way? void Person::set_name(std::string &&name) { this->name_ = std::move(name); } This seems very redundant to me. Is there any way to implement this easier? Thanks! (I read stackoverflow often, but this is my first question. So please give me hint if I’m doing something wrong.) A: Write one function. Take it in by value, then move it. void Person::set_name(std::string name) { this->name_ = std::move(name); } Let the std::string decide how to copy itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is this method of inter-thread-communication safe? I have 3 objects(inherited from QObject) that each contain a separate std::list. Each object gets created in the main gui thread (with no parent) and then is pushed to it's own thread (using Qt's QObject::moveToThread()). Each thread is hooked up to a gui and messages are sent between the different threads with data. Each thread is to essentially handle it's own list. For example: Obj 1 : Consumer of data. It pop's the front off of its list(if data is present) to use. It also has a SLOT available so that other threads can push data to it. No other object can access this list directly only the the original QObject class. Obj 2 : Producer of data. It pushes data to its list. It has SLOTS available for others to 'ping' it for data which will in turn emit a SIGNAL popping data from its list. No other object can access this list directly. Obj 3: Produces data for obj 1 and consumes data from obj 2. It has it's own internal data structures that keep track of the data sent to obj 1 and the data coming from obj 2. It finally will push both data sets to some QwtPlots after it does some analysis. Obj's 1 and 2 are real-time critial and use QueryPerformanceCounter style 'timing' which will essentially suck down a CPU each while they're running. They run QCoreApplication::processEvents() every loop to handle the events that come down through. Is this an okay way to handle cross-thread data sharing? If it isn't, where are the holes and how would you correct them? I understand this will create a lot of 'copies' of data flying around, but memory bloat isn't a concern at this point. thanks in advance :) A: It's hard to say exactly whether it's thread-safe or not without all the implementation details as there are a lot of things that can go wrong when using threads. Obj 1 : Consumer of data. It pop's the front off of its list(if data is present) to use. It also has a SLOT available so that other threads can push data to it. No other object can access this list directly only the the original QObject class. If this slot is connected to signals in other threads (such as Obj 3) using queued or auto connection type, then the Obj 1 is probably safe. If the slot is called directly from other threads, then it obviously isn't thread safe unless you explicitly synchronize everything. Obj 2 : Producer of data. It pushes data to its list. It has SLOTS available for others to 'ping' it for data which will in turn emit a SIGNAL popping data from its list. No other object can access this list directly. You don't mention how "pinging" is implemented or which threads call those slots. If other threads call them directly and if pinging involves accessing the internal std::list, then you're in trouble. If those slots are only called via queued or auto connections (to some signal in Obj 3, for example), then it's fine. If those slots are thread safe (for example, they only put a "ping" message into some sort of internal synchronized message queue), then it's fine too. The latter way looks like custom reimplementation of the queued connection mechanism, though. Overall, this whole thing looks too dangerous to me as slots can be called from anywhere by mistake. I'd try to avoid this kind of thing by putting some safety checks there, like this: void Obj2::ping() { if (QThread::currentThread() != this->thread()) { // not sure how efficient it is QMetaObject::invoke(this, "ping", Qt::QueuedConnection); return; } // thread unsafe code goes here }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Gnu Emacs: tab-completion for psql running within sql.el process I enjoy running Postgres client "psql" under psql.el while interacting with a .sql file in a separate window. Sometimes, I want to use tab-completion within the the buffer running the psql process to find the name of an appropriate table name. However, I can not figure out how to cause the desired result. A very related question has been asked here: https://superuser.com/questions/236574/how-can-i-send-a-literal-tab-to-bash-in-emacs-shell-mode without any successful suggestions. Thanks in advance! SetJmp A: Usually programs that designed for interactive use (when they own terminal) disable interactive features (like history for UP/DOWN, completion for TAB) when used in pipe. Emacs usually use pipes for external processes. So interactive features are disabled. Even if you send TAB, your client program does not interpret it for you as you want. You can read man/help for your program and try force interactive mode by providing command line switch (like --login for GNU Bash). To send TAB eval: (defun my-comint-send-string (string) "Send string to comint buffers. Useful for *compilation* read-only buffer." (interactive (list (read-input "Type string: " nil 'my-comint-send-hist-list))) (comint-send-string (get-buffer-process (current-buffer)) string)) (define-key XXX-mode-map [C-return] 'my-comint-send-string) and use such key sequence: C-RET C-q TAB RET. But this may not work if buffering is enabled for stdio of your program (to flush input you must send \n too)... Mostly same problem discussed at Bash autocompletion in Emacs shell-mode NOTE M-x term use pseudo terminal so all interactive program work as desired. But in this mode you lose any Emacs editing capabilities...
{ "language": "en", "url": "https://stackoverflow.com/questions/7587072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I check for the SQL Server Version using Powershell? What's the easiest way to check for the SQL Server Edition and Version using powershell? A: Just an option using the registry, I have found it can be quicker on some of my systems: $inst = (get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances foreach ($i in $inst) { $p = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL').$i (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$p\Setup").Edition (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$p\Setup").Version } A: Hacked up advice from this thread (and some others), this went in my psprofile: Function Get-SQLSvrVer { <# .SYNOPSIS Checks remote registry for SQL Server Edition and Version. .DESCRIPTION Checks remote registry for SQL Server Edition and Version. .PARAMETER ComputerName The remote computer your boss is asking about. .EXAMPLE PS C:\> Get-SQLSvrVer -ComputerName mymssqlsvr .EXAMPLE PS C:\> $list = cat .\sqlsvrs.txt PS C:\> $list | % { Get-SQLSvrVer $_ | select ServerName,Edition } .INPUTS System.String,System.Int32 .OUTPUTS System.Management.Automation.PSCustomObject .NOTES Only sissies need notes... .LINK about_functions_advanced #> [CmdletBinding()] param( # a computer name [Parameter(Position=0, Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.String] $ComputerName ) # Test to see if the remote is up if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) { # create an empty psobject (hashtable) $SqlVer = New-Object PSObject # add the remote server name to the psobj $SqlVer | Add-Member -MemberType NoteProperty -Name ServerName -Value $ComputerName # set key path for reg data $key = "SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL" # i have no idea what this does, honestly, i stole it... $type = [Microsoft.Win32.RegistryHive]::LocalMachine # set up a .net call, uses the .net thingy above as a reference, could have just put # 'LocalMachine' here instead of the $type var (but this looks fancier :D ) $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName) # make the call $SqlKey = $regKey.OpenSubKey($key) # parse each value in the reg_multi InstalledInstances Foreach($instance in $SqlKey.GetValueNames()){ $instName = $SqlKey.GetValue("$instance") # read the instance name $instKey = $regKey.OpenSubkey("SOFTWARE\Microsoft\Microsoft SQL Server\$instName\Setup") # sub in instance name # add stuff to the psobj $SqlVer | Add-Member -MemberType NoteProperty -Name Edition -Value $instKey.GetValue("Edition") -Force # read Ed value $SqlVer | Add-Member -MemberType NoteProperty -Name Version -Value $instKey.GetValue("Version") -Force # read Ver value # return an object, useful for many things $SqlVer } } else { Write-Host "Server $ComputerName unavailable..." } # if the connection test fails } A: To add to Brendan's code.. this fails if your machine is 64-bit, so you need to test appropriately. Function Get-SQLSvrVer { <# .SYNOPSIS Checks remote registry for SQL Server Edition and Version. .DESCRIPTION Checks remote registry for SQL Server Edition and Version. .PARAMETER ComputerName The remote computer your boss is asking about. .EXAMPLE PS C:\> Get-SQLSvrVer -ComputerName mymssqlsvr .EXAMPLE PS C:\> $list = cat .\sqlsvrs.txt PS C:\> $list | % { Get-SQLSvrVer $_ | select ServerName,Edition } .INPUTS System.String,System.Int32 .OUTPUTS System.Management.Automation.PSCustomObject .NOTES Only sissies need notes... .LINK about_functions_advanced #> [CmdletBinding()] param( # a computer name [Parameter(Position=0, Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.String] $ComputerName ) # Test to see if the remote is up if (Test-Connection -ComputerName $ComputerName -Count 1 -Quiet) { $SqlVer = New-Object PSObject $SqlVer | Add-Member -MemberType NoteProperty -Name ServerName -Value $ComputerName $base = "SOFTWARE\" $key = "$($base)\Microsoft\Microsoft SQL Server\Instance Names\SQL" $type = [Microsoft.Win32.RegistryHive]::LocalMachine $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName) $SqlKey = $regKey.OpenSubKey($key) try { $SQLKey.GetValueNames() } catch { # if this failed, it's wrong node $base = "SOFTWARE\WOW6432Node\" $key = "$($base)\Microsoft\Microsoft SQL Server\Instance Names\SQL" $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $ComputerName) $SqlKey = $regKey.OpenSubKey($key) } # parse each value in the reg_multi InstalledInstances Foreach($instance in $SqlKey.GetValueNames()){ $instName = $SqlKey.GetValue("$instance") # read the instance name $instKey = $regKey.OpenSubkey("$($base)\Microsoft\Microsoft SQL Server\$instName\Setup") # sub in instance name # add stuff to the psobj $SqlVer | Add-Member -MemberType NoteProperty -Name Edition -Value $instKey.GetValue("Edition") -Force # read Ed value $SqlVer | Add-Member -MemberType NoteProperty -Name Version -Value $instKey.GetValue("Version") -Force # read Ver value # return an object, useful for many things $SqlVer } } else { Write-Host "Server $ComputerName unavailable..." } # if the connection test fails } A: Try this Invoke-SqlCmd -query "select @@version" -ServerInstance "localhost" Check all available method to Get the build number of the latest Cumulative Update / Service Pack that has been installed in SQL Server A: Invoke-Sqlcmd -Query "SELECT @@VERSION;" -QueryTimeout 3 http://msdn.microsoft.com/en-us/library/cc281847.aspx A: Here is a version I cobbled together from some sources here and there*. This version does not hit the registry, does not hit SQL, and doesn't even require that the instance be running. It does require that you know the instance name. If you don't know the instance name, you should be able to trivially work it out from this code. To get this to work, replace "YourInstanceNameHere" with the name of your instance. Don't touch the $ if you do it won't work. $ErrorActionPreference = "Stop" $instanceName = "MSSQL`$YourInstanceNameHere" $sqlService = Get-Service -Name $instanceName $WMISQLservices = Get-WmiObject -Class Win32_Product -Filter "Name LIKE 'SQL Server % Database Engine Services'" | Select-Object -Property Name,Vendor,Version,Caption | Get-Unique foreach ($sqlService in $WMISQLservices) { $SQLVersion = $sqlService.Version $SQLVersionNow = $SQLVersion.Split("{.}") $SQLvNow = $SQLVersionNow[0] $thisInstance = Get-WmiObject -Namespace "root\Microsoft\SqlServer\ComputerManagement$SQLvNow" -Class SqlServiceAdvancedProperty | Where-Object {$_.ServiceName -like "*$instanceName*"} | Where-Object {$_.PropertyName -like "VERSION"} } $sqlServerInstanceVersion = $thisInstance.PropertyStrValue if ($sqlServerInstanceVersion) { $majorVersion = $thisInstance.PropertyStrValue.Split(".")[0] $versionFormatted = "MSSQL$($majorVersion)" } else { throw "ERROR: An error occured while attempting to find the SQL Server version for instance '$($instanceName)'." } $versionFormatted *I also received help from and help from this this friend of mine https://stackoverflow.com/users/1518277/mqutub and I didn't want it to go uncredited. A: [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" "." $srv.Version $srv.EngineEdition Obviously, replace "." with the name of your instance. If you want to see all the methods available, go here. A: All you need is to connect to SQL Server and run this query: select @@version This, of course, will work for any client tool. Additionally, this is also available: SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition') More ways to determine the SQL Server version here: http://support.microsoft.com/kb/321185 A: Just an expansion of Ben Thul's answer, It loops through a list of all my DB Servers and prints out the current version of the database engine: [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null $computers = @(‘XXXX-OMG-DB-01’,’XXXX-PRO-DB-01’,’XXXX-PRO-DB-02’, ’XXXX-QAT-DB-01', 'XXXX-TST-DB-01’,'YYYY-PRO-DB-01', 'YYYY-PRO-DB-02','YYYY-QAT-DB-01','YYYY-QAT-DB-02', 'YYYY-TST-DB-01','ZZZZ-DEV-DB-01','ZZZZ-DEV-DB-02') $computers | % { $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $_ if ($null -eq $srv.ComputerNamePhysicalNetBIOS) { $s = $_.tostring() + ' is unavailable' $s.tostring() } else { $srv.ComputerNamePhysicalNetBIOS + ' ' + $srv.VersionString + ' ' + $srv.DatabaseEngineEdition } } A: Well, here's the old school way, that's easy: sqlcmd -Q "select @@version;" And here's how I use it from Serverspec: require 'windows_spec_helper' describe 'MS SQL Server Express' do describe service('MSSQLSERVER') do it { should be_enabled } it { should be_running } end describe port(1433) do it { should be_listening } end describe command('sqlcmd -Q "select @@version;"') do its(:stdout) { should match /Microsoft SQL Server 2008 R2 (SP2) - 10.50.4000.0 (X64)/ } end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7587077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Non-dirty view gets redrawn I do have a strange problem. I programmed a a dockview. It's basically a NSView with three vertical subviews inside. So I have a left dock, a middle view and a right dock. Both docks are collapsable. The middle view gets resized while collapsing. I'm using CoreAnimation to animate the collapsing process. This works almost correct. If I uncollapse the left dock, the right docks drawRect method gets called although it's not dirty. If I deactivate the animator and set the new frame size directly, the right dock not gets redrawn while uncollapsing so I assume the calculation of the frames is correct. Here is my code for collapsing the docks: - (void) mouseDown:(NSEvent *)event { // Exit method if already animating a dock if(is_animating) { return; } NSPoint firstPoint = [self convertPoint:[event locationInWindow] fromView:nil]; unsigned long divider = [self mousePointInCollapseRect:firstPoint]; // If not clicked on a divider don't animate anything if(divider == NSNotFound) { return; } NSView* main_view = [[self subviews] objectAtIndex:VIEW_MIDDLE]; NSView* collapse_view = [[self subviews] objectAtIndex:(divider == 0)? VIEW_LEFT : VIEW_RIGHT]; NSRect cframe = [collapse_view frame]; // New collapsable frame NSRect mframe = [main_view frame]; // New main frame if([self isSubviewCollapsed:collapse_view] == NO) { if(divider == 0) { cframe.size.width = 0.0; mframe.origin.x -= (dock_width_left + DIVIDER_THICKNESS); mframe.size.width += (dock_width_left + DIVIDER_THICKNESS); } else { mframe.size.width += (collapse_view.frame.size.width + DIVIDER_THICKNESS); cframe.size.width = 0.0; cframe.origin.x = mframe.origin.x + mframe.size.width; } // Turn off autoresizesSubviews on the collapsible subview [collapse_view setAutoresizesSubviews:NO]; [NSAnimationContext beginGrouping]; [[NSAnimationContext currentContext] setDuration:(ANIMATION_DURATION)]; [[collapse_view animator] setFrame:cframe]; [[main_view animator] setFrame:mframe]; [NSAnimationContext endGrouping]; } else { // Uncollapse dock if(divider == 0) { // Left dock cframe.size.width = dock_width_left; mframe.origin.x = (COLLAPSEBAR_THICKNESS + dock_width_left + DIVIDER_THICKNESS); mframe.size.width -= (dock_width_left + DIVIDER_THICKNESS); } else { // Right dock mframe.size.width -= (dock_width_right + DIVIDER_THICKNESS); cframe.size.width = dock_width_right; cframe.origin.x = mframe.origin.x + mframe.size.width + DIVIDER_THICKNESS; } [NSAnimationContext beginGrouping]; [[NSAnimationContext currentContext] setDuration:ANIMATION_DURATION]; [[main_view animator] setFrame:mframe]; [[collapse_view animator] setFrame:cframe]; [NSAnimationContext endGrouping]; //Restore Autoresizing on subview [self performSelector:@selector(restoreAutoResizingOfSubview:) withObject:collapse_view afterDelay:ANIMATION_DURATION + 0.05]; } is_animating = YES; [self performSelector:@selector(animationEnded) withObject:nil afterDelay:ANIMATION_DURATION + 0.05]; } So why gets a non-dirty view redrawn?
{ "language": "en", "url": "https://stackoverflow.com/questions/7587084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you compare the time portion of a time string? I have in my preferences some strings that represent a start time and and ending time. I wrote this function to determine if the current time is within the start and ending time. The format of the date strings is "HH:mm". The function takes the strings that are from the preferences. I'm sure I'm missing some code for the comparing because my parsing returns a something like this: Thu Sep 29 12:24:33 EDT 2011 But all I need is to get this: 12:24 Here is the function. Can you help me correct the coding? Thanks. Truly, Emad public static boolean currentTimeIsWithinStartAndEnd(String startTime, String endTime) { String pattern = "HH:mm"; SimpleDateFormat sdf = new SimpleDateFormat(pattern); boolean booleanValueToReturn = false; try { Date startTimeToCompare = sdf.parse(startTime); Date endTimeToCompare = sdf.parse(endTime); /* * These are for the current time in date format. */ Date currentTime = new Date(System.currentTimeMillis()); Log.w("Emad", "Current Time: " + currentTime + " Start Time is: " + startTimeToCompare + " End Time is : " + endTimeToCompare); /* * Check if current time is equal or greater than the start time. */ if (currentTime.compareTo(startTimeToCompare) == 0 || currentTime.compareTo(startTimeToCompare) == 1) { booleanValueToReturn = true; /* * Now check if the current time is equal or less than the end * time. */ if (currentTime.compareTo(endTimeToCompare) == 0 || currentTime.compareTo(endTimeToCompare) == -1) { booleanValueToReturn = true; } else { booleanValueToReturn = false; } } else { booleanValueToReturn = false; } } catch (java.text.ParseException e) { } return booleanValueToReturn; A: You are using SimpleDateFormat Incorrectly. String pattern = "HH:mm" should be format in which your input Date String is. otherwise how is SimpleDateFormat going to know which portion represents what. Create two SimpleDateFormat, f1 (with Input String Format) and f2 ( with output String Format) ; Use f1.parse() to get Date object for Input String. Then use f2.format() on this Date Object to get Output String representation. Refer to SimpleDateFormat for details on how to specify date Format. public static boolean currentTimeIsWithinStartAndEnd(String startTime, String endTime) { // assuming input date string is of format MM/dd/yyyy. Change it according to your needs. String inputPattern = "MM/dd/yyyy"; String outputPattern = "HH:mm"; SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern); SimpleDateFormat outputFormatter = new SimpleDateFormat(outputPattern); Date startTimeToCompare = inputFormatter.parse(startTime); String dateInRequiredFormat = outputFormat.format(startTimeToCompare);
{ "language": "en", "url": "https://stackoverflow.com/questions/7587086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: will_paginate dropping "sum" after first page I am using will_paginate which works like a charm for breaking up my results into many pages. But on any page but the first one, my 'sum' method returns 0. My view has two tables in it. The first is summary information over the entire collection and the second is the paginated collection. Page 1 of my collection shows everything perfect. Page >= 2 turns the 'sum' to 0 yet .count still works. My controller: def donations_by_season @season_name = params[:season_name] @donations = Donation.by_season(@season_name).paginate :page=>params[:page], :order=>'created_at desc', :per_page => 25 @valid_seasons = Donation.select(:season).group(:season) end My Partial has these values in the top table: <td> <%= number_to_currency @donations.sum(:amount) %></td> <td><%= @donations.count %></td> And these in the lower: <% @donations.each do |donation| %> <tr class="<%= cycle("odd", "even", :name => "row_class") %> "> <td><%= number_to_currency(donation.amount) %></td> <td><%= donation.iho_full %></td> <td><%= donation.box_code %></td> <td><%= donation.list_name %></td> </tr> <% end %> </table> <p><%= will_paginate @donations %></p> On page one, number_to_currency @donations.sum(:amount) and @donations.count are accurate. After page one, the .sum turns to 0 but the .count remains the same. How do I get the .sum to work as well? A: I believe will_paginate is overriding the relation method "count". If you take a look at the relation returned by the paginate method, it doesn't contain the elements that it says its counting. The same for sum. It must be overwritting it, because it does not reflect what the true collection is returning. If you refactor your code, to use: @all_donations = Donation.by_season(@season_name) @donations = @all_donations.paginate :page=>params[:page], :order=>'created_at desc', :per_page => 25 And use @all_donations, to get the count and sum metrics, it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can JAXB marshal by containment at first then marshal by @XmlIDREF for subsequent references? I'm wondering if it's possible to annotate my classes so that the first time the marshaller encounters an object, it generates an XML element of the appropriate type, but any subsequent reference to this object by anything else will have an XML IDREF entry created? A: You can leverage the concept of JAXB's XmlAdapter to do something like the following: input.xml The following is the XML document I will use for this example. The 3rd phone-number entry is a reference to the 1st phone-number entry, and the 5th phone-number entry is a reference to the 4th.: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customer> <phone-number id="A"> <number>555-AAAA</number> </phone-number> <phone-number id="B"> <number>555-BBBB</number> </phone-number> <phone-number id="A"/> <phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W"> <number>555-WORK</number> <extension>1234</extension> </phone-number> <phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W"/> </customer> Customer The customer class maintains a collection of PhoneNumber objects. The same instance of PhoneNumber may appear multiple times in the collection. package forum7587095; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Customer { private List<PhoneNumber> phoneNumbers; @XmlElement(name="phone-number") public List<PhoneNumber> getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) { this.phoneNumbers = phoneNumbers; } } PhoneNumber This is a class that can either appear in the document itself or as a reference. This will be handled using an XmlAdapter. An XmlAdapter is configured using the @XmlJavaTypeAdapter annotation. Since we have specified this adapter at the type/class level it will apply to all properties referencing the PhoneNumber class: package forum7587095; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @XmlJavaTypeAdapter(PhoneNumberAdapter.class) public class PhoneNumber { private String id; private String number; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } @Override public boolean equals(Object arg0) { if(null == arg0 || arg0.getClass() != this.getClass()) { return false; } PhoneNumber test = (PhoneNumber) arg0; if(!equals(id, test.getId())) { return false; } return equals(number, test.getNumber()); } protected boolean equals(String control, String test) { if(null == control) { return null == test; } else { return control.equals(test); } } @Override public int hashCode() { return id.hashCode(); } } WorkPhoneNumber Based on your comment I have added a subclass of PhoneNumber. package forum7587095; public class WorkPhoneNumber extends PhoneNumber { private String extension; public String getExtension() { return extension; } public void setExtension(String extension) { this.extension = extension; } @Override public boolean equals(Object arg0) { if(!super.equals(arg0)) { return false; } return equals(extension, ((WorkPhoneNumber) arg0).getExtension()); } } PhoneNumberAdapter Below is the implementation of the XmlAdapter. Note that we must maintain if the PhoneNumber object has been seen before. If it has we only populate the id portion of the AdaptedPhoneNumber object. package forum7587095; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; public class PhoneNumberAdapter extends XmlAdapter<PhoneNumberAdapter.AdaptedPhoneNumber, PhoneNumber>{ private List<PhoneNumber> phoneNumberList = new ArrayList<PhoneNumber>(); private Map<String, PhoneNumber> phoneNumberMap = new HashMap<String, PhoneNumber>(); @XmlSeeAlso(AdaptedWorkPhoneNumber.class) @XmlType(name="phone-number") public static class AdaptedPhoneNumber { @XmlAttribute public String id; public String number; public AdaptedPhoneNumber() { } public AdaptedPhoneNumber(PhoneNumber phoneNumber) { id = phoneNumber.getId(); number = phoneNumber.getNumber(); } public PhoneNumber getPhoneNumber() { PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setId(id); phoneNumber.setNumber(number); return phoneNumber; } } @XmlType(name="work-phone-number") public static class AdaptedWorkPhoneNumber extends AdaptedPhoneNumber { public String extension; public AdaptedWorkPhoneNumber() { } public AdaptedWorkPhoneNumber(WorkPhoneNumber workPhoneNumber) { super(workPhoneNumber); extension = workPhoneNumber.getExtension(); } @Override public WorkPhoneNumber getPhoneNumber() { WorkPhoneNumber phoneNumber = new WorkPhoneNumber(); phoneNumber.setId(id); phoneNumber.setNumber(number); phoneNumber.setExtension(extension); return phoneNumber; } } @Override public AdaptedPhoneNumber marshal(PhoneNumber phoneNumber) throws Exception { AdaptedPhoneNumber adaptedPhoneNumber; if(phoneNumberList.contains(phoneNumber)) { if(phoneNumber instanceof WorkPhoneNumber) { adaptedPhoneNumber = new AdaptedWorkPhoneNumber(); } else { adaptedPhoneNumber = new AdaptedPhoneNumber(); } adaptedPhoneNumber.id = phoneNumber.getId(); } else { if(phoneNumber instanceof WorkPhoneNumber) { adaptedPhoneNumber = new AdaptedWorkPhoneNumber((WorkPhoneNumber)phoneNumber); } else { adaptedPhoneNumber = new AdaptedPhoneNumber(phoneNumber); } phoneNumberList.add(phoneNumber); } return adaptedPhoneNumber; } @Override public PhoneNumber unmarshal(AdaptedPhoneNumber adaptedPhoneNumber) throws Exception { PhoneNumber phoneNumber = phoneNumberMap.get(adaptedPhoneNumber.id); if(null != phoneNumber) { return phoneNumber; } phoneNumber = adaptedPhoneNumber.getPhoneNumber(); phoneNumberMap.put(phoneNumber.getId(), phoneNumber); return phoneNumber; } } Demo To ensure the same instance of the XmlAdapter is used for the entire marshal and unmarshal operations we must specifically set an instance of the XmlAdapter on both the Marshaller and Unmarshaller: package forum7587095; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Customer.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setAdapter(new PhoneNumberAdapter()); File xml = new File("src/forum7587095/input.xml"); Customer customer = (Customer) unmarshaller.unmarshal(xml); System.out.println(customer.getPhoneNumbers().get(0) == customer.getPhoneNumbers().get(2)); System.out.println(customer.getPhoneNumbers().get(3) == customer.getPhoneNumbers().get(4)); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setAdapter(new PhoneNumberAdapter()); marshaller.marshal(customer, System.out); } } Output true true <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customer> <phone-number id="A"> <number>555-AAAA</number> </phone-number> <phone-number id="B"> <number>555-BBBB</number> </phone-number> <phone-number id="A"/> <phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W"> <number>555-WORK</number> <extension>1234</extension> </phone-number> <phone-number xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="work-phone-number" id="W"/> </customer> For More Information * *http://blog.bdoughan.com/2011/09/mixing-nesting-and-references-with.html *http://blog.bdoughan.com/2010/10/jaxb-and-shared-references-xmlid-and.html *http://blog.bdoughan.com/search/label/XmlAdapter *http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html *http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7587095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android tab bar view overlapping? My question is regarding android tab bar. I have created tab bar in a separate activity and on default first tab view, I am showing layout of an activity. Now when I use tab bar in any other activity, the activity's layout overlapped the tab bar view. Error in catlog is "couldn't save which view to show...". What is the way to show tab bar view along with the activity's view. thanks in advance. A: If you re taking about an action bar overlapping with the view; you can add android:layout_marginTop="?android:attr/actionBarSize" to your layout to "push" the view down under the action bar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Counting Total Time but resetting total if large gap I have a table containing device movements. MoveID DeviceID Start End I want to find out if there is a way to sum up the total movement days for each device to the present. However if there is a gap 6 weeks bewtween an end date and the next start date then the time count is reset. MoveID DeviceID Start End 1 1 2011-1-1 2011-2-1 2 1 2011-9-1 2011-9-20 3 1 2011-9-25 2011-9-28 The total for device should be 24 days as because there is a gap of greater than 6 weeks. Also I'd like to find out the number of days since the first movement in the group in this case 28 days as the latest count group started on the 2011-9-1 I thought I could do it with a stored proc and a cursor etc (which is not good) just wondered if there was anything better? Thanks Graeme A: create table #test ( MoveID int, DeviceID int, Start date, End_time date ) --drop table #test insert into #test values (1,1,'2011-1-1','2011-2-1'), (2,1,'2011-9-1','2011-9-20'), (3,1,'2011-9-25','2011-9-28') select a.DeviceID, sum(case when datediff(dd, a.End_time, isnull(b.Start, a.end_time)) > 42 /*6 weeks = 42 days*/ then 0 else datediff(dd,a.Start, a.End_time)+1 /*we will count also the last day*/ end) as movement_days, sum(case when datediff(dd, a.End_time, isnull(b.Start, a.end_time)) > 42 /6 weeks = 42 days/ then 0 else datediff(dd,a.Start, a.End_time)+1 /we will count also the last day/ end + case when b.MoveID is null then datediff(dd, a.Start, a.End_time) + 1 else 0 end) as total_days from #test a left join #test b on a.DeviceID = b.DeviceID and a.MoveID + 1 = b.MoveID group by a.DeviceID Let me know if you need some explanation - there can be more ways to do that... A: DECLARE @Times TABLE ( MoveID INT, DeviceID INT, Start DATETIME, [End] DATETIME ) INSERT INTO @Times VALUES (1, 1, '1/1/2011', '2/1/2011') INSERT INTO @Times VALUES (2, 1, '9/1/2011', '9/20/2011') INSERT INTO @Times VALUES (3, 1, '9/25/2011', '9/28/2011') INSERT INTO @Times VALUES (4, 2, '1/1/2011', '2/1/2011') INSERT INTO @Times VALUES (5, 2, '3/1/2011', '4/20/2011') INSERT INTO @Times VALUES (6, 2, '5/1/2011', '6/20/2011') DECLARE @MaxGapInWeeks INT SET @MaxGapInWeeks = 6 SELECT validTimes.DeviceID, SUM(DATEDIFF(DAY, validTimes.Start, validTimes.[End]) + 1) AS TotalDays, DATEDIFF(DAY, MIN(validTimes.Start), MAX(validTimes.[End])) + 1 AS TotalDaysInGroup FROM @Times validTimes LEFT JOIN @Times timeGap ON timeGap.DeviceID = validTimes.DeviceID AND timeGap.MoveID <> validTimes.MoveID AND DATEDIFF(WEEK, validTimes.[End], timeGap.Start) > @MaxGapInWeeks WHERE timeGap.MoveID IS NULL GROUP BY validTimes.DeviceID
{ "language": "en", "url": "https://stackoverflow.com/questions/7587098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: KnownType attribute on a property during model binding in MVC? Lets say I have the class Food and a class BirdFood that derives from Food: public class Food { ... } public class BirdFood : Food { public int SeedCount { get; set; } } And lets say I have a class Creature and a class Bird that derives from Creature public class Creature { public Food Food { get; set; } } public class Bird : Creature { ... } And finally, lets say I have a view model for Creature: public class ViewModel { public Creature Creature { get; set; } } When I create an instance of Bird, I also create an instance of BirdFood and assign it to the Food property and pass the view model to the View. Simple enough. public ActionResult Index() { ViewModel viewModel = new ViewModel(); viewModel.Creature = new Bird(); viewModel.Creature.Food = new BirdFood() { SeedCount = 100 } ; return View(viewModel); } And the view: <% using(Html.BeginForm("Save", "Home", FormMethod.Post)) { %> <%: Html.Hidden("Creature.Food.SeedCount", (Model.Creature.Food as MvcApplication6.Controllers.BirdFood).SeedCount) %> <input type="submit" /> <% } %> Okay, here is the problem. When the view model is received in the Action, the Creature property is of the base class Creature instead of the derived type Bird with the SeedCount property of the derived type BirdFood with the post parameters (from firebug) that looks like Creature.Food.SeedCount 100 Okay, my questions is, how do I preserve the derived types when model binded? I'm suspecting it has to do with a custom Model Binder but I'm clueless when it comes to that. Any ideas? A: The default model binder simply inspects the types in your view model and uses those classes. He cannot guess that you want some derived class. A custom model binder could be used to provide such hint. And here's another one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Routing Error in Rails 3 I'm upgrading my application running on Jruby 1.4 & rails 2.3 to Rails 3.1.0 and jruby 1.6. I followed the Rails 3 upgrade Handbook by Jeremy, and using the plugin rails_upgrade, but when I fire the server I'm getting errors. like Routing Error cannot load Java class com.mysentry.persistence.HibernateUtil Somebody please help me. This is the error log Started GET "/admin/login/en/sentry" for 127.0.0.1 at Wed Sep 28 13:13:56 -0400 2011 ActionController::RoutingError (cannot load Java class com.mysentry.persistence. HibernateUtil): org/jruby/javasupport/JavaClass.java:1204:in `for_name' org/jruby/javasupport/JavaUtilities.java:34:in `get_proxy_class' C:/upgrade/jruby-1.6.4/lib/ruby/site_ruby/shared/builtin/javasupport/core_ext/ object.rb:46:in `java_import' C:/upgrade/jruby-1.6.4/lib/ruby/site_ruby/shared/builtin/javasupport/core_ext/ object.rb:26:in `include_class' lib/sentry/interceptor/transaction_interceptor.rb:5:in `Interceptor' lib/sentry/interceptor/transaction_interceptor.rb:2:in `Sentry' lib/sentry/interceptor/transaction_interceptor.rb:1:in `(root)' org/jruby/RubyKernel.java:1038:in `require' polyglot (0.3.2) lib/polyglot.rb:63:in `require' activesupport (3.1.0) lib/active_support/dependencies.rb:240:in `require' activesupport (3.1.0) lib/active_support/dependencies.rb:223:in `load_dependen cy' activesupport (3.1.0) lib/active_support/dependencies.rb:640:in `new_constants _in' activesupport (3.1.0) lib/active_support/dependencies.rb:639:in `new_constants _in' activesupport (3.1.0) lib/active_support/dependencies.rb:223:in `load_dependen cy' activesupport (3.1.0) lib/active_support/dependencies.rb:240:in `require' lib/sentry/interceptor/transaction_interceptor.rb:7:in `Dispatcher' lib/sentry/dispatcher/application_dispatcher.rb:3:in `Sentry' lib/sentry/dispatcher/application_dispatcher.rb:2:in `(root)' org/jruby/RubyKernel.java:1038:in `require' polyglot (0.3.2) lib/polyglot.rb:63:in `require' A: I suspect that you have jar files, including a hibernate jar, in lib or some other folder that was autoloaded by Rails 2.3 have a look at http://hemju.com/2010/09/22/rails-3-quicktip-autoload-lib-directory-including-all-subdirectories/ You may still need to include the requires descibed by jens in his comment. A: At last I found the solution, In windows we need to load the classes first then the jar files. like (This is really strange!) set CLASSPATH = %<project_name>%\classes;%<project_name>%\lib\java\ant-antlr-1.6.5.jar;.... Apart from we need to include the class include_class '<your class>.persistence.HibernateUtil' Thanks for all the help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Python's DictReader class in the csv library? I'm getting to grips with my first Python project and have got pretty stumped trying to use Python's csv.DictReader class to consume a CSV file. Code is as follows: import os import csv f = open('MyCsvFile.txt', 'rb') d = csv.Sniffer().sniff(f.read(1024), ',') csvDict = csv.DictReader(csvfile = f, dialect = d) for line in csvDict: print line['Balance Date '] The csv file roughly looks like this: "Balance Date ","Currency Code ","Main Account","Balance Float - 1 Day",... forty more fields "09/01/2011","EUR","4000519"," .00",... "09/01/2011","GBP","4000519"," .00",... "09/01/2011","JPY","4000519"," .00",... Python is not liking my use of DictReader g:\work\csvtest>python csvtest.py Traceback (most recent call last): File "csvtest.py", line 6, in <module> csvDict = csv.DictReader(csvfile = f, dialect = d) TypeError: __init__() takes at least 2 arguments (2 given) Could someone point me in the right direction? A: You need to pass the csvfile as a positional argument, not as a keyword argument: csvDict = csv.DictReader(f, dialect = d) A: According to the code supplied in the documentation, this would work better: with open('MyCsvFile.txt', 'rb') as source: dialect = csv.Sniffer().sniff(source.read(1024), ',') source.seek(0) csvDict = csv.DictReader(source, dialect)
{ "language": "en", "url": "https://stackoverflow.com/questions/7587105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook App Wall Posting no longer showing in Facebook iPhone App I use the GRAPH API with django for Facebook wall postings. Since yesterday, the wall posts only show on the Facebook web app but not the Facebook iPhone app. I tried Yelp, and their postings still show up. How can I debug this? Anyone notice this issue with their Facebook connect? Is this a Facebook algorithm issue. Code for Wall Post: graph = facebook.GraphAPI(access_token) attachment = {"name": name, "link": link, #"caption": "{*actor*} posted a new review", "description": desc, "picture": picture } graph.put_wall_post("",attachment) A: I have the same problem. I am writing an iPhone app in Objective C and my post code uses the FBStreamDialog box to prompt for input and then post to a news feed. So, it appears the problem is more likely to be a Facebook problem rather than a coding problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Basic user-input string validation I have been writing a check in a name property of my person abstract class. The problem that i have is that i am trying to implement a piece of code that will not allow the user to leave the field empty or to exceed the name limit with 35characters or in-put a digit but i am stuck with it. If any one can help or suggest me. public string Name { get { return name; } set { while (true) { if (value == "" || value.Length > 35) { Console.Write("Please Enter Correct Name: "); value = Console.ReadLine(); continue; } foreach (char item in value) { if (char.IsDigit(item)) { Console.Write("Digits Are NotAllowed....\n"); Console.Write("Please Enter Correct Name: "); value = Console.ReadLine(); break; } } break; } name = value; } } A: This sort of validation should be broken up. The setter should only know the various restrictions that it has and throw an exception in the case that an invalid value makes it that far. Do not put user interface code in there. Try something like this: public string Name { get { return name; } set { if (value == "" || value.Length > 35) { throw new ArgumentException("Invalid name length."); } foreach (char item in value) { if (char.IsDigit(item)) { throw new ArgumentException("Digits are not allowed."); } } name = value; } } Then something like this in your console application: bool success = false; while(!success) { try { Console.WriteLine("Please enter a name:"); myObject.Name = Console.ReadLine(); success = true; } catch(ArgumentException ex) { Console.WriteLine(ex.Message); } } A: First of all, never ask for Console input inside of a setter. It is a seriously bad practice. Instead, you should throw an Exception from the setter and let the caller handle that however they need: public string Name { get { return name; } set { if(String.IsNullOrWhiteSpace(value)) throw new ArgumentException("Name must have a value"); if(value.Length > 35) throw new ArgumentException("Name cannot be longer than 35 characters"); if(value.Any(c => char.IsDigit(c)) throw new ArgumentException("Name cannot contain numbers"); name = value; } } You can then catch and handle the Exceptions appropriately in the calling code (which, in your case, would involve re-prompting the user for the input). A: Don't do any form of UI or I/O in a property. public string Name { get { return _name; } set { if (! Regex.IsMatch(value, @"\w{1-35}")) throw new ArgumentException("Name must be 1-35 alfanum"); _name = value; } } The exact regular expression is up for discussion but the best practice: * *do not try to list and reject all the patterns you don't like. Too much possibilities. *accept what you expect (and understand), reject everything else. A: The solution for handling this according to your rules are almost obvious but the thing is, it's better not to put the checking and validating logic in the setter method of a property, you can have a separate class for instance and that class does the validation responsibility for you and you can tell it to do that and then use the result appropriately. In that case you are following "Tell, Don't Ask" rule and also "Single Responsibility Principle" Good Luck A: public string Name { get { return name; } set { name = value; } } public static bool IsNameValid(string name) { if (string.IsNullOrEmpty(name) || name.Length > 35) { return false; } foreach (char item in value) { if (!char.IsLetter(item)) { return false; } } return true; } Finally a code snippet for reading an user input. var yourClassInstance = new YourClass(); string input bool inputRead = false; while(!inputRead) { var input = Console.ReadLine(); inputRead = YourClass.IsNameValid(input); } yourClassInstance.Name = inputRead; A: The short answer for this is to loop while the value is not valid: public string GetName() { String name = String.Null; do { Console.Write("Please Enter Correct Name: "); name = Console.ReadLine(); } while (!ValidateName(name)) } public bool ValidateName(string name) { //String validation routine } That being said, as I'm sure you will see from other answers, change where the Name is given. As a general rule, accessors are really just for "getting" and "setting" quickly what's in a class. A: I would create a method for changing the name that contains the validation logic. If you want to check the name is valid, so you don't have to handle the argumentexception do a check first, call IsValidName before calling ChangeName public class Person { public void ChangeName(string name) { if (!IsValidName(name)) { throw new ArgumentException(....); } else this.Name = value; } public bool IsValidName(string name) { // is the name valid using } public string Name { get; private set; } } And to use it var newName = Console.ReadLine(); var person = new Person(); while (!person.IsValidName(newName)) { newName = Console.ReadLine(); } person.ChangeName(newName); A: From a semantics point of view, a setter is as its name says, a setter! It should be used to set a private/protected field of a class From a testability point of view, your design is very hard to be automatically tested not to say impossible! This reminds me of a bit of code I worked on sometime ago where a setter is opening a socket and sending stuff over the network! The code should do what it reads, just imagine if someone uses your code, calls your setter and wonders why on earth does his/her application hang (waiting for user input) The way I see your code more readable and testable is to have a verifer class that ensures the user is entering the right data in the right format. The verifier should take an input stream as data source, this will help you easily test it. Regards, A: Aside from what Mr Skeet said, seems like you should replace this break with a continue in order to validate the new value (like you do in your first length check): if (char.IsDigit(item)) { Console.Write("Digits Are NotAllowed....\n"); Console.Write("Please Enter Correct Name: "); value = Console.ReadLine(); continue; //here }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Get the total width of a string rendered with an arbitrary .ttf font in Java Graphics 2 Currently we attempt to get the width of a string rendered with an arbitrary font. BufferedImage img = new BufferedImage(10, 10, BufferedImage.TRANSLUCENT); img.createGraphics(); Graphics2D g = (Graphics2D) img.getGraphics(); g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); FontMetrics metrics = g.getFontMetrics(font); // get the height of a line of text in this font and render context int hgt = metrics.getHeight(); // get the advance of my text in this font and render context int adv = metrics.stringWidth(text); // calculate the size of a box to hold the text with some padding. //Dimension dim = new Dimension(adv + 2, hgt + 2); The problem is with this line... int adv = metrics.stringWidth(text); For most fonts this works but for some fancier script fonts it seems to break being less wide than we expected. As per the javadoc for FontMetrics.stringWidth you can even read... Returns the total advance width for showing the specified String in this Font. The advance is the distance from the leftmost point to the rightmost point on the string's baseline. Note that the advance of a String is not necessarily the sum of the advances of its characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I Have A project developed using XCode on MAC OS,How Could I build it On Linux? I Have A project developed using XCode on MAC OS, for some special reason, I want copy entire project to the Linux operating system and go on developing on linux. How can I develop and build it on Linux? I am developing an I-Phone project, I using iOS libraries, I (wish to) develop and build on linux, run on iphone A: No, it is not currently possible to build Native iOS applications using the native Cocoa Libraries and Objective-C on platforms other than Mac OS X. A: You have two issues. First, are you using OS X only libraries, for example Foundation or AppKit? You could potential develop a Cocoa program on OS X and build it against OpenStep on Linux, but at this point you would need to be very selective in which functionality you use, to the point where it is probably impossible. Assuming that you have fully cross-platform code, then yes you can build it on Linux, but you will need to move away from the Xcode build system. You can create an Xcode project using an external build system, and then proceed to use something like scons, ccmake, or even make. That way the same build files with work both on OS X and Linux. Or you can continue to use the Xcode build system on OS X and keep a parallel build tool for use on Linux.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why might a full-text search not return short words even if ft_min_word_len has been lowered? In my MySQL configuration I've set ft_min_word_len = 2 and rebuilt the index with a quick repair. Is there anything else I need to do in order to be able to search for short (3 letter) words? EDIT: This query SELECT *, match(`Tournament`.`Name`) against ('aaa') as score, `Tournament`.`id` FROM `tournie`.`tournaments` AS `Tournament` WHERE 1 = 1 GROUP BY `Tournament`.`id` having score > 0.1 ORDER BY `score` desc LIMIT 20 returns 0 records despite the existence of a record with that exact name - "aaa". I've also tried others, such as "bag" and (a classic) "bum". A: Did you also restart mysql after making the change? You need to restart and rebuild your indexes. Also remember that if what you are searching on appears in more than 50% of the records, mysql won't return anything. This makes testing with 10 records difficult. A: Please make sure that you added ft_min_word_len = 2 in 1 #Vi etc/my.cnf [mysqld] ft_min_word_len = 2 after that #service mysqld restart #rebuild your index
{ "language": "en", "url": "https://stackoverflow.com/questions/7587120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Control.Invoke() in place of lock(Control) I am working on a multi-threaded application which needs to update a Winforms control as it progresses (A DataGridView). In order to prevent multiple access to the same shared resource, I started out with the following lock structure: if (DGV.Columns.Count >= DesiredColumnCount) return; lock(DGV) { while (DGV.Columns.Count < DesiredColumnCount) { DGV.Columns.Add(newColumn); } } I then realized that, since the DGV was created on the UI thread, it needs to be .Invoke()'d. This changes the code to: if (DGV.Columns.Count >= DesiredColumnCount) return; lock(DGV) { DGV.Invoke(new MethodInvoker(() => { while (DGV.Columns.Count < DesiredColumnCount) { DGV.Columns.Add(newColumn); } } } My question is: Isn't this redundant? the lock will block the worker thread until it has exclusive access to DGV, and the Invoke() will block the worker thread until the UI thread can pick up the invoke request and execute the code. Can't I just get by using only the Invoke()? (That is the main question. Of course if there are any other multithreading sins in the above code, please comment) A: It is a bit redundant, the Invoke call will "dispatch" the operpation to the UI thread. Each subsequent Invoke call will be dispatched in a serial fashion, so there isn't really any need to do any locking. You may consider using BeginInvoke instead of Invoke order to prevent the worker thread from blocking, but again, that will be done "serially" so there is no need to worry about locking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: .NET 4.5 Metro Application DependencyProperty I cant get DependencyProperty.Register to work. It requires (string, string, string, PropertyMetadata) instead of string, Type, Type, UIPropertyMeatdata)... I changed the UI-PropertyMetadata part but can't get string part of it to work. I tried typeof(T).ToString() and just "T" but it doesn't work. My code looks like this public ObservableCollection<RingSegment> RingSegments { get { return (ObservableCollection<RingSegment>)GetValue(RingSegmentsProperty); } set { SetValue(RingSegmentsProperty, value); } } public static readonly DependencyProperty RingSegmentsProperty = DependencyProperty.Register( "RingSegments", typeof(ObservableCollection<RingSegment>), typeof(MainPage), new PropertyMetadata(new ObservableCollection<RingSegment>())); And errors that i get Error 1 The best overloaded method match for 'Windows.UI.Xaml.DependencyProperty.Register(string, string, string, Windows.UI.Xaml.PropertyMetadata)' has some invalid arguments C:\Users\aleksandar.toplek\documents\visual studio 11\Projects\Project - XX\XX\MainPage.xaml.cs 21 68 XX Error 2 Argument 2: cannot convert from 'System.Type' to 'string' C:\Users\aleksandar.toplek\documents\visual studio 11\Projects\Project - XX\XX\MainPage.xaml.cs 22 20 XX Error 3 Argument 3: cannot convert from 'System.Type' to 'string' C:\Users\aleksandar.toplek\documents\visual studio 11\Projects\Project - XX\XX\MainPage.xaml.cs 22 63 XX -- EDIT -- When I do this public static readonly DependencyProperty RingSegmentsProperty = DependencyProperty.Register( "RingSegments", "ObservableCollection<RingSegment>", "MainPage", new PropertyMetadata(new ObservableCollection<RingSegment>())); Code compiles but throws exception in runtime A first chance exception of type 'System.TypeInitializationException' occurred in mscorlib.dll in file XamplTypeIngo.g.cs System.TypeInitializationException was unhandled by user code Message=The type initializer for 'XX.MainPage' threw an exception. Source=mscorlib TypeName=XX.MainPage StackTrace: at System.Runtime.CompilerServices.RuntimeHelpers._RunClassConstructor(RuntimeType type) at System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(RuntimeTypeHandle type) at Disk_Visualizer.XamlTypeInfo.XamlUserType.RunInitializer() in c:\Users\aleksandar.toplek\Documents\Visual Studio 11\Projects\Project - XX\XX\obj\Debug\XamlTypeInfo.g.cs:line 277 InnerException: System.NullReferenceException Message=Object reference not set to an instance of an object. Source=Windows.UI.Xaml StackTrace: at Windows.UI.Xaml.DependencyProperty.Register(String name, String propertyTypeName, String ownerTypeName, PropertyMetadata typeMetadata) at Disk_Visualizer.MainPage..cctor() in c:\Users\aleksandar.toplek\Documents\Visual Studio 11\Projects\Project - XX\XX\MainPage.xaml.cs:line 21 InnerException: ... A: you can find the solution for this problem on Dependency Property declaration MSDN link A: OK. After observing a little more, I noticed, just as Aleksandar Toplek pointed out, it is the XamlTypeInfo.g.cs code responsible for instantiating types. It uses the IXamlType CreateXamlType method for BOTH XAML defined types and discovering defined Dependency Properties. I noticed this when I change my SelectedUser DP type from User to string. I also noticed one of my converters in this switch implementation. I figured it picked it up when I declared it in my resources. So I experimented: I referenced the namespace to my custom class: xmlns:model="using:AccountManagement.Model" I added a sample model to "register" this type into XamlTypeInfo.g.cs implementation: <!--Sample Model--> <model:User x:Key="sampleUser"/> // Generates the following case in CreateXamlType case "AccountManagement.Model.User": userType = new XamlUserType(this, typeName, typeof(AccountManagement.Model.User), GetXamlTypeByName("Windows.Foundation.Object")); userType.Activator = Activate_1_User; xamlType = userType; break; I run my code and the type for my DP is recognized and instantiated. That's only the first part. On my dependency property I have a CallBack to invoke some logic upon selection. public static readonly DependencyProperty SelectedUserProperty = DependencyProperty.Register("SelectedUser", typeof(User).FullName, typeof(UsersView).FullName, new PropertyMetadata(null, OnSelectedUserChanged)); I set up my bindings: <GridView ... SelectedItem="{Binding SelectedUser, ElementName=root}" /> <!--root being my UserControl (x:Name="root")--> But this did not invoke the CallBack. :(. I eventually got it working using a handler that assigns the dp, and at that assignment it does trigger the callback. This confirms that the DP was properly registered with the proper type. Getting the binding to work the way I expect it to work, is my next challenge. Hope this helps, Andres Olivares A: We don't have support for the Custom Type property declaration in WinRT C#. But you can try this workaround. This may solve the problem. public static readonly DependencyProperty RingSegmentsProperty = DependencyProperty.Register( "RingSegments", "ObservableCollection<"Object>", "MainPage", new PropertyMetadata(new ObservableCollection<"Object>()) A: I am also running into issues declaring a dependency property for a UserControl. Tried this: public static readonly DependencyProperty SelectedUserProperty = DependencyProperty.Register("SelectedUser", typeof(User).FullName, typeof(UsersView).FullName, new PropertyMetadata(default(User), OnSelectedUserChanged)); Where User is a custom class and UsersView is a UserControl, but still get the following error: A first chance exception of type 'System.NullReferenceException' occurred in accountreader.exe Additional information: Object reference not set to an instance of an object. Hope this helps, Andres Olivares A: Passing "Object" as propertyTypeName helped in my case public static readonly DependencyProperty MyProperty = DependencyProperty.Register("My", "Object", typeof(MyControl).FullName, new PropertyMetadata(null));
{ "language": "en", "url": "https://stackoverflow.com/questions/7587134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get UIView to overlay UIScrollView as a footer I have a UIScrollView with an image that needs to be scalable. I want to have a "footer" with a black (opaque) background and white text. I wanted to have it be fixed as a footer. It will be opaque so you can see the image behind it. I created a containing UIView for the scrollview and footer. I can get the scrollview to be smaller than the app frame and have a footer at the bottom filling in the extra space, but obviously I can't see the image behind the footer. I also tried putting the UIScrollView and UIView (footer) inside the container and positioning them accordingly, but in this case I can't even see the footer. Any ideas? Code I've gotten so far (executed in viewDidLoad of view controller): CGRect appFrame = [[UIScreen mainScreen] applicationFrame]; UIView* view = [[UIView alloc] initWithFrame:appFrame]; view.backgroundColor = [UIColor blackColor]; CGRect scrollViewFrame = CGRectMake(0.0, 0.0, view.frame.size.width, view.frame.size.height - 100); UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:scrollViewFrame]; [scrollView setCanCancelContentTouches:NO]; scrollView.clipsToBounds = YES; scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite; [scrollView addSubview:imageView]; [scrollView setContentSize:CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)]; scrollView.minimumZoomScale = 0.7; scrollView.maximumZoomScale = 5; scrollView.delegate = self; [scrollView setScrollEnabled:YES]; UIView* textView = [[UIView alloc] initWithFrame:CGRectMake(0.0, scrollViewFrame.size.height, appFrame.size.width, 100)]; // Red for testing purposes textView.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5]; [view addSubview:scrollView]; [view addSubview:textView]; self.view = view; A: I have plenty of UIScrollViews with a small non-scroll view at the bottom or the top. In most cases I don't have any overlap, and they just sit side-by-side. I create them all in InterfaceBuilder, and assign them to IBOutlets. A: I assume that with "image" you mean that there is an UIImage in the scroll view, and that you want to see it through a half transparent footer view. In this case you should not put the views beneath each other, but the footer view on top of the scroll view. You can insure it is on top by calling bringSubviewToFront or using [containerView insertSubview:footer atIndex:0]; instead of addSubview:. Another caveat might be that you call your view view. There might be some unpredictable behavior about which view it is, so perhaps it is better to call it something else and then assign it to self.view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS - how to save hyperlinks in sqlite? How to save hyperlinks in sqlite. I tried saving it as a string but something like this has been saved in my column - HYPERLINK "HYPERLINKHYPERLINKwwwHYPERLINK.HYPERLINKyoutubeHYPERLINK.HYPERLINKcomHYPERLINK/HYPERLINKwatchHYPERLINK?HYPERLINKvHYPERLINK=HYPERLINKurHYPERLINK_HYPERLINKairHYPERLINK_HYPERLINKPcWo is there any special way to treat hyperlinks in iOS development. I am a newbie in iOS world so any help would be appreciated. Thanks. A: Thats a bit random, but you can always remove the hyperlinks to get the URL from that string: columnStringVar = [columnStringVar stringByReplacingOccurancesOfString:@"HYPERLINK" withString:@""];
{ "language": "en", "url": "https://stackoverflow.com/questions/7587146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is this error message about implicitly deleted virtual destructors? I've just updated GCC from (I think) 4.5.6 to 4.6.1, under Windows, MinGW. Suddenly my NonInstantiable base class (from which you inherit with public virtual to prevent instantiation) refuses to work with the following and similar error messages: #ifndef Frigo_Lang_NonInstantiable #define Frigo_Lang_NonInstantiable namespace Frigo { namespace Lang { /** * Inherit from this class if you want to make a non-instantiable class. Most * useful for static classes. It seems every inheritance combination * (public/protected/private, non-virtual/virtual) shuts off instantiation in * all subclasses as well. **/ class NonInstantiable { private: /* Private Classes */ /** * A dummy class to prevent GCC warnings about virtual * constructors/destructors and no friends **/ class NonInstantiableDummy { }; /* Private Constructors */ /** * Private constructor to prevent instantiation **/ NonInstantiable() { } /** * Private destructor to prevent instantiation on the stack. Virtual to * prevent GCC warnings **/ virtual ~NonInstantiable() { } /* Friends */ friend class NonInstantiableDummy; }; } } #endif Errors: /code/Frigo/Util/Arrays:40:7: error: deleted function 'virtual Frigo::Util::Arrays::~Arrays()' /code/Frigo/Lang/Object:37:11: error: overriding non-deleted function 'virtual Frigo::Lang::Object::~Object()' /code/Frigo/Util/Arrays:40:7: error: 'virtual Frigo::Util::Arrays::~Arrays()' is implicitly deleted because the default definition would be ill-formed: /code/Frigo/Lang/NonInstantiable:39:11: error: 'virtual Frigo::Lang::NonInstantiable::~NonInstantiable()' is private /code/Frigo/Util/Arrays:40:7: error: within this context /code/Frigo/Lang/NonInstantiable:39:11: error: 'virtual Frigo::Lang::NonInstantiable::~NonInstantiable()' is private /code/Frigo/Util/Arrays:40:7: error: within this context /code/Frigo/Util/Arrays:40:7: error: deleted function 'virtual Frigo::Util::Arrays::~Arrays()' /code/Frigo/Lang/NonInstantiable:39:11: error: overriding non-deleted function 'virtual Frigo::Lang::NonInstantiable::~NonInstantiable()' I suspect it is because I do not create any destructors, virtual or otherwise, in the child classes, and this somehow conflicts with the private virtual destructor of NonInstantiable, but I need confirmation. And a solution how to fix my NonInstantiable class to suppress these errors, but still work. A: Parent destructors always need to be callable from a child class (because this happens automatically) and so parent class destructors can't be private. Just make your NonInstantiable's destructor protected. Also note that a child class could circumvent the parent as written by explicitly (accidentally?) calling into its public compiler-generated copy constructor. EDIT: I should add as an aside that you might want to consider your need for a non-instantiable class here. I personally believe that a combination of free functions and anonymous-namespace variables would be a cleaner way of doing this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: IOS String issues. one works, one doesn't, what gives? from the .h NSString *_maplink; @property (nonatomic, retain) NSString *mapLink; in the .m this one is fine NSString *link = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,+%f&daddr=thatCity+thatState+515+north+state+street", latitude, longitude]; i need the property later so i'm mapLink = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,+%f&daddr=thatCity+thatState+515+north+state+street", latitude, longitude]; then i NSLog(@"the map link %@", mapLink); in a different function and I get the ole SIGABRT. what's the dilly o? A: Simply assigning your string to the mapLink variable won't retain it. You need to: self.mapLink = [NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,+%f&daddr=thatCity+thatState+515+north+state+street", latitude, longitude];
{ "language": "en", "url": "https://stackoverflow.com/questions/7587155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I set a static variable that can be accessed by all subclasses of the same base class (Perl/Moose)? Since Perl/Moose always calls the base class' BUILD function before it calls the subclass BUILD function, there is a new instance of the base class everytime you instantiate a subclass. How do I go about creating a static variable that can be used by all the subclasses, or alternatively how can I create a static base or abstract class? (does that approach even make sense?) I'm trying to create a variable that dynamically enables or disables certain features of a function defined at run-time in the base class but accessible from the sub classes. So if I do something like my obj = My::childObject_1->new( 'use_my_var' => 1 ); it will also be true for my obj2 = My::childObject_2->new(); my obj3 = My::childObject_3->new(); without having to specifically define that variable. Unless my obj4 = My::childObject_2->new( use_my_var' => 0 ); in which case it would from that point be false for all subclasses because they all extends My::BaseObject Additionally, is there a design pattern that describes this behavior? (Note: I'm on a shared system so I can't install MooseX -- or at least I haven't been able to figure out how to setup local PERL5LIB installs of modules in my user directory =/ so Moose-only solution helps for now!) A: UPDATE Now there is a much better way to do this, use MooseX::ClassAttribute Then just use class_has rather than has for the methods you want shared with all instances. package My::Class; use Moose; use MooseX::ClassAttribute; class_has 'Cache' => ( is => 'rw', isa => 'HashRef', default => sub { {} }, ); __PACKAGE__->meta()->make_immutable(); OLD Additionally, is there a design pattern that describes this behavior? Yes. It's called a Singleton. A Singleton is a pattern whereby multiple initiations (calls to ->new) will return the same object. You can either do it like this, or store the variable outside of a class. Moose provides a layer that will permit you to create Singletons easily (thought it isn't particularly hard either way): the module MooseX::Singleton. Moose also permits you to delegate to another object by using an accessor. Here we use MooseX::Singleton, and delgation to a hidden attribute to achive the desired effect. package MySingleton; use MooseX::Singleton; has 'foo' => ( is => 'rw', isa => 'Bool', default => 0 ); package ClassA; use Moose; has '_my_singleton' => ( isa => 'MySingleton' , is => 'ro' , default => sub { MySingleton->new } , handles => [qw( foo )] ); package ClassB; use Moose; has '_my_singleton' => ( isa => 'MySingleton' , is => 'ro' , default => sub { MySingleton->new } , handles => [qw( foo )] ); package main; use Test::More tests => 5; my $class_a = ClassA->new; my $class_b = ClassA->new; is( $class_a->foo(0), 0, 'Set A to false' ); is( $class_a->foo, 0, 'A Is false' ); is( $class_b->foo, 0, 'B Is false' ); is( $class_b->foo(1), 1, 'Set B to true' ); is( $class_a->foo, 1, 'A is true' ); Or, without MooseX Please don't do this unless required. The MooseX method is much nicer: package Underclass; use Moose; has 'foo' => ( is => 'rw', isa => 'Bool', default => 0 ); package SingletonWrapper; my $obj; sub new { if ( $obj ) { return $obj; } else { $obj = Underclass->new } } package ClassA; use Moose; has '_my_singleton' => ( isa => 'Underclass' , is => 'ro' , default => sub { SingletonWrapper->new } , handles => [qw( foo )] ); package ClassB; use Moose; has '_my_singleton' => ( isa => 'Underclass' , is => 'ro' , default => sub { SingletonWrapper->new } , handles => [qw( foo )] );
{ "language": "en", "url": "https://stackoverflow.com/questions/7587157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: MVC: Need to pass an list or array of strings from controller to view I need to populate an object in the script section of my mvc page, currently the object looks like this: <script> var disabledDays = ["9-30-2011","2-24-2010","2-27-2010","2-28-2010","3-3-2010","3-17-2010","4-2-2010","4-3-2010","4-4-2010","4-5-2010"]; Now I am trying to pass an array of DateTime objects to the view from the controller, but converting it to strings before I do that. Something like this: <Controller> var blockedDates = new List<string>(); foreach (DateTime closeDate in dealershipInfo.ClosedDates) blockedDates.Add(closeDate.ToString()); ViewBag.BlockedDates = blockedDates; But definitely it is not working for me. What will be the proper way to achieve this kind of a result. A: public ActionResult Index() { var blockedDates = dealershipInfo.ClosedDates.Select(x => x.ToString()).ToList(); return View(blockedDates); } and in the view: @model IEnumerable<string> ... <script type="text/javascript"> var disabledDays = @Html.Raw(Json.Encode(Model)); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7587166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Appending text to a richTextBox in a different thread and code file With the intention of creating a program to interface with a serial port device, I recently started learning vb.net. To keep the structure neat the vb code has been split into two places; the first is the code behind for initialising, clicking buttons etc., whilst the second is for managing the comm port. Respectively, these are named 'MainWindow.xaml.vb' and 'ComPortManager.vb'. In 'comPortManager.vb': Dim RXArray(2047) As Char ' Array to hold received characters Dim RXCnt As Integer ' Received character count Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles comPort.DataReceived Do RXCnt = 0 Do 'Populates the array, RXArray and counts the number of characters, RXCnt Loop Until (comPort.BytesToRead = 0) 'Keeps reading the buffer until it is empty 'Code for posting to the richTextBox Loop Until (comPort.BytesToRead = 0) 'If the buffer has been written to in the meantime, repeat End Sub The 'MainWindow.xaml' contains a ribbon (Microsoft's October 2010 release) with controls for settings, opening, closing and sending (keeping it all separate and simple for now), with the rest of the window being a richTextBox entitled 'RichTextBox1'. The search for a way to post the contents of RXArray to RichTextBox1 brought up many suggestions based around Invoke or BeginInvoke. Indeed, working examples have been run successfully but all the code associated with Invoke has been in one file, the code behind. (Correct me if I'm wrong, but this sounds fine for small programs but could get bloated with medium to larger programs, hence me wanting to find a better solution) The code closest to running (I believe) is as follows: 'In comPort_DataReceived... after populating the array If RichTextBox1.InvokeRequired Then RichTextBox1.Invoke(New MethodInvoker(AddressOf Display)) End If 'and back in the main code Public Delegate Sub MethodInvoker() Private Sub Display() RichTextBox1.AppendText(New String(RXArray, 0, RXCnt)) End Sub This has a few problems and I'm not sure in what direction to go at this stage. RichTextBox1 is in a different thread hence not recognised; InvokeRequired is not a member of System.Windows.Controls.RichTextBox, likewise with Invoke; and finally, in examples, the delegate entitled MethodInvoker was never stated as above. Any help on this topic is most appreciated. In these few weeks, Invoke, BeginInvoke etc. have somewhat eluded my comprehension. Regards, Jonathan A: we have a large scale application which a textbox has the status of many threads appended to it concurrently, and from different forms. this is a dumbed down version of it: Public Sub addToMessageBox(ByVal msg As String) If Me.InvokeRequired Then Dim d As New AddToMessageBoxDelegate(AddressOf Me.addToMessageBox) Me.BeginInvoke(d, New Object() {msg}) Else Try Me.MessageBox.AppendText("--" + msg + vbCrLf) Catch ex As Exception End Try End If End Sub The delegate is declared at the begining Private Delegate Sub AddToMessageBoxDelegate(ByVal msg As String) the biggest difference that I can see is that I use the parent class's beginInvoke() and InvokeRequired(). I'd say give this a try. Call the parentClass.AddToMessageBox("Text you want to append") where you are calling the display().
{ "language": "en", "url": "https://stackoverflow.com/questions/7587172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java cannot find symbol error I have a simple file system, in which all the files being used by the main program are in the same folder. The main program is also in the same system. It was actually a jar file by my friend and then I unzipped it using winrar, the class files are running well, but only when i amended something and tried to compile the program i am getting this error of cannot find symbol for one of the class being used, and its right there in the same folder. How can i resolve this please? Thanks in advance A: You have to place your source files into appropriate subfolders. The name of the folder corresponds to your package name, in this case next. next/Pretty.java next/Tree.java ... Then you can compile using command javac next/*.java from the base directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: delect NSTextField When I use [myNSTextField setStringValue:@"AAA"]; to set the text of a NSTextField the texts always have black background and look likes they have been selected. Is it possible to display the text with black text color and white background color? Welcome any comment A: Ask the text field to resignFirstResponder. That will deselect the view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent directory listing and files for specific user I have a folder (/files) and I have tons of files there that users can download. I want users to be able to download their files only and no be able to see others people file. For example: User A can only view and download: - file1.doc - file2.jpg User B can only view and download: - file3.txt - file4.jpeg User C can only view and download: - file1.doc - file2.jpg - file3.txt My idea was to put all files in the same folder so all users knows where to go. My question is: Can I use .htaccess or should I build a PHP scripts for this? What about security (which one is more secure)? Thanks A: Is it an open directory, to start with? What you could do is create a subfolder for each user, put their files in there and then assign appropriate permissions in .htaccess for said folders. However, this would require some security integration with your OS (i.e., users would have to have accounts on your machine, not just your web application)... A quick and dirty -- and insecure -- alternative would be to prepend all uploaded filenames with the username (e.g., 'file1.jpg' uploaded by 'foobar' could be named 'foobar.file1.jpg', for example), then it's just a case of your PHP script returning only those files with the respective username and perhaps stripping that part out when displaying (or again, you could use folders, as long as your script can create a new folder per user, when one doesn't exist). Another option, which is slightly more secure is to create a hash of the file and usernames in a database, rename all uploaded files with this hash and then query the database appropriately. The best solution would definitely be OS managed accounts, a I first mentioned, but it entails more overhead. A: Build a PHP script where you use readfile to send the file to the browser. This way you can restrict access for individual files, and use the authentication system you already have. A: You can certainly use either htaccess or PHP for this. Neither are more secure, as far as I know, that the other - though done wrong both can permit access where none is intended! PHP might be marginally better, since you have more flexibility (in terms of integrating it with other PHP authentication, say) and you can put the folder outside the usual web root, which is good practise anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: deployment issue in asp.net i'm working on asp.net web application project.Situation is that i want to deploy my project on hosting site but when i try to deploy using vs2010 it get me error saying access denied error 550. i want to know can i deploy on ftp server using package. actually when i unzip and copying all the files of package on server using file upload of host server it done but when i run the site it show runtime error.u can see that error on http://prakash.somee.com/ A: Change your customErrors as your screen shot is telling you, so you can see what the real error is: <configuration> <system.web> <customErrors mode="Off"/> </system.web> </configuration>
{ "language": "en", "url": "https://stackoverflow.com/questions/7587179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Selecting the next instance within a class in jQuery I have a table with alternating rows of course names and course descriptions. Here's some of the html (that I loop through): <tr> <td><a class="course_name_click" href='#'><%= course.name %></a></td> </tr> <tr class="course_descrip" height="200"> <td style="word-wrap: break-word" width="10"><%= course.descrip %></td> </tr> I'd like to make it so that when the user clicks on the course name, the course description slide toggles up and down. But I'm having trouble finding the right selector for the course descrip that appears right after the course name that is clicked. I've tried a bunch of different combinations of $(this) and .next(), but none seems to work. Here's my jquery so far: $('.course_name_click').click(function() { $('tr.course_descrip').slideToggle('slow'); return false; }); As it appears above, clicking on any course name slide toggles every instance of tr.course_descrip. I only want it to slide toggle the instance that appears after the course name that is clicked. A: $('.course_name_click').click(function() { $(this).closest('tr').next().slideToggle('slow'); return false; }); A: This is because $(this).next() gets the next sibling of the <a/> that was clicked, which is nothing. You will have to get it's parent's parent (the <tr/>) and do next on that: $('.course_name_click').click(function() { $(this).parent().parent().next().slideToggle('slow'); return false; }); Here is a jsFiddle of it working. Edit: Matt's answer may make more syntactic sense than doing .parent().parent()
{ "language": "en", "url": "https://stackoverflow.com/questions/7587189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HttpWebRequest.GetResponse failing continuously until program reset Occasionally on some machines, a web request will fail with the following message and continue to do so until the program is reset at which time it will start working again. Has anyone else experienced this and is there any programmatic way to prevent it? Message: The remote name could not be resolved: 'www.validwebsite.com' Source: System StackTrace: at System.Net.HttpWebRequest.GetResponse() EDIT: This is the code the that is being executed virtual public string Execute(string web_uri,string request_method,string data = null, string content_type = null) { WebRequest webRequest = WebRequest.Create(web_uri); webRequest.Method = request_method; if (content_type != null) { webRequest.ContentType = content_type; } webRequest.Method = request_method; byte[] bytes = new byte[0]; if (!string.IsNullOrEmpty(data)) { bytes = Encoding.ASCII.GetBytes(data); // send the Post webRequest.ContentLength = bytes.Length; //Count bytes to send } else { webRequest.ContentLength = 0; } if (webRequest.Method == "POST") { using (Stream os = webRequest.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); //Send it } } using (HttpWebResponse webResponse =(HttpWebResponse)webRequest.GetResponse()) { if (webResponse != null) { ResponseCode = webResponse.StatusCode; using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(),Encoding.UTF8)) { string xml_string = sr.ReadToEnd().Trim(); return xml_string; } } } return null; A: Put an entry in the hosts file to rule out a DNS issue. If your app then works consistently, you found the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best player to stream WMV content - in 64 bits? I just realized that a client is using the JW WMV player to stream a .wmv broadcast. When I visit the page in Firefox it tells me I need to restart firefox in 32bit because the plugin is not available in 64 bits. So I guess the JW WMV player is built on silverlight, which currently only supports 32 bit. My question is this: Is there a better solution to embed a wmv stream on a webpage? Or is it OK just acceptable ask your viewers to restart their browser in 32 bit mode in order to view streaming content? A: You guessed it. There is no 64-bit version of the Silverlight plug-in. Why Microsoft has a 64-bit OS, but not a 64-bit version of their own plug-in, is a mystery. If you are using a 64-bit version of Windows you will need to use the 32-bit version of Internet Explorer to view the video. Both the 64-bit version of IE and the 32-bit version are included with the OS. http://www.microsoft.com/windows/compatibility/windows-7/en-us/Details.aspx?type=Software&p=Microsoft%20Silverlight&v=Microsoft&uid=3&pf=0&pi=0&c=Communication%20%26%20Internet&sc=Web%20Browsers%20%26%20Plug-ins&os=32-bit
{ "language": "en", "url": "https://stackoverflow.com/questions/7587201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is the code I'm using to make .zip files correct? I'm using this code in C# to zip files.. I need to open these files in an Android app (java): String mp3Files = "E:\\"; int TrimLength = mp3Files.ToString().Length; byte[] obuffer; string outPath = mp3Files + "\\" + i + ".zip"; ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream oZipStream.SetLevel(9); // maximum compression foreach (string Fil in ar) // for each file, generate a zipentry { oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength)); oZipStream.PutNextEntry(oZipEntry); if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory { ostream = File.OpenRead(Fil); obuffer = new byte[ostream.Length]; ostream.Read(obuffer, 0, obuffer.Length); oZipStream.Write(obuffer, 0, obuffer.Length); } } oZipStream.Finish(); oZipStream.Close(); I'm having problems in extracting these files in java and I want to make sure the problem isnt from zip files files.. so is this code correct? Can java read these zips? I just tried to create normally using winrar and the file extraction code gives the same problem.. the problem is that "zin.getNextEntry()" is always null: String zipFile = Path + FileName; FileInputStream fin = new FileInputStream(zipFile); ZipInputStream zin = new ZipInputStream(fin); ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { UnzipCounter++; if (ze.isDirectory()) { dirChecker(ze.getName()); } else { FileOutputStream fout = new FileOutputStream(Path + ze.getName()); while ((Unziplength = zin.read(Unzipbuffer)) > 0) { fout.write(Unzipbuffer, 0, Unziplength); } zin.closeEntry(); fout.close(); } } zin.close(); A: Your problem might be due to FileInputStream object's mode. This link (has C# code) states the stream must be readable. Try changing your code according to their recommendation. Posting part of the code from their site: using (var raw = File.Open(inputFileName, FileMode.Open, FileAccess.Read)) { using (var input= new ZipInputStream(raw)) { ZipEntry e; while (( e = input.GetNextEntry()) != null) { A: From the dicussion we've had on this question, the size of your entry is being set to 4294967295, which is the reason you're having a problem with the unzip in java. Try setting the Size: FileInfo fi = new FileInfo(Fil); // added this line here oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength)); oZipEntry.Size = fi.Length; // added this line here oZipStream.PutNextEntry(oZipEntry); Apologies if the syntax is incorrect, this is untested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does my DLL leak when using it in an MFC SDI program using MFC as a DLL in Visual Studio 2010? This may be better directed to Microsoft support, but was wondering if anyone had any ideas as to why this is happening. I created a simple C++ DLL like the following: //simpledll.h class simpledll { public: __declspec(dllexport) simpledll(); __declspec(dllexport) ~simpledll(); } //someheader.h #include <string> const std::string SomeString(L"I'm Leaking"); //simpledll.cpp #include "simpledll.h" #include "someheader.h" //some code to generate memory leak debug messages simpledll::simpledll(){ /*code to register for memory leak debug messages*/} simpledll::~simpledll(){} Next, I make a generic MFC SDI (single document interface) application using the default settings in VS 2010. In MainFrm.h I #include "simpledll.h" and create a member variable: simpledll mSimpleDLL; Here's where it gets interesting. If I compile both the DLL and the MFC application targeting v100 (both using the /MDd switch), simply starting and then closing the application generates a memory leak. If I change the "Use of MFC" setting in the MFC app to use MFC in a static library, the leak goes away. Then, if I recompile the DLL targeting v90 and recompile the MFC app using the DLL version of MFC, no memory leak. Switch the DLL to use v100 and the MFC app to use v90 and no memory leak. In fact, the only combination that seems to generate a memory leak is when both the DLL and the MFC app target v100 and the MFC app is using MFC as a shared DLL. I even tried this with the VS11 developer preview and when targeting v110, everything worked fine. Has anyone run into this issue? Is it limited just to the SDI MFC app in VS2010? What could be causing these leaks? I'm assuming it has something to do with the DLL being terminated prior to calling the destructor of the SomeString constant, but why would using MFC as a DLL affect that? A: I believe it is simply a question of in which order SomeString is initialized versus the call to AfxEnableMemoryTracking() (if I remember correctly). In fact, the memory leak probably happen in the other builds, but SomeString may have been allocated before the memory leak tracking was activated, or it was released before the check happens (unlikely, nothing clear it in the sample). You can try to make the other build to show the leak by assigning a new value to SomeString, with a longuer string to be sure a new memory allocation is done. Do it from the simpledll's constructor. But first, you have to move the string declaration inside simpledll.cpp file, otherwize you get a new instance into each .cpp that include someHeader.h. Edit: It is not specific to MFC, that would happens with any DLL, but as MFC automatically enable the memory leak detection, it become more visible in MFC applications. A: Two-and-one-half years later ... I converted a non-trivial standalone application that did not use MFC to a non-MFC DLL that was intended to be loaded by an MFC program. Everything worked, but the VS 2010 debugger reported endless memory leaks. The clue was that these memory leaks were being reported on exit before the DLL cleanup functions were being called. There is a detailed discussion with an equally detailed and complex solution here: http://www.vis-sim.com/3dsceneBB/viewtopic.php?t=1027 that involves specifying MFC library dependencies. There is however a much simpler solution: * *In Property Pages->Linker->Input, add your DLL filename to "Delay Loaded DLLs". *In the same dialog box tab, add "delayimp.lib" to "Additional Dependencies". A programmatic alternative (along with a discussion of delay-loaded DLL advantages and disadvantages) can be found here: http://www.codeproject.com/Articles/9428/Delay-Loading-a-DLL The advantage here is that the delay-loaded DLL is unloaded before the MFC DLL is unloaded, and so MFC no longer reports false memory leaks. NOTE that this only needs to be done for the DEBUG version your DLL in order to suppress the false memory leak messages. The DLL can still be statically linked in the RELEASE version, thereby avoiding the disadvantages of delay-linked DLLs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: EF 4.1 Update 1 Code First + ASP.NET Membership Provider I watched the “Creating immersive data experiences with Entity Framework “ video from this year’s BUILD conference and wanted to build out a simple application to test out the new features of EF. But, I’d also like to use the ASP.NET Membership Provider for managing users and roles within my app and I am struggling to find a clean way to include it in my code first approach. Do you guys have any recommendations, suggestions, or examples on how this could be done? A: I would recommend looking at the MVC3-Boilerplate project on GitHub as it has a good example of creating a custom membership provider that is implemented using EF Code First. A: I found this NuGet package which has been very useful. Quickstart sample for using Altairis Web Security, Entity Framework and Unity in MVC 3. Super easy membership user/role integration. When using this quickstart, the users and role part of your project is completely setup. You can signup, login, edit roles for users etc. http://www.nuget.org/List/Packages/quickstart.mvc3.unity.ef.altairiswebsecurity A: CodeFirstMembership may be what you are looking for. Features: * *Based on GUID's *Login either by entering Username or Email *Username and Email are unique *Uses nearly all features from SimpleMembershipProvider *Code-First approach *All membership fields can be renamed/changed/localized *Easily extendable (add additional fields) *VB.NET and C# versions available Also, ShoelaceMVC is a great MVC3 starter project that implements CodeFirstMemebership and comes with a nice layout thanks to Twitter's Bootstrap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: VB6 Converting Long to Integer throwing overflow I am trying to convert a long to an integer. I believe the value of the long is low enough to fit in the range on an integer. I have the code: 'mapdc is a long Debug.Print mapdc Debug.Print CInt(mapdc) The first line runs fine. It outputs 1107367444. The second line however causing an overflow error to happen. Any ideas? THANKS!!!! A: A VB6 Integer data type is 16-bits. You are causing an overflow: The value of mapdc is greater than 32,767 which falls outside of the range of values supported by an Integer variable. For more information on VB6 data types see this MSDN page. A: The range of a VB6 Integer type is -32,768 to 32,767. Obviously, your value falls outside of that range and overflows. Data Types - VB 6 tutorial MSDN Confirms by saying that a VB6 Integer corresponds to the .NET type of Int16 which has the same range: Integer Data Type for Visual Basic 6.0 Users A: Int in VB6 is 16 bit (range from -32,768 to 32,767). This link provides a comparison between VB6 with the .Net equivalents
{ "language": "en", "url": "https://stackoverflow.com/questions/7587213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: MS DOS command or Java code to Copy a file are directory from one drive to Multiple Drives? I need to copy a directory from one directory to multiple drives (the drives are external storage devices). After searching I found the MS DOS command xcopy C:\ F:\ /e. This command only copies a file to one drive at a time, it doesn't copy to multiple drives. Is there any way to copy a file from one drive to many drives? A: A small batch file may help to achieve what you need. set src=%~1 :Loop shift set dest=%~1 if "%dest%"=="" goto :EOF xcopy "%src%" "%dest%" /E goto Loop save the code to %SystemRoot%\system32\mcopy.bat, then mcopy some-file e: f:\some-directory g:\some-directory-2 h: i: ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7587214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android accelerometer values inside Flash CS5 Hey am a newbie to Android development. I need an application to test the accelerometer values on my mobile phone. I need the values on my system so that I can manipulate that info for something else. If I write an Android application, the values will be inside the Mobile phone, which is not what I want. I have written an app in Flash, n tested in Adobe Device Central. Only catch is that instead of simulator, I need to test it on my mobile. How do i do this? A: If you are looking to just get the accelerometer data and get it off the phone non-real time, you could download an app like this, https://market.android.com/details?id=pt.acoelhosantos.android.acc -- then get the file off your sd card afterwards. There are several other apps on marketplace that will let you see and or record the data from sensors real time. Or if you are feeling crafty and want to learn a bit about sensor access programming, feel free to read up on the android SensorManager and SensorEventListener, no permissions in android manifest needed! If you plan to implement your own app I recommend handling listening to each sensor in its own thread, you can read up on Threads with Handlers or AsyncTasks for that. I implemented my sensor code as a service that spawns async threads personally, and received updates via intent with broadcastreceiver. This is a great project to learn about threads, intents, services, etc. if you are interested. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7587218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XML POST to Server from iPhone I have an XML that I need to send to another website using PHP. What would be the best way to do this on the iPhone? The XML needs to be formatted based on the selections of the user, then sent to a different server using PHP that is on my server. Any suggestions? A: Disclaimer: I know absolutely nothing about NSURLConnection as @Mat alluded to or how to POST data from an iPhone. how do i format it using PHP so that i can send it to a webserver as an XML? In PHP you can convert the $_POST data to XML by using DOMDocument. The other server most likely also requires you to POST the XML data. In that case you can use cURL A: Just send a regular POST request. NSString* aUrlEncodedString = @"some%20string"; NSString* anotherUrlEncodedString = @"foobar"; NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://example.com/blah.php"]]; request.HTTPMethod = @"POST"; request.HTTPBody = [[NSString stringWithFormat:@"param1=%@&param2=%@", aUrlEncodedString, anotherUrlEncodedString] dataUsingEncoding:NSUTF8StringEncoding]; NSURLResponse* response = nil; NSError* error = nil; NSData* responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
{ "language": "en", "url": "https://stackoverflow.com/questions/7587220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Parse string as non-XML HTML5 without loading descendent-elements There are multiple versions of this question on SO, but none of them really get at the heart of what I'm trying to do. When JavaScript is enabled, the browser sees the contents of the noscript element as unparsed text. I'm using that element to provide all the contents of my site, but for those who do have JavaScript I load the contents with AJAX. …But then I thought, why make the additional request with AJAX when all the contents are in the noscript? I'll try to grab the pieces I need out of the string in the noscript element instead. At first I tried this: do_stuff_with($($("noscript").text())) But I soon found that that method causes the browser immediately to make requests for all the replaced elements (images, etc) within the parsed string. (I assume jQuery adds it to the DOM in order to parse it.) Then I glanced at $.parseXML(), but quickly let that idea go because the markup is not XML (it's HTML5 in non-XML form). Is there some way I can cherry pick elements from the string without making unnecessary HTTP requests? A: I believe there is no way to parse HTML with jQuery, without adding it to the DOM. However, if you're willing to get a little cheesy, you can avoid requesting unwanted/unneeded assets by modifying the noscript source before you parse it. HTML <noscript> <span class="name">Mr. Smith</span> <img src="/images/02938/avatar.jpg" /> <span class="age">27</span> </noscript> jQuery // Load raw content, make sure it's wrapped in a single node raw = '<div>' + $('noscript').text() + '</div>'; // "Fix" any elements that might reference external resources by // turning them into invalid HTML tags. raw = raw.replace(/img/g, 'cheese'); dom = $(raw); // Now we can access our variables without unnecessary resource requests name = dom.find('.name').text(); age = dom.find('.age').text(); A: A colleague of mine who doesn't have or want an SO account described a solution I think is worth documenting here. While it doesn't answer exactly how to parse arbitrary HTML5 without making immediate requests, it is probably the solution I'll go with. Said coworker's suggestion was to put each of my includes in separate noscript elements. So instead of having to parse the entire contents in a single long string, I only parse the elements I'm going to display anyway. In this case if they start loading images and resources at parse-time, it's just fine. It seems so simple now…
{ "language": "en", "url": "https://stackoverflow.com/questions/7587223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using a forward slash as a Scanner delimiter I'm trying to use a Scanner to get a date from the user in MM/DD/YYYY format and using a delimiter / to do so, but as soon as the user inputs data the application ceases to continue. It will work how ever if I simply use the standard space delimiter. Scanner scanner = new Scanner(System.in); scanner.useDelimiter("/"); System.out.print("Birth Date (MM/DD/YYYY) "); birthMonth = scanner.nextInt(); birthDay = scanner.nextInt(); birthYear = scanner.nextInt(); A: Your only delimiter is / not newline. This means you have to type / after the year or add newline as a delimiter. Try scanner.useDelimiter("[/\n]"); A: You have to accept slash and new line characters or the prompt will not return the control to the user. import java.util.Scanner; public class Test { public static void main( String[] args ) { Scanner scanner = new Scanner( System.in ); scanner.useDelimiter( "[/\n]" ); System.out.print( "Birth Date (MM/DD/YYYY) " ); int birthMonth = scanner.nextInt(); int birthDay = scanner.nextInt(); int birthYear = scanner.nextInt(); scanner.close(); System.out.printf( "Day(%02d), Month(%02d), Year(%04d)%n", birthDay, birthMonth, birthYear ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7587224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Form and Request.Form in a asp.net MVC3 Facebook Application I'm working on a facebook app and facing a problem with my forms with MVC3 with Razor. A. Working form: index.cshtml @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.TextBox("tbTest", "Pouet pouet", new { Width = "500px" }) <input type="submit" name="btnCalculate">calculer vos tarifs</input> } Result form : @Request.Form <br /> HomeController.cs: public ActionResult Index() { return View(); } B. Bugging form : About.cshtml : @using (Html.BeginForm("About", "Home", FormMethod.Post)) { @Html.TextBox("tbTest", "Pouet pouet", new { Width = "500px" }) <input type="submit" name="btnCalculate">calculer vos tarifs</input> } Result form : @Request.Form <br /> HomeController.cs : [CanvasAuthorize(Permissions = "user_about_me,manage_pages,offline_access")] public ActionResult About() { var fb = new FacebookWebClient(); FacebookWebClient fbApi = new FacebookWebClient(FacebookWebContext.Current.AccessToken); dynamic result = fb.Get("me"); return View(); } In apps.facebook.com/appname/home/index, the form is working, Request.Form return tbTest = Pouet pouet. In apps.facebook.com/appname/home/about, the form return nothing else but Signed_Request. EDIT If I edit HomeController.cs like this [CanvasAuthorize(Permissions = "user_about_me,manage_pages,offline_access")] public ActionResult Index() { the first page, index.cshtml, does not work anymore... The post only return Signed_Request. So, I think I have a problem using Facebook SDK and Signed request, no ? Could you help me please. Why does the form is not sent or lost in the About page ? A: for post backs you need to maintain the signed request manually. http://facebook.stackoverflow.com/a/5364815/157260 A: Because you have @using (Html.BeginForm("Index", "Home", FormMethod.Post)) in your About form, which causes it to POST to Index instead of About. Change it to @using (Html.BeginForm("About", "Home", FormMethod.Post))
{ "language": "en", "url": "https://stackoverflow.com/questions/7587226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: base language for agency work Coldfusion vs php I have a promotion agency, we develop web pages, mobile web pages, sms messaging and other digital solutions for promotion campaigns that capture data and then provide reporting sites. struggling over whether best to use CF of PHP. With licensing fees off the table, i need to have a scalable process where projects can be turned over to other programmers and/or picked up on the fly when necessary. Also considering switching to cloud based server support. which is best suited for my needs, coldfusion or PHP as the base language? A: Give this a try: https://stackoverflow.com/questions/234296/coldfusion-vs-php In the end it will come down to personal preference. Just make sure you do your research, and don't jump on the first bandwagon that crosses in front of you. A: I"ve worked with both, although I admit I am a ColdFusion developer primarily. CF allows rapid development, has great frameworks, an excellent community of developers, and if you prefer open source you can run Railo or Open Blue Dragon. A: If you have a rolodex with 2 or three quality ColdFusion developers (IE One's that can set up an application layer that supports flex/flash/air apps), you'll find you'll save development time using ColdFusion. If you don't know a few good CF developers, you'll find you have a higher pool of PHP developers on hand when you need them. The development time will be slower comparatively, but you won't struggle as much with head count. In general, it's easier to find PHP hosting then ColdFusion as well if you're considering the cloud approach. In your case I'd suggest PHP to minimize liability, and maximize portability. A: I would go with CF due to ease and speed in development.
{ "language": "en", "url": "https://stackoverflow.com/questions/7587227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fluent Nhibernate - Joining/reference table from two classes I have three classes: Class A { string name IList<AB> list } Class B { name } Class AB { A a B b } Class B exists separate from A. It exists in its own right, and of is part of similar lists in other classes This is why I have the reference table. Problem is, automapper generate schema gives me this schema: A{id, name} B{id, name} AB{id, AFK} WIth regards to the AB schema, I'm expecting BFK in there as well, and I'm not expecting the id field, as it's not needed. It should be a composite PK between AFK and BFK. I'm using automapper, with no overrides at the mo. Please note, I do not want to include IList into my Class B, as it has no place there. Please help - I have been looking all over for the solution to this, and I feel it should be a simple solution. Back when I modelled from ER direct to sql tables this was how I was told to do it if the entities were both strong. A: unfortunately you have to override HasMany(x => x.List) .Component(c => { c.ParentReference(x => x.A); c.References(x => x.B); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7587229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }