text
stringlengths
8
267k
meta
dict
Q: Getting Microsoft PlayReady server to output to Windows Media DRM 10 PD (Portable Devices) Is it possible to get Microsoft PlayReady Server to output DRM'd streams that are playable by Windows Media DRM 10-PD compatible devices? If so, where could I find any relevant documentation? A: It is possible. You need to use so-called "cocktail licenses" and encrypt ASF (i.e. WMV) streams. The relevant documentation is part of the PlayReady Server documentation set, which unfortunately requires you to be a PlayReady Server licensee from Microsoft (you can become a licensee here, but it does cost quite a bit of money). A: PlayReady server will only deliver licenses to PlayReady clients. unfortunately any of the PD clients will not be able to talk to PlayReady Server. A: There are multiple aspects to consider here. I am not sure which one exactly the question is about, so I will cover all of them. First, some background information. There are two types of DRM-protected WMV files: * *WMV files protected with Windows Media DRM *WMV files protected with PlayReady There are also two types of media players: * *Using the Windows Media DRM engine *Using the Playready engine And finally, there are also two types of license servers: * *Windows Media DRM *PlayReady. The compatibility relationships between these are the following: * *Windows Media DRM files can be played in both types of media player. *PlayReady files can be played only in media players using the PlayReady engine. *What sort of licensing server you need depends on the media player, not the file. *Windows Media DRM licensing servers can only create licenses for Windows Media DRM players. *PlayReady licensing servers can only create licenses for media players using the PlayReady engine. Note: I am not familiar with the differences between the different types of Windows Media DRM licenses (Portable VS Network), so there might be additional considerations
{ "language": "en", "url": "https://stackoverflow.com/questions/7635521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: sun.misc.BASE64Decoder showing error in java application In some java file there is a use of : import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; and when I put that java file in Eclipse IDE. It will not detecting these files. But these packages(sun.misc.BASE64Decoder , sun.misc.BASE64Encoder) are inside the rt.jar file. In the library of my project "rt.jar" is available. But why it shows error(red lines in eclipse) ? A: Don't use classes in the sun.misc package. These are deprecated and terrible. Check out Apache commons codec for base64 encoding and decoding. Why not to use sun.misc.* classes A: I wrote the following code for Base64 encoding and decoding: public static String base64Encode(String filename, boolean padding) { char[] base64Chars = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").toCharArray(); FileInputStream dataToEncode; StringBuilder encodedData = new StringBuilder(); byte[] dataBuffer = new byte[3]; int bytesRead; try { dataToEncode = new FileInputStream(filename); } catch (FileNotFoundException fnfe) { System.err.println("File not found!!"); return ""; } try { bytesRead = dataToEncode.read(dataBuffer); // cast to int, to avoid sign issues on the byte int buffer0 = dataBuffer[0] & 0xFF; int buffer1 = dataBuffer[1] & 0xFF; int buffer2 = dataBuffer[2] & 0xFF; if (bytesRead == -1) { System.err.println("Premature END OF FILE (nothing read)!!"); dataToEncode.close(); return ""; } while (bytesRead == 3) { // calculation of the base64 digits int b641 = buffer0 >>> 2; int b642 = ((buffer0 & 0x03) << 4) | (buffer1 >>> 4); int b643 = ((buffer1 & 0x0F) << 2) | (buffer2 >>> 6); int b644 = buffer2 & 0x3F; // generation of the 4 base64 chars, for the 3 bytes encodedData.append(base64Chars[b641]); encodedData.append(base64Chars[b642]); encodedData.append(base64Chars[b643]); encodedData.append(base64Chars[b644]); bytesRead = dataToEncode.read(dataBuffer); buffer0 = dataBuffer[0] & 0xFF; buffer1 = dataBuffer[1] & 0xFF; buffer2 = dataBuffer[2] & 0xFF; } if (bytesRead == 2) { encodedData.append(base64Chars[buffer0 >>> 2]); encodedData.append(base64Chars[((buffer0 & 0x03) << 4) | (buffer1 >>> 4)]); encodedData.append(base64Chars[((buffer1 & 0x0F) << 2)]); // exclude the last byte, that's just 0 if (padding) { // add the '=' character for padding, if the user wants encodedData.append('='); } } else if (bytesRead == 1) { encodedData.append(base64Chars[buffer0 >>> 2]); encodedData.append(base64Chars[((buffer0 & 0x03) << 4)]); if (padding) { encodedData.append("=="); } } dataToEncode.close(); return encodedData.toString(); } catch (IOException e) { System.out.println("Error reading file!!"); return ""; } } public static byte[] base64Decode(String encodedData) { String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // remove padding encodedData = encodedData.split("=")[0]; // create the byte buffer to unpack the bytes into byte[] result = new byte[(int) (encodedData.length() / 4) * 3 + encodedData.length() % 4 - 1]; int readingPosition = 0, writingPosition = 0, b641, b642, b643, b644; while (encodedData.length() - readingPosition > 3) { b641 = base64Chars.indexOf(encodedData.charAt(readingPosition++)); b642 = base64Chars.indexOf(encodedData.charAt(readingPosition++)); b643 = base64Chars.indexOf(encodedData.charAt(readingPosition++)); b644 = base64Chars.indexOf(encodedData.charAt(readingPosition++)); result[writingPosition++] = (byte) ((b641 << 2) | (b642 >>> 4)); result[writingPosition++] = (byte) (((b642 & 0x0F) << 4) | (b643 >>> 2)); result[writingPosition++] = (byte) (((b643 & 0x03) << 6) | b644); } b641 = base64Chars.indexOf(encodedData.charAt(readingPosition++)); b642 = base64Chars.indexOf(encodedData.charAt(readingPosition++)); result[writingPosition++] = (byte) ((b641 << 2) | (b642 >>> 4)); if (encodedData.length() % 4 == 3) { b643 = base64Chars.indexOf(encodedData.charAt(readingPosition++)); result[writingPosition++] = (byte) (((b642 & 0x0F) << 4) | (b643 >>> 2)); } return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic checkBox length in java script I am getting some values from server in XML format using ajax. The format is like : <employees><employee><id>Id</id><employeeName>Name</employeeName></employee>.....</employees> So to process this response i use if(employees.childNodes.length>0){ for (loop = 0; loop < employees.childNodes.length; loop++) { var employee = employees.childNodes[loop]; var ids = employee.getElementsByTagName("id")[0].childNodes[0].nodeValue; var name = employee.getElementsByTagName("employeeName")[0].childNodes[0].nodeValue; s=s+'<input name=\"userAction'+type+'\" id=\"userAction'+type+'\" value=\"'+ids+'\" type=\"checkbox"\/>'+name+'<br\/>'; } document.getElementById('div'+type).innerHTML=s; } I am able to successfully show the no. of users in . But my problem is when i click on submit function i want to know the length of no. of chekboxes. As u see i use the same name of all the checkoxes in a particular div. var lennt=document.frm["userAction"+i].length; alert(lennt) If there were more than 1 user the lenght is ok, but for one user it is giving me "undefined" Please help me... A: The problem you have is if there are no elements named "userAction"+i then document.frm["userAction"+i] is undefined, if there is only 1 then document.frm["userAction"+i] is a reference to one DOM node so there is no length property, if there are > 1, document.frm["userAction"+i] is a reference to a DOMNodeList, so there IS a length property. Solution: do some tests like so: var checkboxes = document.frm["userAction"+i]; var lennt = 0; // default if (checkboxes) { // checkboxes is not undefined // assign value based on whether checkboxes.length is defined lennt = (checkboxes.length) ? checkboxes.length : 1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validate email address textbox using JavaScript I have a requirement to validate an email address entered when a user comes out from the textbox. I have googled for this but I got form validation JScript; I don't want form validation. I want textbox validation. I have written below JScript but "if email invalid it's not returning the same page". function validate(email) { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; //var address = document.getElementById[email].value; if (reg.test(email) == false) { alert('Invalid Email Address'); return (false); } } A: Assuming your regular expression is correct: inside your script tags function validateEmail(emailField){ var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if (reg.test(emailField.value) == false) { alert('Invalid Email Address'); return false; } return true; } in your textfield: <input type="text" onblur="validateEmail(this);" /> A: The result in isEmailValid can be used to test whether the email's syntax is valid. var validEmailRegEx = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*@[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i var isEmailValid = validEmailRegEx.test("Email To Test"); A: function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } To validate email id in javascript above code works. A: Validating email is a very important point while validating an HTML form. In this page we have discussed how to validate an email using JavaScript : An email is a string (a subset of ASCII characters) separated into two parts by @ symbol. a "personal_info" and a domain, that is personal_info@domain. The length of the personal_info part may be up to 64 characters long and domain name may be up to 253 characters. The personal_info part contains the following ASCII characters. * *Uppercase (A-Z) and lowercase (a-z) English letters. *Digits (0-9). *Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~ *Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other. The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots. Example of valid email id mysite@ourearth.com my.ownsite@ourearth.org mysite@you.me.net Example of invalid email id mysite.ourearth.com [@ is not present] mysite@.com.my [ tld (Top Level domain) can not start with dot "." ] @you.me.net [ No character before @ ] mysite123@gmail.b [ ".b" is not a valid tld ] mysite@.org.org [ tld can not start with dot "." ] .mysite@mysite.org [ an email should not be start with "." ] mysite()*@gmail.com [ here the regular expression only allows character, digit, underscore, and dash ] mysite..1234@yahoo.com [double dots are not allowed] JavaScript code to validate an email id function ValidateEmail(mail) { if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w {2, 3})+$/.test(myForm.emailAddr.value)) { return (true) } alert("You have entered an invalid email address!") return (false) } A: This is quite an old question so I've updated this answer to take the HTML 5 email type into account. You don't actually need JavaScript for this at all with HTML 5; just use the email input type: <input type="email" /> * *If you want to make it mandatory, you can add the required parameter. *If you want to add additional RegEx validation (limit to @foo.com email addresses for example), you can use the pattern parameter, e.g.: <input type="email" pattern=".+@foo.com" /> There's more information available on MozDev. Original answer follows First off - I'd recommend the email validator RegEx from Hexillion: http://hexillion.com/samples/ It's pretty comprehensive - : ^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$ I think you want a function in your JavaScript like: function validateEmail(sEmail) { var reEmail = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/; if(!sEmail.match(reEmail)) { alert("Invalid email address"); return false; } return true; } In the HTML input you need to trigger the event with an onblur - the easy way to do this is to simply add something like: <input type="text" name="email" onblur="validateEmail(this.value);" /> Of course that's lacking some sanity checks and won't do domain verification (that has to be done server side) - but it should give you a pretty solid JS email format verifier. Note: I tend to use the match() string method rather than the test() RegExp method but it shouldn't make any difference. A: Are you also validating server-side? This is very important. Using regular expressions for e-mail isn't considered best practice since it's almost impossible to properly encapsulate all of the standards surrounding email. If you do have to use regular expressions I'll usually go down the route of something like: ^.+@.+$ which basically checks you have a value that contains an @. You would then back that up with verification by sending an e-mail to that address. Any other kind of regex means you risk turning down completely valid e-mail addresses, other than that I agree with the answer provided by @Ben. A: If you wish to allow accent (see RFC 5322) and allow new domain extension like .quebec. use this expression: /\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/ * *The '\u00C0-\u017F' part is for alowing accent. We use the unicode range for that. *The '{2,}' simply say a minimum of 2 char for the domain extension. You can replace this by '{2,63}' if you dont like the infinitive range. Based on this article JsFidler $(document).ready(function() { var input = $('.input_field'); var result = $('.test_result'); var regExpression = /\b[a-zA-Z0-9\u00C0-\u017F._%+-]+@[a-zA-Z0-9\u00C0-\u017F.-]+\.[a-zA-Z]{2,}\b/; $('.btnTest').click(function(){ var isValid = regExpression.test(input.val()); if (isValid) result.html('<span style="color:green;">This email is valid</span>'); else result.html('<span style="color:red;">This email is not valid</span>'); }); }); body { padding: 40px; } label { font-weight: bold; } input[type=text] { width: 20em } .test_result { font-size:4em; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="search_field">Input</label> <input type='text' class='input_field' /> <button type="button" class="btnTest"> Test </button> <br/> <div class="test_result"> Not Tested </div> A: <!DOCTYPE html> <html> <body> <h2>JavaScript Email Validation</h2> <input id="textEmail"> <button type="button" onclick="myFunction()">Submit</button> <p id="demo" style="color: red;"></p> <script> function myFunction() { var email; email = document.getElementById("textEmail").value; var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if (reg.test(textEmail.value) == false) { document.getElementById("demo").style.color = "red"; document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email; alert('Invalid Email Address ->'+email); return false; } else{ document.getElementById("demo").style.color = "DarkGreen"; document.getElementById("demo").innerHTML ="Valid Email ->"+email; } return true; } </script> </body> </html> A: <h2>JavaScript Email Validation</h2> <input id="textEmail"> <button type="button" onclick="myFunction()">Submit</button> <p id="demo" style="color: red;"></p> <script> function myFunction() { var email; email = document.getElementById("textEmail").value; var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if (reg.test(textEmail.value) == false) { document.getElementById("demo").style.color = "red"; document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email; alert('Invalid Email Address ->'+email); return false; } else{ document.getElementById("demo").style.color = "DarkGreen"; document.getElementById("demo").innerHTML ="Valid Email ->"+email; } return true; } </script> A: You should use below regex which have tested all possible email combination function validate(email) { var reg = "^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$"; //var address = document.getElementById[email].value; if (reg.test(email) == false) { alert('Invalid Email Address'); return (false); } } Bonus tip if you're using this in Input tag than you can directly add the regex in that tag example <input type="text" name="email" class="form-control" placeholder="Email" required pattern="^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$"/> Above you can see two attribute required & pattern in required make sure it input block have data @time of submit & pattern make sure it input tag validate based in pattern(regex) @time of submit For more info you can go throw doc
{ "language": "en", "url": "https://stackoverflow.com/questions/7635533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: How to change the default enums serialization in Boost.Serialization By default in Boost.Serialization, enum types are serialized as a 32-bit integer. But I need to serialize some enum types as different width integer. I've tried to specialize the boost::serialization::serialize method, but it seems it doesn't work for enums. Here is my attempt: #include <iostream> #include <boost/archive/binary_oarchive.hpp> #include <boost/asio.hpp> enum MyEnum_t { HELLO, BYE }; namespace boost { namespace serialization { template< class Archive > void save(Archive & ar, const MyEnum_t & t, unsigned int version) { unsigned char c = (unsigned char) t; ar & c; } template< class Archive > void load(Archive & ar, MyEnum_t & t, unsigned int version) { unsigned char c; ar & c; t = (MyEnum_t) c; } } // namespace serialization } // namespace boost BOOST_SERIALIZATION_SPLIT_FREE(MyEnum_t) int main(int argc, const char *argv[]) { boost::asio::streambuf buf; boost::archive::binary_oarchive pboa(buf); buf.consume(buf.size()); // Ignore headers MyEnum_t me = HELLO; pboa << me; std::cout << buf.size() << std::endl; // buf.size() = 4, but I want 1 return 0; } A: This probably doesn't work because enums aren't a real type, I don't think you can in general overload a function for a specific enum. You could accomplish what you want by doing the conversion to char in the serialization of whatever object contains your MyEnum_t. You could also do what Dan suggested and encapsulate the enum in a first-class type for which you can overload the serialization. Something like: class MyEnum_clone { unsigned char v_; MyEnum_clone(MyEnum_t v) : v_(v) {}; operator MyEnum_t() const {return MyEnum_t(v_); }; // serialization... }; That still likely won't be completetely transparent, though. However, I don't see why you care about how the type is serialized. Isn't the point of serializing that you don't have to care about the internal representation of the serialization, as long as you can restore the object correctly. The internal representation seems like a property of the archive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to stop every 10 questions? Let's say I have a list of 100 questions in my database. I also have an array of shuffled questions with a index size of 0-99 which I use to reference to the database. It's so I don't shuffled the database. My question is that the game starts at question 0 (10 for 2nd round, 20 for 3rd etc). I tried using a x mod 10 but I have it ordered so I check whether or not the question I'm up to has exceeded the limit for the round. (This stops the 11th question displaying on the screen) But since the game starts at question 0, the mod result is 0 and that would mean the end of the round. I need it to run question 0-9 stop at 10. next round 10-19 stop at 20.. etc I don't want to have to hardcode it like: run question except if question number is 0, 10, 20... 80, 90 100. in one big if statement. Any help would be great. A: What about (x + 1) mod 10? If you offset by one you don't get 0 as a valid case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MYSQL performance issue concat in select or in where I used to develop databases under ms-sql, and now I've moved to mysql. Great progress. The problem is that I don't have any tool to see graphically the query execution plan... EXPLAIN doesn't really help. Thus I require your advice on this one: I'll have a table with approximatively 50000 entries: The two following queries are giving me the same result but I need to know which one will be the more efficient/quick on a huge database. In the first one the concat is in the where, whereas in the second one it is in the select with a having clause. SELECT idPatient, lastName, firstName, idCardNumber FROM optical.patient WHERE CONCAT(lastName,' ',firstName) LIKE "x%"; SELECT idPatient, CONCAT(lastName,' ',firstName) as formattedName, idCardNumber FROM optical.patient HAVING formattedName LIKE "x%"; Thanks in advance for your answers. A: In both versions, the query cannot use index to resolve WHERE and will perform full-table scan. However, they are equialent to: SELECT idPatient, CONCAT(lastName,' ',firstName) as formattedName, idCardNumber FROM optical.patient WHERE lastName LIKE "x%"; And it can use index on lastName If you need to search by any of the 2 fields, use union SELECT idPatient, CONCAT(lastName,' ',firstName) as formattedName, idCardNumber FROM optical.patient WHERE firstName LIKE "x%"; UNION SELECT idPatient, CONCAT(lastName,' ',firstName) as formattedName, idCardNumber FROM optical.patient WHERE lastName LIKE "x%"; A: I don't believe you'll see any difference between these two queries since the CONCAT needs to be executed for all rows in both cases. I would consider storing formattedName in the database as well, since you can then add an index on it. This is probably the best you can do to optimize the query. As an aside, you may find pt-visual-explain to help with visualizing EXPLAIN output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Authorize.Net SIM Method With Response using C# I have been trying to implement the Authorize.NEt SIM Method using the information given on their website and tutorials.But i have been only able to redirect to their payment gateway using the ddl provided by them.I need a way to get a response from SIM Method to know about the transaction status. A: Either use relay response or silent post (I am the author of that blog post).
{ "language": "en", "url": "https://stackoverflow.com/questions/7635546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tooltip creation in android I am using ListView in my application. For each listitem I have to keep four images to its right side. When I click on each image it has to move to that particular page. Though the image specifies what it is meant for to know clearly I want to put a tooltip for each image. How can I create tooltip in android? Any help will be thankful to you. Thank you A: Normally tool tips are used when you hover over something using mouse..Tooltips are not a normal practice in touch screen devices.. If you want to do it, you can use a longClickListener and show a toast message with your tip string in it.. Toast viewToast = Toast.makeText(this, "Your tool tip", Toast.LENGTH_SHORT); yourView.setOnLongClickListener(new OnLongClickListener() { @Override public void onLongClick(View v) { viewToast.show(); } }); well this is one way to do..Hope it helps..
{ "language": "en", "url": "https://stackoverflow.com/questions/7635551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to use EditorFor with an ICollection in an ASP.NET MVC3 View? I'm trying to display a class object in a Create view, where a property is an ICollection<string>. For example... namespace StackOverflow.Entities { public class Question { public int Id { get; set; } .... public ICollection<string> Tags { get; set; } } } and if the view was like a StackOverflow 'ask a question' page, where the Tags html element is a single input box .. I'm not sure how I could do that in an ASP.NET MVC3 view? Any ideas? I tried using EditorFor but nothing was displayed in the browser, because it's not sure how to render a collection of strings. A: Start by decorating your view model with the [UIHint] attribute: public class Question { public int Id { get; set; } [UIHint("tags")] public ICollection<string> Tags { get; set; } } and then in the main view: @model StackOverflow.Entities.Question @Html.EditorFor(x => x.Tags) and then you could write a custom editor template (~/Views/Shared/EditorTemplates/tags.cshtml): @model ICollection<string> @Html.TextBox("", string.Join(",", Model)) or if you don't like decorating, you could also specify the editor template to be used for the given property directly in the view: @model StackOverflow.Entities.Question @Html.EditorFor(x => x.Tags, "tags")
{ "language": "en", "url": "https://stackoverflow.com/questions/7635555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can i implement CustumBinding configuration for this nettcpbinding configuration I have a nettcpbinding wcf service.It called 100000+ times in one second so there are more issue about performance. I must optimize this. My first issue is: A newly accepted connection did not receive initialization data from the sender within the configured ChannelInitializationTimeout (00:00:05). As a result, the connection will be aborted. If you are on a highly congested network, or your sending machine is heavily loaded, consider increasing this value or load-balancing your server. I should set ChannelInitializationTimeout using CustomBinding. I read some sample but not implemented configuration. How can implement below configuration to custombinding configuration? <?xml version="1.0"?> <configuration> <system.diagnostics> <sources> <source name="System.ServiceModel" switchValue="Warning" propagateActivity="false"> <listeners> <add type="System.Diagnostics.DefaultTraceListener" name="Default"> <filter type="" /> </add> <add name="ServiceModelTraceListener"> <filter type="" /> </add> </listeners> </source> </sources> <sharedListeners> <add initializeData="E:\Services\Ozy3\logs\EventParserService.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="Timestamp"> <filter type="" /> </add> </sharedListeners> <trace autoflush="true" /> </system.diagnostics> <system.web> <compilation debug="true" /> </system.web> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> <system.serviceModel> <services> <service name="Ozy3.Services.EventParserService" behaviorConfiguration="Ozy3.Services.EventParserServiceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:3274/EventParserService" /> </baseAddresses> </host> <endpoint address="net.tcp://localhost:3273/EventParserService" binding="netTcpBinding" bindingConfiguration="tcp_Unsecured" contract="Ozy3.Domain.Contracts.Service.IEventParserService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <bindings> <netTcpBinding> <binding name="tcp_Unsecured" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxConnections="2147483647" maxReceivedMessageSize="2147483647" portSharingEnabled="false" transactionFlow="false" listenBacklog="2147483647" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"> <readerQuotas maxDepth="64" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="None"></security> </binding> </netTcpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="Ozy3.Services.EventParserServiceBehavior"> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> <serviceThrottling maxConcurrentCalls="32" maxConcurrentSessions="200" maxConcurrentInstances="232" /> <serviceMetadata httpGetEnabled="True" /> <serviceDebug includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> A: I resolved this problem using customTcpBinding and Protocol Buffer for .Net but I understand to need high capacity network for using nettcpbinding fastly and efficient (10GBit Ethernet and Cat6 cable) <system.serviceModel> <services> <service behaviorConfiguration="EventDecoderService.ServiceBehavior" name="WcfService1.EventDecoderService"> <host> <baseAddresses> <add baseAddress="http://192.168.1.67:9001" /> </baseAddresses> </host> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <endpoint address="net.tcp://192.168.1.67:9000" behaviorConfiguration="EventDecoderService.EndpointBehavior" binding="customBinding" bindingConfiguration="customBind" name="EventDecoderService.Endpoint" contract="WcfService1.IEventDecoderService" /> </service> </services> <bindings> <customBinding> <binding name="customBind" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"> <binaryMessageEncoding> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> </binaryMessageEncoding> <tcpTransport maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxPendingConnections="100" channelInitializationTimeout="00:10:00" transferMode="Buffered" listenBacklog="1000" portSharingEnabled="false" teredoEnabled="false" > <!--<connectionPoolSettings maxOutboundConnectionsPerEndpoint ="1000" />--> </tcpTransport> </binding> </customBinding> <netTcpBinding> <binding name="tcp_Unsecured" maxBufferPoolSize="2147483647" closeTimeout="10:00:00" receiveTimeout="10:00:00" sendTimeout="10:00:00" openTimeout="10:00:00" maxBufferSize="2147483647" maxConnections="10000" maxReceivedMessageSize="2147483647"> <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" /> <security mode="None"> <transport clientCredentialType="None" protectionLevel="None" /> <message clientCredentialType="None" /> </security> </binding> </netTcpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="EventDecoderService.EndpointBehavior"> <ProtoBufSerialization /> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="EventDecoderService.ServiceBehavior"> <serviceMetadata httpGetEnabled="True" /> <serviceDebug includeExceptionDetailInFaults="true" /> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> <serviceTimeouts transactionTimeout="00:10:10"/> <serviceThrottling maxConcurrentCalls="96" maxConcurrentSessions="600" maxConcurrentInstances="696" /> </behavior> </serviceBehaviors> </behaviors> <extensions> <behaviorExtensions> <add name="ProtoBufSerialization" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=2.0.0.480, Culture=neutral, PublicKeyToken=257b51d87d2e4d67"/> </behaviorExtensions> </extensions> </system.serviceModel>
{ "language": "en", "url": "https://stackoverflow.com/questions/7635556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to encode accented char I am using php and getting some utf8 string from Javascript. I try to remove accent... by using a lot of difference function but still have troubles... With iconv() I have wrong accent removing, with some encode() I have nothing... When I use serialize(mystring), my wrong char look like followings: xE3xA0 with A0 depending of the char. It there any exhaustive map I can use ? Is there another method ? (I am under php 5.2 and no real control on the server so I cannot use intl/Normalize) Edit : code like this doesnt works (otherwise it would be ugly but efficient for short term) $string = mb_ereg_replace('(À|Á|Â|Ã|Ä|Å|à|á|â|ã|ä|å)','a',$string); A: This should do it: iconv("UTF-8", "ASCII//TRANSLIT", $text) If this does not work for you, see "How do I remove accents from characters in a PHP string?" A: For simple cases, like words or small sentences, I always use Sjoerd answer and it does work. For more complex cases such as long and complex paragraphs, possibly including some html, I use HTMLPurifier library with this set of options require_once dirname(__FILE__) . '/htmlpurifier/HTMLPurifier.auto.php'; $config = HTMLPurifier_Config::createDefault(); $config->set('Core.Encoding', 'utf-8'); $config->set('Core.EscapeNonASCIICharacters', true); $config->set('Cache.SerializerPath', sys_get_temp_dir()); $config->set('HTML.Allowed', 'a[href],strong,b,i,p'); $config->set('HTML.TidyLevel', 'heavy'); $purifier = new HTMLPurifier($config); echo $purifier->purify('òàòààòòààè'); It will replace any non ASCII char to its corresponding HTML entity, in this way you get rid of all encoding problems for such strings. For instance òàòààòòààè will become &#224;&#242;&#224;&#242;&#232;&#224;&#242;&#232;&#224;&#242;&#232; which is encode friendly because it doesn't contain any non-ASCII char. P.S. in any case don't use preg_replace for this kind of tasks, it's unsafe because you can't list all the possible non ASCII chars in a regex (or better, you could but it's pretty error prone task). P.P.S. here is a good document on utf-8 encoding and conversion in php taken from HTMLPurifier website.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pass a boolean field from one activity to a class? How to pass, at any time!, a boolean field from one activity to a class? A: Pass to Activity: Intent i = new Intent(getBaseContext(), NameOfActivity.class); i.putExtra("my_boolean_key", myBooleanVariable); startActivity(i) Retrieve in Second Activity: Bundle bundle = getIntent().getExtras(); boolean myBooleanVariable = bundle.getBoolean("my_boolean_key"); A: You can create your own singleton class that both your Activity and other class can access at any time. You have to be careful with it because it does add a layer of global variables (which people tend to not like), but it works. public class MyBoolean{ private static final MyBoolean instance = new MyBoolean(); private boolean boolValue = false; private MyBoolean(){} public static MyBoolean getInstance(){ return instance; } public boolean getValue(){ return boolValue; } public void setValue(boolean newValue){ boolValue = newValue; } } Call MyBoolean.getInstance() and you can use the methods inside which will be in sync with your whole program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Speed optimize - which is better? Let's say that we build a game and we have a player character. That character in the game will do many actions, like walking, jumping,attacking, searching target etc : public class Player extends MovieClip { public function Player(){} private function walk(){} private function attack(){} private function jumping(){} ... .. . private function update(){} } Now, for every state or action we want to execute a different code. Now, how to do this? I can think of 3 ways. 1.With events - as I understand, event system is costly to use, so I'll skip this one. 2. With simple checks in the update() - something like if(currentStateAction) {doSomethingHere} or with switch statement. But what if the actions are not mutually exclusive, e.g. it can jump and attack in the same time? Than we have to use if() for every action, e.g. to do checks for every frame. 3. I came up with this solution on my own and I need to know is this better than option number 2: //declare Dictionary. Here we will add all the things that needs to be done public var thingsToDo:Dictionary = new Dictionary(true); //in the update function we check every element of the dictionary private funciton update():void { for each(item:Function in thingsToDo) { item.call(); } } Now, every time we need to do something, we add a element, like thingsToDo[attack]=attack; Or if we don't want to do something anymore: delete thingsToDo[attack]; In this ... system ... you don't need to check every frame what the object should do, but instead, you only check when is needed. It's like a event driving system. Say for example, the object don't need to check for attack until new enemy is spawn. So. when spawing a new enemy, you will add thingsToDo[attack] = attack; and etc. So the question: Is this faster than option number 3? Any idea how to do this checking differently? Thanks. A: You should probably focus on making it work the way you want (flexible, easy to maintain and modify), instead of making it as fast as possible. This is very unlikely to ever be a real bottleneck. Premature optimization is the root of all evil, and all that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Embed MS Excel in SWF / Silverlight For a project requirement, I want to make available editing of an excel file through browser. The only possible ways that I could think of was by embedding the excel file either in Flash or Silverlight. I am building my project on asp.net mvc3 c#. I wanted to know that is there a way by which this could be achieved? I shall be happy to start an open source project is need be so that people who are interested can collaborate together. Any pointer would be great. Much thanks. A: Well on Windows Live Skydrive there is an Silverlight Excel app, but that requires windows live accounts... There are other controls out there I'm sure, just most will cost something.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Most appropriate way to develop a server on limited resources I am facing a problem which seems to have few, and especially simple solutions. To get to the point; I have written a client application on Windows using C++. This client application takes input from the user, and is supposed to send this information to a server, which find users who's inputs match each other - like matchmaking. How can I (an indie developer) with most ease solve this problem, IF and only if I cannot host the server application myself, and do not want to spend money on renting a whole virtual private server? Most preferred, I want to write this server using sockets in PHP and just rent a web-server with unlimited bandwidth, but it seems to have far too many restrictions, related to timeouts (PHP's set_time_limit, Apache's timeout value and the internal OS timeout value). So to sum up the question, and in a generic form; How can I as an indie developer create a server application which do not require using my own bandwidth and without expensive purchases for items such as a virtual private server. A: You can just code your server application in PHP as a webservice. In your client application, instead of connecting through sockets and a using a home-made protocol, you just have to use the HTTP REST webservice you created. It seems to me even easier than coding a whole server. Maybe you absolutely want to use socket on your server, but you didn't specify that in your question. A: You can try a cloud hosting provider, such as Rackspace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can ReSharper be used when editing SSIS script tasks? I have ReSharper 6 installed and integrated with Visual Studio 2008 and Visual Studio 2010. I'm editing SSIS packages in VS2008 and some of them contain script tasks. When editing the script task, a Microsoft Visual Studio Tools for Applications (VSTA) application is launched which is lacking ReSharper integration. Does anyone know if ReSharper can be installed and used in this context? A: Resharper works with Business Intelligence Development Studio for SQL Server 2012, primarily because SQL Server 2012 now uses the integrated Visual Studio shell for editing script files. Anything before SQL Server 2012 does not use the integrated shell. VSTA and the isolated shell do not load additional plugins like Resharper, which is why it won't show up in BIDS for SQL Server 2008 R2 or earlier. (In fact, the SSIS editor will create an entire temporary Visual Studio project and load it into the separate IDE as a complete, buildable solution.) A: to expand on SpikeX's answer, the Visual Studio 2008 used for SSIS is a Shell Version of Visual Studio 2008. It won't support anything beyond Business Intelligence Studio projects. (Akin to the Express version of VS2008) Since it's not a full version of VS, it can't support Resharper.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set transparency color of the WPF Window? Is there any way to set one specific color to be transparent for the whole WPF window? A: You don't need to. Transparency in WPF doesn't work using mask colors like in Winforms- just set the background to Transparent, and AllowsTransparency to true. If you want different shaped windows, you can use the technique described here: http://devintelligence.com/2007/10/shaped-windows-in-wpf/ A: We can make a transparent WPF window by using a XAML like follows. <Window x:Class="SeeThru.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="SeeThru" Height="300" Width="300" WindowStyle="None" AllowsTransparency="True" Background="Transparent"> ...... </Window> A: No. WPF supports alpha-channel transparency, not bitmap mask transparency. There are people who have attempted to work around this, but only on a per-image basis.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DB Migrate not reflected on heroku I recently created a db migration which works fine locally. I pushed to heroku and ran heroku rake db:migrate Whilst the command doesn't seem to throw an error, I can see the database hasn't been updated with the column I've tried to add to a table. I've tried running heroku rake db:setup but to no avail. Additionally, I've also tried restarting heroku after both commands but it still doesn't work. Anybody have this problem before? A: First try to be specific with heroku rake db:migrate:up VERSION=xxx I had similar problems and what I did was to reset the database, if that doesn't work, I would migrate down all migrations (one by one) and add them up again, of course only if you can afford to loose all your data, alternatively download the database and investigate. The problems I had with recreating the db were related to the fact that I was changing the migrations and that in heroku I had a shared database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dubugging GAC DLL with IIS 5 I'm trying to debug a DLL in the GAC with VS 2008 / XP / IIS 5 configuration. Tried to copy the DLL in the C:\\assembly\GAC_MSIL but the symbols still doesnt get loeded :-( Also this interesting post about debugging GAC without having to copy the PDB file into the GAC : http://www.elumenotion.com/Blog/Lists/Posts/Post.aspx?ID=23 But since I run IIS 5, there's no trace of the w3wp.exe (which seems to be only in IIS 6 and newer). Do you know a trick so I can attach to my web page and trace a referenced DLL ? A: Finally, turns out that the solution without copying the .pdb file is working. Only thing is to attach to the "aspnet_wp" process instead of the "w3wp.exe" mentionned in the post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do I get a warning about possible loss of data when seeding the random number generator from time(NULL)? am learning vectors and made a bit of code that selects random numbers i can use for buying lottery tickets here in Netherlands. But although it runs, the compiler is warning me about 'conversion from 'time_t' to 'unsigned int, possible loss of data'. Can anyone spot what is causing this? I haven't even defined any unsigned int in this code; int i by default is a signed int as i understand. Thanks for insight. #include <iostream> #include <vector> #include <string> #include <ctime> using namespace std; void print_numbers(); string print_color(); int main() { srand(time(NULL)); print_numbers(); string color = print_color(); cout << color << endl; system("PAUSE"); return 0; } //Fill vector with 6 random integers. // void print_numbers() { vector<int> lucky_num; for (int i = 0; i < 6; i++) { lucky_num.push_back(1 + rand() % 45); cout << lucky_num.at(i) << endl; } } //Select random color from array. // string print_color() { string colors[6] = {"red", "orange", "yellow", "blue", "green", "purple"}; int i = rand()%6; return colors[i]; } Exact compiler message: warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data. Line 11. A: Because time_t happens to be larger in size than unsigned int on your particular platform, you get such a warning. Casting from a "larger" to a "smaller" type involves truncating and loss of data, but in your particular case it doesn't matter so much because you are just seeding the random number generator and overflowing an unsigned int should occur for a date in the very far future. Casting it to unsigned int explicitly should suppress the warning: srand((unsigned int) time(NULL)); A: time_t is a 64 bit value on many platforms to prevent the epoch time eventually wrapping while unsigned int is 32 bits. In your case, you don't care cause you're just seeding the random number generator. But in other code, if your software ever deals in dates past 2038, you could have your time_t truncated to a 32-bit pre 2038 date when you cast to a 32-bit value. A: time returns a time_t object. srand is expecting an unsigned int. A: srand(time(NULL)); This line can overflow if the return value from time exceeds the representation range of an unsigned int, which is certainly possible. A: void srand ( unsigned int seed ); time_t time ( time_t * timer ); typedef long int __time_t; long int is not the same as a unsigned int. Hence the warning. (from stackoverflow
{ "language": "en", "url": "https://stackoverflow.com/questions/7635580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: unknown property while using a list of class in Vf page i have a class public with sharing class CAccountRep { string sageAccountNo {get;set;} string clientName {get;set;} string name {get;set;} integer noofdays {get;set;} string billableUnits {get;set;} decimal dailyChargeRate {get;set;} string nominalCode {get;set;} string practice {get;set;} string taxFlag {get;set;} string ProjectId {get;set;} string PONumber {get;set;} public CAccountRep(String CrSageAc,String CrClientN,string CrName,integer Crnoofdays,string crbillableunits,decimal CrDecimalChargeRate,string crNominalCode,string CrPractice, String CrTaxFlag,String CrProjectId, String CrPONumber) { sageAccountNo=CrSageAc; clientName=CrClientN; name=CrName; noofdays=Crnoofdays; billableUnits=crbillableunits; dailyChargeRate=CrDecimalChargeRate; nominalCode=crNominalCode; practice=CrPractice; taxFlag=CrTaxFlag; ProjectId=CrProjectId; PONumber=CrPONumber; } } Iam creating a object of this class and passing out the parameters into this class public List<CAccountRep> AR { get;set; } public list<CAccountRep> getAR() { if(AR!= null) return AR ; else return null; } Using the follwing code to create the object of the class CAccountRep CRep=new CAccountRep(projectList[0].Sage_Account_Number__c,projectList[0].Client_Name__c, Cname,enoOfBillableDays,projectList[0].BillableUnits__c,AssConlist[0].Daily_Charge_Rate_of_Consultant__c,AssConlist[0].Nominal_Code__c,projectList[0].C85_Practice__c,projectList[0].Tax_Flag__c,projectList[0].Project_ID__c,projectList[0].PO_Number__c); AR.add(CRep); In my VF page i am trying to display the contents of the list AR. But i get an error Unknown Propery CAccountRep.ProjectId while saving the VF page. <table id="tableRep"> <apex:repeat id="tc" value="{!AR}" var="TCrep"> <tr> <td>{!TCrep.ProjectId}</td> </tr> </apex:repeat> </table> I can get the output like this if i just give {!TCrep} CAccountRep:[PONumber=null, ProjectId=C85_JPMC1 _A-0083, billableUnits=null, clientName=001A000000YJFhdIAH, dailyChargeRate=null, name=Change Order 10002011-09-05 to 2011-10-10 : 0 null, nominalCode=null, noofdays=0, practice=Administration, sageAccountNo=null, taxFlag=null] CAccountRep:[PONumber=null, ProjectId=C85_BBCWW _A-0084, billableUnits=null, clientName=001A000000cwgIlIAI, dailyChargeRate=null, name=Secure Desktop v012011-09-05 to 2011-10-10 : 0 null, nominalCode=null, noofdays=0, practice=null, sageAccountNo=null, taxFlag=null] CAccountRep:[PONumber=null, ProjectId=C85_JPMC1 _A-0083, billableUnits=null, clientName=001A000000YJFhdIAH, dailyChargeRate=null, name=Change Order 10002011-09-05 to 2011-10-10 : 0 null, nominalCode=null, noofdays=0, practice=Administration, sageAccountNo=null, taxFlag=null] Any ideas on how to get it display correctly? A: I think the compiler is getting confused because you have 2 public getters in it's opinion i.e. both of these lines: public List<CAccountRep> AR { get;} // just removed set; for now public list<CAccountRep> getAR() Would be called from a Visualforce page when you use the following syntax in the page: {!AR} Try doing this instead: public List<CAccountRep> AR { get{ return AR ; // if AR is null it returns null so the if statement was redundant }set; } And remove the getAR() method. You should also mark the class member variables that you'd like to be visible as public e.g. public string ProjectId {get;set;}
{ "language": "en", "url": "https://stackoverflow.com/questions/7635588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect if css position overflow is working? As iOS5 beta has fixed css property overflow: scroll and overflow: auto, I’d like to target the older iOS versions with Javascript. Is there a way to check with JS if the property is actually working or not? Trying to get the style property does alert the correct value in both Mobile Safaris, but in the current version it requires a two-finger scrolling to work. A: I don't know of a way to check if the scroll property is working but you could check the user-agent to determine which version of iOS they're running (3.2 in the following example): Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10
{ "language": "en", "url": "https://stackoverflow.com/questions/7635589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: store a Byte[] in an sqlite db in small chunks? I would like to store a large Byte[] in my SQLite database. Android has a limit to how much RAM each app can use, so I figured the best way to skirt around this limitation is to write the file in smaller chunks. Is it possible to use a stream to access my file, and append to my database Byte[] in small pieces? (without loading the Byte[] into memory to append) A: Store the data in files in your app/sdcard and keep a reference in SQLite - you cannot append to BLOBs in SQLite (at least without pre-allocating the size with zeroblob() and using the NDK) - besides - how would you read it back? The only API made available in the SDK will attempt to read the entire BLOB back as a byte[]. Typically you want to implement ContentProvider#openFile(..) properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to do a second transform on the output of an XSLT template I have only basic XSLT skills so apologies if this is either basic or impossible. I have a paginator template which is used everywhere on the site I'm looking at. There's a bug where one particular search needs to have a categoryId parameter appended to the href of the page links. I can't alter the paginator stylesheet or else i would just add a param to it. What I'd like to do is apply the template as is then do a second transform based on its output. Is this possible? How do others normally go about extending library templates? So far I've thought about doing a recursive copy of the output and applying a template to the hrefs as they are processed. The syntax for that escapes me somewhat, particularly as I'm not even sure it's possible. Edit - Between Dabbler's answer and Michael Kay's comment we got there. Here is my complete test. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="http://exslt.org/common"> <!-- note we require the extensions for this transform --> <!--We call the template to be extended here and store the result in a variable--> <xsl:variable name="output1"> <xsl:call-template name="pass1"/> </xsl:variable> <!--The template to be extended--> <xsl:template name="pass1"> <a href="url?param1=junk">foo</a> </xsl:template> <!--the second pass. we lock this down to a mode so we can control when it is applied--> <xsl:template match="a" mode="pass2"> <xsl:variable name="href" select="concat(@href, '&amp;', 'catid', '=', 'stuff')"/> <a href="{$href}"><xsl:value-of select="."/></a> </xsl:template> <xsl:template match="/"> <html><head></head><body> <!--the node-set extension function turns the first pass back into a node set--> <xsl:apply-templates select="ext:node-set($output1)" mode="pass2"/> </body></html> </xsl:template> </xsl:stylesheet> A: Here is a complete example how multi-pass processing can be done with XSLT 1.0: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="http://exslt.org/common"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="node()|@*" mode="mPass2"> <xsl:copy> <xsl:apply-templates select="node()|@*" mode="mPass2"/> </xsl:copy> </xsl:template> <xsl:template match="/"> <xsl:variable name="vrtfPass1Result"> <xsl:apply-templates/> </xsl:variable> <xsl:apply-templates mode="mPass2" select="ext:node-set($vrtfPass1Result)/*"/> </xsl:template> <xsl:template match="num/text()"> <xsl:value-of select="2*."/> </xsl:template> <xsl:template match="/*" mode="mPass2"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:apply-templates mode="mPass2"/> </xsl:copy> </xsl:template> <xsl:template match="num/text()" mode="mPass2"> <xsl:value-of select="3 + ."/> </xsl:template> </xsl:stylesheet> when this transformation is applied on the following XML document: <nums> <num>01</num> <num>02</num> <num>03</num> <num>04</num> <num>05</num> <num>06</num> <num>07</num> <num>08</num> <num>09</num> <num>10</num> </nums> the wanted result (each num is multiplied by 2 and in the next pass 3 is added to each num) is produced: <nums> <num>5</num> <num>7</num> <num>9</num> <num>11</num> <num>13</num> <num>15</num> <num>17</num> <num>19</num> <num>21</num> <num>23</num> </nums> A: It's possible in XSLT 2; you can store data in a variable and call apply-templates on that. Basic example: <xsl:variable name="MyVar"> <xsl:element name="Elem"/> <!-- Or anything that creates some output --> </xsl:variable> <xsl:apply-templates select="$MyVar"/> And somewhere in your stylesheet have a template that matches Elem. You can also use a separate mode to keep a clear distinction between the two phases (building the variable and processing it), especially when both phases use templates that match the same nodes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: ColdFusion not "seeing" my components I have a directory structure similar to C:...\wwwroot\project\testPage.cfm <html> <head> <title>Test Page</title> </head> <cfset this.mappings["/local"] = getDirectoryFromPath(getCurrentTemplatePath()) /> <cfform name="myform"> Pick as many as you like: <cfinput id="pickers4" name="pickmany" type="checkbox" value="Apples"> <label for="pickers4">Apples</label> <cfinput id="pickers5" name="pickmany" type="checkbox" value="Oranges"> <label for="pickers5">Oranges</label> <cfinput id="pickers6" name="pickmany" type="checkbox" value="Mangoes"> <label for="pickers6">Mangoes</label> <br/> <cfinput name="pickmany-selected" bind="cfc:TestCFC.One({myform:pickmany})"><br /> </cfform> </body> </html> C:...\wwwroot\project\TestCFC.cfc <cfcomponent> <cfscript> remote function One(whatever){ return whatever; } </cfscript> </cfcomponent> and for some reason the ColdFusion server won't "see" my component. I get this error. I wasn't using mappings as my component was located in the same directory as my page. This worked at one point, and it seems as though the CF server has just dropped a setting or something. Anyone have some idea as to why this is happening? A: Well, since your CFC is located in C:...\wwwroot\project\TestCFC.cfc wouldn't the path (FQN) be project.TestCFC? Did you try this: <cfinput name="pickmany-selected" bind="cfc:project.TestCFC.One({myform:pickmany})"><br /> A: This is not an answer, per-se; but a suggestion for investigation. What's the URL that is actually being requested by the browser under the hood? And what's the HTTP error you get? Also: I doubt CF mappings are relevant here because JS is mapping a client-side HTTP request, and CF mappings are just so CF can access resources on its local system (ie: server side). If you need to map anything to the location of the URL, it needs to be a web server virtual directory, not a CF mapping.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detail property of SoapException set in .NET Web service ends up as null in Java web service client So I wrote simple asmx .NET web service in C#. All exceptions are caught and re-thrown as SoapException with Detail property set up to XmlNode that contains three sub-nodes with additional information about exception that has occurred. On Java side server exceptions surface as SoapFaultException. But when I try to print ex.getFault().getDetail() it's appears to be null. So my question is why is this happening or what am I doing wrong? Finally managed to get raw SOAP response: HTTP/1.1 500 Internal Server Error Cache-Control: private Content-Type: text/xml; charset=utf-8 Server: Microsoft-IIS/7.0 X-AspNet-Version: 2.0.50727 X-Powered-By: ASP.NET Date: Tue, 04 Oct 2011 20:13:21 GMT Content-Length: 2143 <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org /soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <soap:Fault> <faultcode>soap:Server</faultcode> <faultstring>System.Web.Services.Protocols.SoapException: ...</faultstring> <faultactor>CustomSoapException</faultactor> <detail> <CustomExceptionType>BackendException</CustomExceptionType> <UserMessage>Internal application error occured. Please contact application developer for quick resolution.</UserMessage> <DeveloperMessage>Exception details: ....</DeveloperMessage> </detail> </soap:Fault> </soap:Body> </soap:Envelope>
{ "language": "en", "url": "https://stackoverflow.com/questions/7635600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Variable not defined error in Classic ASP (VBScript) Microsoft VBScript runtime error '800a01f4' Variable is undefined: 'product_id' /Vital/form/products.asp, line 64 I am using option explicit and I have defined the variable as Dim product_id product_id=Request.Form("product_id") Is this a problem with IIS or sql server 2003? Actually its working fine when i access my sql server 2008 database from localhost. But the problem comes when my client uploads the asp file to web server and try to access mysql 2003 database. A: Without seeing more code, I have to guess and I guess you define the variable inside a function, for example: Function Foo Dim product_id '...... End Function Then having the line product_id=Request.Form("product_id") outside the function will indeed result in error, as it's only local to that function. It got nothing to do with IIS or database - pure VBScript issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error while pressuing multiple times physical back button of device in android I am facing this error while I am pressing back multiple times on the physical button of device. This is my log: 10-03 18:47:50.403: ERROR/ActivityManager(98): Reason: keyDispatchingTimedOut 10-03 18:47:50.403: ERROR/ActivityManager(98): Load: 4.16 / 3.77 / 2.21 10-03 18:47:50.403: ERROR/ActivityManager(98): CPU usage from 141136ms to 62ms ago: 10-03 18:47:50.403: ERROR/ActivityManager(98): system_server: 8% = 6% user + 2% kernel / faults: 3797 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): dhd_dpc: 2% = 0% user + 2% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): om.htc.launcher: 1% = 1% user + 0% kernel / faults: 1095 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): mediaserver: 1% = 0% user + 0% kernel / faults: 1610 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): d.process.acore: 0% = 0% user + 0% kernel / faults: 4617 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): e.pluginmanager: 0% = 0% user + 0% kernel / faults: 389 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): akmd: 0% = 0% user + 0% kernel / faults: 69 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): adbd: 0% = 0% user + 0% kernel / faults: 331 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): logcat: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): id.defcontainer: 0% = 0% user + 0% kernel / faults: 153 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): tc.RosieUtility: 0% = 0% user + 0% kernel / faults: 81 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): android.vending: 0% = 0% user + 0% kernel / faults: 61 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): com.htc.bg: 0% = 0% user + 0% kernel / faults: 47 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): e.process.gapps: 0% = 0% user + 0% kernel / faults: 62 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): com.htc.bgp: 0% = 0% user + 0% kernel / faults: 67 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): s:FriendService: 0% = 0% user + 0% kernel / faults: 47 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): equicksearchbox: 0% = 0% user + 0% kernel / faults: 45 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): wpa_supplicant: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): droid.apps.maps: 0% = 0% user + 0% kernel / faults: 50 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): com.svox.pico: 0% = 0% user + 0% kernel / faults: 40 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): suspend: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): events/0: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): cabc_work_q: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): panel_on/0: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): m.android.phone: 0% = 0% user + 0% kernel / faults: 18 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): ksoftirqd/0: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): .android.htcime: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): re-initialized>: 0% = 0% user + 0% kernel / faults: 45 minor 1 major 10-03 18:47:50.403: ERROR/ActivityManager(98): com.android.mms: 0% = 0% user + 0% kernel / faults: 13 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): get.clockwidget: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): atmel_wq: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): ls_wq/0: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): rild: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): zygote: 0% = 0% user + 0% kernel / faults: 31 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): d.process.media: 0% = 0% user + 0% kernel / faults: 10 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): com.htc.music: 0% = 0% user + 0% kernel / faults: 7 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): ogle.android.gm: 0% = 0% user + 0% kernel / faults: 9 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): com.fd.httpd: 0% = 0% user + 0% kernel / faults: 8 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): d.apps.uploader: 0% = 0% user + 0% kernel / faults: 8 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): init: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): netd: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): android.updater: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): roid.worldclock: 0% = 0% user + 0% kernel / faults: 7 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): c.android.Stock: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): com.htc.fm: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): MessageUploader: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): ec.android.jbed: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): roid.footprints: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): android.browser: 0% = 0% user + 0% kernel / faults: 7 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): tc.android.mail: 0% = 0% user + 0% kernel / faults: 6 minor 10-03 18:47:50.403: ERROR/ActivityManager(98): +flush-179:0: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): +om.amritbani.tv: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): +om.amritbani.tv: 0% = 0% user + 0% kernel 10-03 18:47:50.403: ERROR/ActivityManager(98): TOTAL: 24% = 14% user + 8% kernel + 0% softirq A: It is looked like that this error occur because of the emulator. This is error of the emulator. Create New Emulator and try your code again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create Windows in D with win32? Hello I'm trying to open a window with win32 in D, and I've got a little problem. The program crashes when I call CreateWindowA. Here is my code : this.fenetrePrincipale = CreateWindowA(this.classeFenetre.lpszClassName, toStringz(title), WS_OVERLAPPEDWINDOW, 0, 0, 100, 100, null, null, this.hInstance, null); with: this.classeFenetre.lpszClassName = toStringz("classeF"); this.hInstance = GetModuleHandleA(null); and string title = "test"; When I launch the exe, the program crashes and I've got: Process terminated with status -1073740791 on code::blocks. A: The error code -1073740791 (or 0xc0000409) is caused by a stack buffer overrun (not overflow, as in running out of stack, but writing to a place in stack where you are not supposed to write to). The call that you've shown is looks OK. But you didn't show us the class registration code, and more importantly, the WndProc you register. I am not sure how you do it in D, but your WndProc needs to be declared __stdcall, so that it matches the calling convention assumed by Windows. This is a common problem that causes crashes on CreateWindow. A: Yeah that was the problem : I didn't declared the WndProc as __stdcall the way you do that in D is extern (Windows) int windowRuntime(HWND window, UINT message, WPARAM wParam, LPARAM lParam) thanks for your help. A: I would suggest using gtkD or QTD instead of Win32. The two widget libraries are mature and powerful, yet very simple to use. And you have cross-platform support as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Run JQuery after Specific updatePanel fires I have a script that runs once an update panel fires: Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); function EndRequestHandler(sender, args) { initDropSearch(); } function initDropSearch() { var search = jQuery("#searchBar div.productSearchFilter"); if (search.length > 0) { var grid = search.find("table.gridView"); if (search.next().val() != "open") { search.animate({ height: ['toggle', 'easeOutBounce'], opacity: 'toggle' }, 1000) .next().val("open"); } else { search.show(); } } } Once the results of a search have loaded, the container drops down and bounces. It works perfectly - that is until another update panel is triggered on the same page - in which case the search panel opens again. What I need to do is only run the script when a specific updatePanel fires. Is there a way to do this? A: Do the sender or args contain data about the UpdatePanel that triggered the EndRequestHandler? If so just check which one triggered it and only fire your code based on that. function EndRequestHandler(sender, args) { if (((UpdatePanel)sender).ID == "UpdatePanel1") { initDropSearch(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android - javah doesn't find my class I am having troubles generating the C header file for JNI using javah. Here's the script I use while standing in the <project-dir>\bin directory: javah -classpath C:\PROGRA~2\Android\android-sdk\platforms\android-8\android.jar com.test.JniTest As return I get: ERROR: Could not find class file for 'com.test.JniTest'. Even though the class JniTest certainly is in \com\test. What am I doing wrong? A: You specify the classpath to contain only android.jar. You also need to include the location where your classes are stored. In your case it is the current directory, so you need to use . (separated by ; on Windows). The invocation should look like this: javah -classpath C:\PROGRA~2\Android\android-sdk\platforms\android-8\android.jar;. com.test.JniTest A: If you are on Linux or MAC-OS, use ":" to separate the directories for classpath rather than ";" character: Example: javah -cp /Users/Android/android-sdk/platforms/android-xy/android.jar:. com.test.JniTest A: You should change the directory to <project-dir>\bin\classes; then, run the following command: javah -classpath C:\PROGRA~2\Android\android-sdk\platforms\android-8\android.jar;. com.test.JniTest I'm using the following command file to generate headers: jHdr.cmd on my desktop: @echo on SET PLATFORM=android-8 SET ANDROID_SDK_ROOT=C:\Android\android-sdk SET PRJ_DIR=D:\Workspaces\sqLite\raSQLite SET CLASS_PKG_PREFIX=ra.sqlite cd %PRJ_DIR%\bin\classes javah -classpath %ANDROID_SDK_ROOT%\platforms\%PLATFORM%\android.jar;. %CLASS_PKG_PREFIX%.%~n1 pause adjust variables to your needs ... put this file on your desktop, then drag you .java file from eclise to jHdr.cmd, result is under %PRJ_DIR%\bin\classes directory
{ "language": "en", "url": "https://stackoverflow.com/questions/7635624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: EF 4.1 Code First : How to load entity references into memory? I just started working with EF 4.1 Code First and noticed that by default, references (navigation properties), are not loaded into memory with a POCO entity you queried with LINQ-to-Entity. I have had no success with making the referenced entities load using DbEntityEntry.Reference. When I call DbReferenceEntry.Load, the following exception is thrown: "There is already an open DataReader associated with this Command which must be closed first." Closing a DataReader is not something I really want to have to do when I'm in the middle of several LINQ queries. For example, the following will not work: using (db1 = new NorthindDbContext(new SqlConnection(this.NORTHWIND))) { orders = db1.Orders.Where(o => !(o.CustomerId == null || o.ShipperId == null || o.EmployeeID == null)); foreach (var o in orders) { Shipper s = o.Shipper;//exception: "There is already an open DataReader associated with this Command which must be closed first." DbEntityEntry<Order> entry = db1.Entry(o); DbReferenceEntry<Order, Shipper> shipper_reference = entry.Reference<Shipper>("Shipper"); if (!shipper_reference.IsLoaded) { shipper_reference.Load(); } } } Here is the Order class: public partial class Order { public System.Int32 ID { get; set; } public System.Nullable<System.DateTime> OrderDate { get; set; } public System.Nullable<System.DateTime> RequiredDate { get; set; } public System.Nullable<System.DateTime> ShippedDate { get; set; } public System.Nullable<System.Decimal> Freight { get; set; } public Employee Employee { get; set; } public Int32 CustomerId { get; set; } public Customer Customer { get; set; } public Int32 EmployeeID { get; set; } /// <summary> /// marked virtual for lazy loading /// </summary> public virtual Shipper Shipper { get; set; } public Int32 ShipperId { get; set; } } I have tried marking the Order.Shipper property as virtual, and I still get the same exception if when I run the code. The ObjectQuery.Include method, does work: [TestMethod] //configure MARS here? //Order.Shipper is not marked virtual now //... using (db = new NorthindDbContext(new SqlConnection(this.NORTHWIND))) { db.Orders.Include(o => o.Shipper) .Where(o => !(o.CustomerId == null || o.ShipperId == null || o.EmployeeID == null)); foreach (var o in orders) { Shipper s = o.Shipper;//null DbEntityEntry<Order> entry = db.Entry(o); DbReferenceEntry<Order, Shipper> shipper_reference = entry.Reference<Shipper>("Shipper"); if (!shipper_reference.IsLoaded) { shipper_reference.Load();//"There is already an open DataReader associated with this Command which must be closed first." } } With EF 4.1 Code First, how do you make a referenced entity load into memory? A: If you need multiple database reads work in the same time you must allow MARS on your connection string but your real problem is elsewhere. EF doesn't load navigation properties by default. You must either use lazy or eager loading. Lazy loading needs all navigation properties in entity to be virtual: public class Order { ... public virtual Shipper Shipper { get; set; } } Once lazy loading and proxy creation is allowed on context (default) your property will be automatically loaded when first time accessed by your code. This access must happen within scope of the same context used to load the order (you can still meet the error with opened DataReader here). Other way is to load Shipper directly with Order by using eager loading: var query = context.Orders.Include(o => o.Shipper)...
{ "language": "en", "url": "https://stackoverflow.com/questions/7635628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loaded JavaScript files and dynamically events Anyone knows a tool that collect all the js files that are loaded with a web page? I know that Firebug through the script tab gives me all the js files downloaded with the web page, but I have to copy the URL from the tab and make the download one by one. Another question, if I have one element in the web page, for example: <a href="#" id="test1" ...> How can I know all the events associated with this element? Events that were add dynamically for example in the onsubmit event through JavaScript, for example. document.getElementById("test1").onclick = "function()...." A: First Question: Chrome's inspector tool Second Question: refer to this post: Inspect attached event handlers for any DOM element
{ "language": "en", "url": "https://stackoverflow.com/questions/7635630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL- Identify nullable values I am relatively new to SQL queries. I have a large number of tables in my SQL Database ( over 1500 ) My question is as follows: I need to identify columns which are nullable from all the tables which have default values? How can I go about it for all the tables? Any help or tutorial for the same would be also very helpful. Thank you A: You can use information_schema to get this data, the columns "COLUMN_DEFAULT" and "IS_NULLABLE" will give you what you need. SELECT * FROM information_schema.columns c with (Nolock) A: Use the self-describing features of SQL Server :- SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE IS_NULLABLE = 'YES' OR COLUMN_DEFAULT IS NOT NULL A: SELECT OBJECT_NAME(c.object_id), * FROM sys.columns c JOIN sys.default_constrainst dc ON c.columnid = dc.parent_column_id AND c.object_id = dc.parent_object_id WHERE c.is_nullable = 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7635632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I check if a generic method parameter is a value type? Is there a way to check if a variable is value type of reference type? Imagine: private object GetSomething<T>(params T[] values) { foreach (var value in values) { bool is ValueType; // Check if 'value' is a value type or reference type } } A: bool isValueType = typeof(T).IsValueType; Job done... it doesn't matter if any of the values is null, and it works even for an empty array. A: Your condition will look like var cond = false; if(value != null) cond = value.GetType().IsValueType
{ "language": "en", "url": "https://stackoverflow.com/questions/7635640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: SQL Query Join 2 tables I'm new to SQL and was reading on joins but i'm a bit confused so wanted help.... I have a table called student_sport which stores StudentID and SportID I have another table which stores details of matches... so basically sportsID,MatchId,.... What i wanna do is.... for a perticular student display the sports in which matches have been played. ie. if a sportID exists in the second table only then display that when i check which sports the student plays. The resultSet should contain only those sports for a student in which matches have been played.... Thanks A: Okay, as this is homework (thanks for being honest about that) I won't provide a solution. Generic way to design a query is: * *Think of how to write the FROM block (what is your data source) *Think of how to write the WHERE block (what filters apply) *Write the SELECT block (what you want from the filtered data). You obviously need to join your two tables. The syntax for joins is: FROM table1 JOIN table2 ON boolean_condition Here your boolean_condition is equality between the columns sportid in your two tables. You also need to filter the records that your join will produce, in order to only retain those that match your particular student, with the WHERE clause. After that, select what you need (you want all sports ids). Does that help enough? A: Then you have two tables : // One record per student / sport association student_sport StudentID SportID // A match is only for one sport (warning to your plural) no? matches SportID MacthID You want: For one student all sport already played in a match SELECT DISTINCT StudentID, student_sport.SportID FROM student_sport, matches WHERE -- Select the appropriate player student_sport.StudentID = @StudentID -- Search all sport played in a match and plays by the student -- (common values sportid btw student_sport & matches) AND student_sport.SportID = matches.SportID or use this other syntax (JOIN IN) (it makes complex queries easier to understand, so it's good to learn) SELECT DISTINCT StudentID, student_sport.SportID FROM student_sport -- Search all sport played in a match and plays by the student -- (common values sportid btw student_sport & matches) INNER JOIN matches on student_sport.SportID = matches.SportID WHERE -- Select the appropriate player student_sport.StudentID = @StudentID ps: Includes Jan Hudec Coments, tx for it A: Because you only need to return results from the student_sport table, the join type is a semijoin. Standard SQL's operator for semi join is funnily enough MATCH e.g. SELECT * FROM student_sport WHERE SportID MATCH ( SELECT SportID FROM matches WHERE student_sport.SportID = matches.SportID ); There are a number of other ways of writing a semi join in SQL e.g. here's three more: SELECT * FROM student_sport WHERE SportID IN ( SELECT SportID FROM matches WHERE student_sport.SportID = matches.SportID ); SELECT * FROM student_sport WHERE EXISTS ( SELECT * FROM matches WHERE student_sport.SportID = matches.SportID ); SELECT student_sport.* FROM student_sport INNER JOIN matches ON student_sport.SportID = matches.SportID; A: Well the query would be something like that: select sm.* from student_sport ss join student_matches sm on ss.sportid = sm.sportId where ss.StudentId = @studendId This and this should give you some insight of sql joins
{ "language": "en", "url": "https://stackoverflow.com/questions/7635643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I get access to the object which the Timer is attached to? I have a programming problem which I think is being caused by my rustiness in using events and delegates... I have the code: public void DoStuff() { List<IProcess> processorsForService1 = processorsForService1 = ProcessFactory.GetProcessors(); foreach (IProcess p in processorsForService1) { if (p.ProcessTimer != null) { p.ProcessTimer.Elapsed += new ElapsedEventHandler(IProcess_Timer_Elapsed); } } } And: private void IProcess_Timer_Elapsed(object sender, ElapsedEventArgs e) { IProcess p = (IProcess)sender; p.Step_One(); p.Step_Two(); } But when I get to the event handler im getting null reference exception for p on the first line. How do I pass an argument to the handler in this instance? A: It looks like you're using a System.Timers.Timer, if you were to use a System.Threading.Timer then you could pass a state object which, in this case, could be the desired instance of a class, i.e. the timer's 'owner'. In this way, you define your method body as with your previous experience of implementation within an event handler, only now the signature is as follows: private void MyTimerCallbackMethod(object state) { } Then, upon creating the timer instance, you can do something such as: var timerCallback = new TimerCallback(MyTimerCallback); var timer = new Timer(timerCallback, myStateObject, Timeout.Infinite, Timeout.Infinite); Then, use timer.Change(whenToStart, interval) to kick off the timer. A: The sender is the timer object, not the object associated with the handling delegate. For a start, events can have multiple handlers. What you could do is create a delegate which has access to the IProcess using variable capture. A: if you used a lambda instead of a delegate you could refer to the class from the lambda because it would still be in the referencing environment. I think this is called Closure. public void DoStuff() { List<IProcess> processorsForService1 = ProcessFactory.GetProcessors(); foreach (IProcess p in processorsForService1) { if (p.ProcessTimer != null) { p.ProcessTimer.Elapsed += (s, e) => { p.Step_One(); p.Step_Two(); }; } } } Beware of the following scope related rules though (taken from msdn): The following rules apply to variable scope in lambda expressions: * *A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope. *Variables introduced within a lambda expression are not visible in the outer method. *A lambda expression cannot directly capture a ref or out parameter from an enclosing method. *A return statement in a lambda expression does not cause the enclosing method to return. *A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function. A: Make the event handler a member of IProcess and set up like this: p.ProcessTimer.Elapsed += new ElapsedEventHandler(p.IProcess_Timer_Elapsed); and if you want to handle the event elsewhere, make the handler forward the event: class IProcess { public delegate void Timer_Elapsed_Handler (IProcess process, ElapsedEventArgs e); public event Timer_Elapsed_Handler Timer_Elapsed; public void IProcess_Timer_Elapsed (object sender, ElapsedEventArgs e) { if (Timer_Elapsed != null) Timer_Elapsed (this, e); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Equal Heights of Divs I have two columns that have draggable and droppable divs within them. I used this code: //Equal Height Divs function equalHeight( group ) { var tallest = 0; group.each(function() { var thisHeight = $(this).height(); if(thisHeight > tallest) { tallest = thisHeight; } }); group.each(function() { $(this).css( "min-height", tallest ); } ); } To make sure that as more divs are added to one column and that columns height gets larger so will the height of the second column. However I don't seem to know how to reverse this so that if I remove things from one column and the div height of both columns should get smaller. I know that I have over-complicated this so any help to sort out my confusion here would be much appreciated. A: Simply add $(this).css("height", "");, to reset the CSS height attribute, so that the height won't be greater than necessary. Without a set height property, the element will shrink to the minimum height: function equalHeight( group ) { var tallest = 0; group.each(function() { $(this).css({height:"", "min-height":""}); var thisHeight = $(this).height(); if(thisHeight > tallest) { tallest = thisHeight; } }); group.each(function() { $(this).css( "min-height", tallest ); } ); } A: I think I understand your question only to an extent. If you are trying to set the height of elements with the height of the highest element, you can use this code. It is assuming that the elements that you are working on has same class. var maxHeight = Math.max.apply(null, $('.common_classname').map(function() { return $(this).height(); }).get()); $('.common_classname').height(maxHeight);
{ "language": "en", "url": "https://stackoverflow.com/questions/7635653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using a SELECT CASE statement in ActiveRecord, as Rails model default_scope I have a model, User, which can either be an individual or a company, depending on the value of a boolean, is_company. If the user is a company, company_name stores the name; if the user is an individual, first_name and last_name stores their name. In the vast majority of cases, I want the users to be sorted by last_name OR company_name by default, so I'm using a default_scope in my User model. However, the way I have it - even though it works for SQLLite - is not database agnostic. Can anyone let me know how I can refactor this to accept a parameter of "true" in the case statement? default_scope select('users.*') default_scope select('CASE WHEN is_company = "t" THEN company_name ELSE last_name END AS sort_name') default_scope order('sort_name ASC') Thanks! A: You need to rethink your design. A user that can be a company doesn't sound like good design to me. I think you're better off with separate User and Company models. Your sorting will be much easier that way too.. A: You might want to do a modest redesign to handle this at the time you write to the database. * *Create a new column on your User table for display_name *Create a before_save callback in your User model that sets the display name like: before_save :set_display_name def set_display_name self.display_name = self.is_company? ? self.company_name : self.last_name end *Change your default_scope to just order by the new column
{ "language": "en", "url": "https://stackoverflow.com/questions/7635655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why my Emulator get restarted while i am going top run the Application in it? I have made a simple application in which i have use some buttons and some textView. On button click event i am using the selector which will display the appropriate image base on the Button click action. But i dont know what happend, and My Emulator got restarted. I have tried many times but still the emulator got restarted. Where is the problem i dont know. Please Help me in that. Thanks. And the Error after cleaning the project i got is: Error: [2011-10-03 19:01:11 - TaxCalculator] libpng error: Not a PNG file [2011-10-03 19:01:11 - TaxCalculator] ERROR: Failure processing PNG image E:\Android\Workspace\TaxCalculator\res\drawable-hdpi\email_icon.png [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\contect_us.xml:2: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/wawatermark'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\contect_us.xml:7: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/header_gradient'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\contect_us.xml:11: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_back_button'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\contect_us.xml:25: error: Error: No resource found that matches the given name (at 'src' with value '@drawable/contact_us_title'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\contect_us.xml:42: error: Error: No resource found that matches the given name (at 'src' with value '@drawable/phone_icon'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\contect_us.xml:53: error: Error: No resource found that matches the given name (at 'src' with value '@drawable/email_icon'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\menu_screen.xml:6: error: Error: No resource found that matches the given name (at 'src' with value '@drawable/tax_calculator_logo'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\menu_screen.xml:14: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_menu_button'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\menu_screen.xml:21: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_menu_button'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\menu_screen.xml:28: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_menu_button'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\layout\menu_screen.xml:35: error: Error: No resource found that matches the given name (at 'background' with value '@drawable/selector_menu_button'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\drawable\selector_back_button.xml:5: error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/back_pressed'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\drawable\selector_back_button.xml:8: error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/back_normal'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\drawable\selector_menu_button.xml:5: error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/button_blue'). [2011-10-03 19:01:11 - TaxCalculator] E:\Android\Workspace\TaxCalculator\res\drawable\selector_menu_button.xml:8: error: Error: No resource found that matches the given name (at 'drawable' with value '@drawable/button_white'). [2011-10-03 19:01:39 - TaxCalculator] Failed to install TaxCalculator.apk on device 'emulator-5554! [2011-10-03 19:01:39 - TaxCalculator] (null) [2011-10-03 19:01:39 - TaxCalculator] Launch canceled! A: Well, here no one give me answer. But i Got the Solution. Please read this carefully. Problem:I recently faced an issue where when I added my png file to an Android project it complained that it’s not a PNG file. Error I faced: [2011-07-24 19:54:00 - xxxx] libpng error: Not a PNG file [2011-07-24 19:54:00 - xxxx] ERROR: Failure processing PNG image C:\Users\pawana\workspace\xxxx\res\drawable-nodpi\background.png [2011-07-24 19:54:00 - xxxx] C:\Users\pawana\workspace\xxxx\res\layout\main.xml:7: error: Error: No resource found that matches the given name (at ‘background’ with value ‘@drawable/background’). Environment: I was using “windows 7″ for development and that file was opening file as a PNG File on Windows 7. I was puzzled what was happening. Background: I tried searching the web if someone else faced this issue and what as the solution. There were no good answers. I had verified my PNG was 24 bit. Android does support 24-bit and 32-bit. After lot of research it occured to me that maybe Android does not like the PNG format of “Adobe Photoshop”, too which I used to create the PNG. Solution: Final solution was to open the png file in MS Paint and re save it as png file. Once I did that Eclipse was able to use that file in Android project. I looked at what it changed, it convered the PNG to 32-bit format. Since Android supports both 24-bit and 32-bit PNGs, it makes me think there is something with “Adobe Phtoshop” generated PNGs which Android does not like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keygen and Checker C#? I am trying to implement a license feature in my software, i want to print the key on the CD and the user have to input the key in the system and the key will be validated then, that means that a key generated in the CD have to produce a value after decryption that will match the hard coded value on the software or something like that. Can somebody please tell me how to implement this kind of the thing or anything that work with the same i idea. thanks. A: As an indirect answer, I'd suggest you start by having a read through the answers to this question - it may be that you decide to take another approach to the licensing and protection of your software.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why am I getting "Warning: mysql_connect(): Access denied for user" when attempting to connect? I can connect to php/myadmin by using the connection string, but if i am trying to connect through my php page, then it's giving the following error. Warning: mysql_connect(): Access denied for user 'bf_cards_user'@'My Server IP' (using password: NO) in /home/blue204/html/download/test_connection.php Here is my code: $dbCon = mysql_connect('My Server IP', 'bf_cards_user', 'bbeqvfyAwPWECvWs'); if ($dbCon){ echo "connected"; } else { echo "not connected" ; } A: Have you allowed access to the MySQL server for the login/server combination you provide? grant all permissions on *.* 'bf_cards_user'@'My Server IP' identified by 'bbeqvfyAwPWECvWs'; flush privileges; A: You have made two mistakes here. The first mistake is you have passed "My Server IP" as your IP address. This is usually "localhost", but can also be an IP address for your server. Secondly (as pointed out in the comments of your OP), it says there is no password for the database yet you have stated one. You should ensure your database user has a password set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MS Access + NZ() function with empty table I am trying to add values from two different tables, but one of the tables is completely empty. I know the Nz() function is meant to convert Null values to a different value, i.e. 0, but the problem I am having is the table doesn't have any data, so Nz() doesn't work. Is there a way I can add the values of two tables together if one table is Null? I know it seems pointless, and eventually the table will have values, but for the sake of this week's reports, I need to do this. Thanks A: I suspect this is to do with your query. Try something on the lines of: SELECT Nz(t1.[Field1],0) + Nz(t2.[Field1],0) As Added FROM t1 LEFT JOIN t2 ON t1.ID = t2.ID The important point is LEFT JOIN, which will include all records from t1, even if there is no match in t2. A: Note that the Nz() function is not available outside of the Access UI. Here's an alternative approach that avoids Nz(): SELECT t1.Field1 + t2.Field1 AS Added FROM t1 INNER JOIN t2 ON t1.ID = t2.ID UNION SELECT 0 AS Added FROM t2 HAVING COUNT(*) = 0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7635673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error retrieving json with php I've some problem retrieving json information with a PHP. I've created a simple php page that returns a json: $data = array( 'title' => 'Simple title' ); print json_encode($data); And in another page I try to get that array as an object: $content = file_get_contents($url); $json_output = json_decode($content, true); switch(json_last_error()) { case JSON_ERROR_DEPTH: echo ' - Maximum stack depth exceeded'; break; case JSON_ERROR_CTRL_CHAR: echo ' - Unexpected control character found'; break; case JSON_ERROR_SYNTAX: echo ' - Syntax error, malformed JSON'; break; case JSON_ERROR_NONE: echo ' - No errors'; break; } The problem is that there is an error with this approach: I receive a "JSON_ERROR_SYNTAX" because after "file_get_contents" function I have an unknown character at the beginning of the string. If I copy/paste it on Notepad++ I didn't see: {"title":"Simple title"} but I see: ?{"title":"Simple title"} Could someone help me? A: Make sure both your scripts have same encoding - and if it's UTF make sure they are without Byte Order Mark (BOM) at very begin of file. A: What about $content = trim(file_get_contents($url)); ? Also, it sounds as if there was a problem with the encoding within the PHP that echos your JSON. Try setting proper (as in: content-type) headers and make sure that both files are UTF-8 encoded. Also: What happens if you open $url in your browser? Do you see an "?" A: I am pretty sure your page that does the json_encode has a stray ?. Look in there for a missing > in terms of ?> and such. A: Look through your PHP for a stray "?".
{ "language": "en", "url": "https://stackoverflow.com/questions/7635682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Template classes c++ friend functions My code has the same structure as the shown below. I have two container classes defined in a single header file and each one of them has a friend function with parameters of type the other class so I get a compiling error which is something like 'Class2' - undeclared identifier. Tried a few things but didn't work it out. I think that if add one more template parameter V to both of the templates and replace Class2<T> with it could be a solution but thing get much complicated if I use these containers in my program.I also thought to separate Class1 and Class2 into different headers and then include in Class1 Class2 and vice versa but I actually I doubt that this could work at all. I really can't figure out how to solve this problem so please your help is much appreciated! template<class T> class Class1 { ... friend void function1(Class1<Class2<T>>&, const Class2<T>&); ... }; template<class V> class Class2 { ... friend void function2(Class1<V>); ... }; A: Add a forward declaration for Class2 at the beginning of the file: template<class V> class Class2;
{ "language": "en", "url": "https://stackoverflow.com/questions/7635684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing android market form java application I want to build an java application, kind of a robot that periodically asks for exist apps based on a parameter (id, name, package...). What I want to know first is how to access the android market API (if there is any..) from my application. What plug-ins, additional jars in my build path do I need, to start communicating with the android market? More specifically, I saw some answers about how to search, based on given URL's, but my question is even more basic - what are the first steps to access the market? In other words, how do I create a client of the android market in me application. BTW, I am using eclipse for JavaEE. I have pretty good pure java programming knowledge, though working with JavaEE, and web application is quite new for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax.BeginForm response contains previous values even if I pass another model I'm having a simple action: [HttpPost] public virtual ActionResult New(Feedback feedback) { feedback.CreatedDate = DateTime.UtcNow; if (TryValidateModel(feedback)) { FeedbackRepository.Add(feedback); var model = new Feedback { SuccessfullyPosted = true }; return PartialView(MVC.Shared.Views._FeedBackForm, model); } return PartialView(MVC.Shared.Views._FeedBackForm, feedback); } So, idea is if received data is validating fine, return partial view with empty feedback entity. Thing is, that if i look at firebug response, I see old values coming back, how weird is this? Form looks like this: @using (Ajax.BeginForm(MVC.Feedback.New(), new AjaxOptions { UpdateTargetId = "contactsForm", HttpMethod = "post" })) { @Html.LabelFor(x => x.FirstName) @Html.EditorFor(x => x.FirstName) @Html.ValidationMessageFor(x => x.FirstName) @Html.LabelFor(x => x.LastName) @Html.EditorFor(x => x.LastName) @Html.ValidationMessageFor(x => x.LastName) @Html.LabelFor(x => x.Email) @Html.EditorFor(x => x.Email) @Html.ValidationMessageFor(x => x.Email) @Html.LabelFor(x => x.Phone) @Html.EditorFor(x => x.Phone) @Html.ValidationMessageFor(x => x.Phone) @Html.LabelFor(x => x.Comments) @Html.TextAreaFor(x => x.Comments, new { cols = 60, rows = 10 }) @Html.ValidationMessageFor(x => x.Comments) if (Model.SuccessfullyPosted) { Feedback sent successfully. } } Is it possible somehow to disable this behavior and how PartialView(MVC.Shared.Views._FeedBackForm, model) manages to get different model? update: I see stackoverflow ate all html from by view and can't find how to fix that. A: ModelState is primary supplier of model values. Even if you pass your model to View or PartialView, EdiorFor will first look into ModelState for corresponding property value, and if it does not exist there, only then into model itself. ModelState is populated when posting to controller (old feedback). Even if you create new feedback and pass it as model, ModelState already contains values from previously posted feedback, so you get old values on client. Clearing modelstate before successfull post result will help you. FeedbackRepository.Add(feedback); var model = new Feedback { SuccessfullyPosted = true }; ModelState.Clear(); // force to use new model values return PartialView(MVC.Shared.Views._FeedBackForm, model); See this and this links for examples of related situations
{ "language": "en", "url": "https://stackoverflow.com/questions/7635690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: writeToFile is not writing to the file Well I am experiencing a problem and I've been struggling with it for few days. Here it is: when trying to write to an xml file (placed in the xcode project which I am developing) using writeToFile, writing doesn't work and I can see nothing in the xml file although the bool value which is returned from writeToFile is being evaluated to true !! In addition, the file bytes are zero. So, I would really appreciate if anyone can help me out with that. Below is part of the code which I wrote: //writing to a file NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"xml"]; NSString *dummyString = @"Hello World!!\n"; NSFileManager *filemanager; filemanager = [NSFileManager defaultManager]; //entering the first condition so I assured that the file do exists if ([filemanager fileExistsAtPath:pathOfFile] == YES) NSLog (@"File do exist !!!"); else NSLog (@"File not found !!!"); BOOL writingStatus = [dummyString writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:nil]; //Not entering this condition so I am assuming that writing process is successful but when I open the file I can't find the string hello world and file size shows 0 bytes if(!writingStatus) { NSLog(@"Error: Could not write to the file"); } I also tried this alternative, but unfortunately it didn't work too. NSString *hello_world = @"Hello World!!\n"; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *directory = [paths objectAtIndex:0]; NSString *fileName = @"sample.xml"; NSString *filePath = [directory stringByAppendingPathComponent:fileName]; NSLog(@"%@",filePath); BOOL sucess = [hello_world writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil]; if(!sucess) { NSLog(@"Could not to write to the file"); } A: In the first piece of code, we can't see the definition of path. If that's a typo and you meant file_path, the problem is that file_path points to a path inside the app bundle. You can't write inside your app bundle. (There shouldn't be any typos, because you should be pasting the code directly.) In the second case, it's harder to tell what the problem is. filePath should be in the documents directory, which is writeable. However, it'd be a lot easier to diagnose the problem if you were getting an actual error. Instead of passing nil for the error parameter in -writeToFile:atomically:encoding:error:, create a NSError* variable and pass in its address. If there's a problem, then, your pointer will be set to point to an NSError object that describes the problem. A: The fact that writeToFile: is returning a boolean value of YES simply means that the call is completing. You should be passing an NSError** to writeToFile: and examining that, e.g: NSError *error = nil; BOOL ok = [hello_world writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:&error]; if (error) { NSLog(@"Fail: %@", [error localizedDescription]); } That should give you a good clue about what is going wrong (assuming error is not nil after the call). A: -(void)test{ //writing to a file NSError *error; NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@".xml"];//was missing '.' NSString *dummyString = @"Hello World!!\n"; NSFileManager *filemanager; filemanager = [NSFileManager defaultManager]; //entering the first condition so I assured that the file do exists //the file exists in the bundle where you cannot edit it if ([filemanager fileExistsAtPath:pathOfFile]){ NSLog (@"File do exist IN Bundle MUST be copied to editable location!!!"); NSArray *locs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docsDir = [[locs objectAtIndex:0]stringByAppendingString:@"dummyFile"]; NSString *file = [docsDir stringByAppendingPathComponent:@".xml"]; [filemanager copyItemAtPath:pathOfFile toPath:file error:&error]; } else{ NSLog (@"File not found in bundle!!!"); } if (error) { NSLog(@"error somewhere"); } //if youre only messing with strings you might be better off using .plist file idk BOOL success = [dummyString writeToFile:file atomically:YES encoding:NSUnicodeStringEncoding error:nil]; //Not entering this condition so I am assuming that writing process is successful but when I open the file I can't find the string hello world and file size shows 0 bytes if(!success) { NSLog(@"Error: Could not write to the file"); } } A: //I typically do something like this //lazy instantiate a property I want such as array. -(NSMutableArray*)array{ if (!_array) { _array = [[NSMutableArray alloc]initWithContentsOfFile:self.savePath]; } return _array; } //I'm using a class to access anything in the array from as a property from any other class //without using NSUserDefaults. //initializing the class -(instancetype)init{ self = [super init]; if (self) { //creating an instance of NSError for error handling if need be. NSError *error; //build an array of locations using the NSSearchPath... NSArray *locs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //location 0 of array is Documents Directory which is where I want to create the file NSString *docsDir = [locs objectAtIndex:0]; //my path is now just a matter of adding the file name to the docsDir NSString *path = [docsDir stringByAppendingPathComponent:@"fileName.plist"]; //if the file is a plist I have in my bundle I need to copy it to the docsDir to edit it //I'll do that by getting it from the bundle that xCode made for me NSString *bunPath = [[NSBundle mainBundle]pathForResource:@"fileName" ofType:@".plist"]; //now I need a NSFileManager to handle the dirty work NSFileManager *filemngr = [NSFileManager defaultManager]; //if the file isn't in my docsDir I can't edit so I check and if need be copy it. if (![filemngr fileExistsAtPath:path]) { [filemngr copyItemAtPath:bunPath toPath:path error:&error]; //if an error occurs I might want to do something about it or just log it as in below. //I believe you can set error to nil above also if you have no intentions of dealing with it. if (error) { NSLog(@"%@",[error description]); error = nil; } //here I'm logging the paths just so you can see in the console what's going on while building or debugging. NSLog(@"copied file from %@ to %@",bunPath,path); } //in this case I'm assigning the array at the root of my plist for easy access _array = [[NSMutableArray alloc]initWithContentsOfFile:path]; _savePath = path;//this is in my public api as well for easy access. } return self; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: MVC3 render scripts in partial view Hopefully someone out there can help me with this.....I'm building an MVC3 project and I can't seem to figure out why my partial view cannot execute any inline javascript functions. Here is made up example, but will hopefully show the principal I am trying to achieve.... I have a list of items in a view, called Items. foreach (var item in Model.SaleItems) { <div>@Html.ActionLink((string)item.ID, "Item", new { ID = @item.ID })</div> } If the user clicks one of the items, they will be sent to a page with details about the item selected. On this page, there is a menu will 3 choices; details, reviews, images (each is a partial view). If the user selects the details option from the menu, the details partial will render a few charts from a webservice like the Google visualization API. Here is my partial view with a script to load a chart : <div> <h4>Details</h4> <div id= "detailsContainer"></div> </div> <script type="text/javascript"> $(document).ready(function () { google.load('visualization', '1', { packages: ['table'] }); google.setOnLoadCallback(drawDetailsTable); }); function drawDetailsTable() { var data = new google.visualization.DataTable(); data.addColumn('string', ''); data.addColumn('string', ''); data.addRows(4); data.setCell(0, 0, 'Color'); data.setCell(0, 1, '<b>@Model.Color</b>'); data.setCell(1, 0, 'Size'); data.setCell(1, 1, '<b>@Model.Size</b>'); data.setCell(2, 0, 'Weight'); data.setCell(2, 1, '<b>@Model.Weight</b>'); data.setCell(3, 0, 'Material'); data.setCell(3, 1, '<b>@Model.MainMaterial</b>'); var table = new google.visualization.Table(document.getElementById('detailsContainer')); var options = { allowHtml: true }; table.draw(data, options); } </script> Anyone have any ideas why this doesn't work? If I move the script from the partial view to the view, and statically declare an item in the main view's ActionResult, it will work, but other than that it doesn't. Thanks in advance! A: I finally figured it out. Shuniar was correct, scripts should execute in the partial views, but the problem is with the Google maps and visualization APIs. The partial view would render but the function that was never being called in the script. This make sense because there is no onLoad for partial views. google.setOnLoadCallback(drawDetailsTable); function drawDetailsTable() { .... }); To fix it, I simply changed it to explicitly call the function as the partial is being rendered. google.setOnLoadCallback(drawDetailsTable); drawDetailsTable(); function drawDetailsTable() { .... });
{ "language": "en", "url": "https://stackoverflow.com/questions/7635702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JAAS and Security - how to use custom tables with GlassFish Security? Is it possible to use JAAS with GlassFish but using my custom tables ? I've got a mapping like this tbUser -> user_roles <- tbRoles It's a manytomany with users and roles mapped by an Id into user_roles table, so for this to work with JAAS and GlassFish I would need to change GlassFish custom select to one made by me. Is it possible to make glassfish use that setup instead of it's default user_table, role_table without relations ? I need to use this setup for db, because of the client reqs. A: You may want to use JDBCRealm in GlassFish: http://blogs.oracle.com/swchan/entry/jdbcrealm_in_glassfish . A: This post may help: http://weblogs.java.net/blog/kumarjayanti/archive/2010/02/01/using-custom-jaas-loginmodules-authentication-glassfish
{ "language": "en", "url": "https://stackoverflow.com/questions/7635704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "deadlock detected" errors on Rails 2.3.14 site -- Passenger 3.0.9, Ruby 1.9.2 About every 3rd time my app serves a particular update action (two that I've found so far), it bombs out with a "deadlock detected" error. I haven't been able to trace it to any of our own application code. It seems that the action completes, but then this crash happens as either Rails or Passenger is wrapping it up. (It doesn't happen from just saving records in script/console.) Here is what comes up in the logs when it happens: https://gist.github.com/1259104 What's going on, and what do I do about it? (note: have switched to RVM-based Ruby 1.9.2, and issue persists.) A: The issue appears to be this: https://rails.lighthouseapp.com/projects/8994/tickets/5736-connections-not-released-in-rails-3 However, above issue only pertains to Rails 3. We are seeing it in Rails 2.3.14 under Ruby 1.9.2. The patch to connection_pool.rb given there works for us. That particular file appears to be identical between 2.3.14 and 3.1.0 beta so the patch is likewise the same. We had to patch the gem itself -- doing it by loading the new file/class as part of the Rails app itself didn't do the trick -- but the behavior is the same for us as is being reported there -- instead of deadlocking/running out of db connections, there's a short delay. In conjunction with bumping up the pool size in the production db config in database.yml, this works pretty acceptably, though I do hope for an even better solution. & Thanks to Alex Caudill for finding this for us!
{ "language": "en", "url": "https://stackoverflow.com/questions/7635705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenCL built-in function 'select' It's not clear for me what is a purpose of built-in OpenCL function select. Can somebody, please, clarify? From OpenCL specification: function select(gentype a, gentype b, igentype c) returns: for each component of a vector type, result[i] = if MSB of c[i] is set ? b[i] : a[i]. What is a MSB in this case? I know that MSB stands for most significant bit, but I have no idea how it's related to this case. A: OpenCL select is to select elements from a pair of vectors (a, b), based on the truth value of a condition vector (c), returning a new vector composed of elements from the vectors a and b. The MSB (most significant bit) is mentioned here, because the truth value of a vector element is defined to be -1 and the MSB should therefore be set (as the sign bit): a = {1 , 2} // Pseudocode for select operands b = {3 , 4} c = {0 ,-1} r = {1 , 4} // The result r contains some of a and b A: This is a very useful operator which does the same job as what a conditional expression does in C. However, conditional expression often compiles to a conditional branch which cause warp/wavefront divergence. The 'select' usually generates a predicated expression - kind of like CMOV on x86 or blend_ps in SSE. A: I have found 2 basic patterns of using select: scalar case and vector case. Scalar case is pretty straightforward: if (a > 0.0f) b = 0.3f; is equivalent to b = select(b, 0.3f, isgreater(a, 0.0f)); If wanted to deal with vectors, i.e. obtain a vector result from select everything became a bit more complicated: if (a > 0.0f) b = (float2)(0.3f, 0.4f); is equivalent to b = select(b, (float2)(0.3f, 0.4f), (int2)(isgreater(a, 0.0f) << 31)); That bit-wise shift needed to make LSB result of comparison operator to be MSB to conform select specification. Casting to int2 ensures that all components will take their positions in result. Concluding remark is that using snippets above helps more to understand usage of select rather then thinking of equivalence with C ternary operator ?:.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regarding htaccess, PHP and hidden variable passing Alright, I have a problem. Let's say that I want to be able to visit this url `forum.mysite.com/offtopic/23894/` and for it to pass the variables `forum.mysite.com/file.php?board=offtopic&thread=23894` without anyone seeing the string. Is there any way I can do this, either with .htaccess or anything else? A: RewriteEngine on RewriteRule /([^/]+)/([0-9]+)/ file.php?board=$1&thread=$2 That should work if you put it in a .htaccess file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linking CUDA and C++: Undefined symbols for architecture i386 I have tried really hard but no success. I hope someone can help me get this working. I have two source files. Main.cpp #include <stdio.h> #include "Math.h" #include <math.h> #include <iostream> int cuda_function(int a, int b); int callKnn(void); int main(void) { int x = cuda_function(1, 2); int f = callKnn(); std::cout << f << std::endl; return 1; } CudaFunctions.cu #include <cuda.h> #include <stdio.h> #include "Math.h" #include <math.h> #include "cuda.h" #include <time.h> #include "knn_cuda_without_indexes.cu" __global__ void kernel(int a, int b) { //statements } int cuda_function2(int a, int b) { return 2; } int callKnn(void) { // Variables and parameters float* ref; // Pointer to reference point array float* query; // Pointer to query point array float* dist; // Pointer to distance array int ref_nb = 4096; // Reference point number, max=65535 int query_nb = 4096; // Query point number, max=65535 int dim = 32; // Dimension of points int k = 20; // Nearest neighbors to consider int iterations = 100; int i; // Memory allocation ref = (float *) malloc(ref_nb * dim * sizeof(float)); query = (float *) malloc(query_nb * dim * sizeof(float)); dist = (float *) malloc(query_nb * sizeof(float)); // Init srand(time(NULL)); for (i=0 ; i<ref_nb * dim ; i++) ref[i] = (float)rand() / (float)RAND_MAX; for (i=0 ; i<query_nb * dim ; i++) query[i] = (float)rand() / (float)RAND_MAX; // Variables for duration evaluation cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); float elapsed_time; // Display informations printf("Number of reference points : %6d\n", ref_nb ); printf("Number of query points : %6d\n", query_nb); printf("Dimension of points : %4d\n", dim ); printf("Number of neighbors to consider : %4d\n", k ); printf("Processing kNN search :" ); // Call kNN search CUDA cudaEventRecord(start, 0); for (i=0; i<iterations; i++) knn(ref, ref_nb, query, query_nb, dim, k, dist); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsed_time, start, stop); printf(" done in %f s for %d iterations (%f s by iteration)\n", elapsed_time/1000, iterations, elapsed_time/(iterations*1000)); // Destroy cuda event object and free memory cudaEventDestroy(start); cudaEventDestroy(stop); free(dist); free(query); free(ref); return 1; } I try run it from terminal with the following commands: g++ -c Main.cpp -m32 nvcc -c CudaFunctions.cu -lcuda -D_CRT_SECURE_NO_DEPRECATE nvcc -o mytest Main.o CudaFunctions.o But get following errors: Undefined symbols for architecture i386: "cuda_function(int, int)", referenced from: _main in Main.o "_cuInit", referenced from: knn(float*, int, float*, int, int, int, float*)in CudaFunctions.o "_cuCtxCreate_v2", referenced from: knn(float*, int, float*, int, int, int, float*)in CudaFunctions.o "_cuMemGetInfo_v2", referenced from: knn(float*, int, float*, int, int, int, float*)in CudaFunctions.o "_cuCtxDetach", referenced from: knn(float*, int, float*, int, int, int, float*)in CudaFunctions.o ld: symbol(s) not found for architecture i386 collect2: ld returned 1 exit status I don't know if this has something to do with #include statements or header files. I am left of ideas to try. A: The first undefined symbol "cuda_function(int, int)", referenced from: _main in Main.o is caused by the fact that CudaFunctions.cu defines cuda_function2, not cuda_function. Correct the name either in CudaFunctions.cu or Main.cpp. The rest of the undefined symbols are caused by not linking against libcuda.dylib correctly, because that is where those symbols live. Try moving the -lcuda argument to the second nvcc command line, the one that actually links together the program. Better yet, try omitting the -lcuda argument entirely, because it isn't necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is this a good REST URI? Is the following URI good in REST or how can it be improved? This is the service definition: (REST and SOAP - WCF) [OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Services?CostCentreNo={CostCentreNo}&Filter={Filter}")] List<Services> GetServices(Int32 CostCentreNo, Int32 Filter); This would give an example URI as: http://paul-hp:1337/WCF.IService.svc/rest/Services?CostCentreNo=1&Filter=1 I have a lot of get methods. and a few insert methods. Is the URI acceptable. Does it need GET/ in it or something? edit: Okay, now i undstand it more: So If I had a sub service, it would(could) be /CostCenters/{CostCentreNo}/Services/{ServiceID}/SubService and, Insert Room booking (with over 20 parameters) could be /CostCentres/{CostCentreNo}/Rooms/{RoomNo}/Booking?param1={param1}....&param20=‌​{param20} A: hmm... one of the reasons folks use REST is to avoid query strings for anything other than actual queries. In your case, a CostCentre probably deserves its own URL, as well as a separate URL for its services. Based on your example, in my opinion only the Filter should be a query string. I would structure your URL as follows: /CostCenters/{CostCentreNo}/Services?Filter={Filter} Edit: Okay, now i undstand it more: So If I had a sub service, it would(could) be /CostCenters/{CostCentreNo}/Services/{ServiceID}/SubService and, Insert Room booking (with over 20 parameters) could be /CostCentres/{CostCentreNo}/Rooms/{RoomNo}/Booking?param1={param1}....&param20=‌​{param20} I would recommend granting individual entities that can exist on their own URLs that are closer to the parent hierarchy, if possible. Obviously I don't know your system, but my guess is that you might want to do something along the lines of: /CostCenters/{CostCenterNo} /Services/{ServiceID} /Rooms/{RoomNo} Only use hierarchies like /CostCenters/{CostCentreNo}/Services/{ServiceID}/ when a Service cannot exist without a CostCenter. If that is the case, by all means, go with such a hierarchy. If a Service can exist without a CostCenter, go with the former hierarchy above. One last thing. This URL from your example: /CostCenters/{CostCentreNo}/Services/{ServiceID}/SubService only makes sense if a Service can have one and only one SubService. I'm betting that your example needs a SubServiceID or something similar. And following my advice above, I would definitely say that a SubService absolutely would need to be extending a Service URL, e.g.: /Services/{ServiceID}/SubServices/{SubServiceID} In the above case, I would expect that a SubServiceID references the same entity pool as ServiceID, and that whatever data or view is returned by this URL would include both the Service and SubService.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to prevent keyboard from hiding? Say I have an InputService ( keyboard ) that starts an activity. Since the activity has a transparent background, it is seen, that going on under it. Once the activity starts, the keyboard hides from under it and remains hidden after the activity has ended. How to I prevent it from hiding? Intent PopIntent = new Intent(getBaseContext(), popup.class); PopIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getApplication().startActivity(PopIntent); A: Just do this: //Show soft-keyboard: getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); A: i'm stranded at the exactly the same problem :-(. did you meanwhile found a solution? i tried to open the keyboard programmatically again after i come back to the originally activity and simulate a touchevent on the TextView so that the TextView is bound again to the InputMethodService: Runnable r = new Runnable() { @Override public void run() { final Instrumentation inst = new Instrumentation(); int[] location = new int[2]; tvEdit1.getLocationOnScreen(location); long time1 = SystemClock.uptimeMillis(); long time2 = SystemClock.uptimeMillis(); MotionEvent mv = MotionEvent.obtain(time1, time2, MotionEvent.ACTION_DOWN, location[0], location[1], 0); inst.sendPointerSync(mv); time1 = SystemClock.uptimeMillis(); time2 = SystemClock.uptimeMillis(); mv = MotionEvent.obtain(time1, time2, MotionEvent.ACTION_UP, location[0], location[1], 0); inst.sendPointerSync(mv); } }; Thread t = new Thread(r); t.start(); That works if i know which TextView the user clicked. Is there a way to find in a InputMethodService Class the correlating position of the bound TextView? With position i mean the x und y coordinates for simulating a touchevent on that position.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: type declarations in 'where' -- what's going on? While reading the QuickCheck Manual, I came across the following example: prop_RevRev xs = reverse (reverse xs) == xs where types = xs::[Int] The manual goes on to say: Properties must have monomorphic types. `Polymorphic' properties, such as the one above, must be restricted to a particular type to be used for testing. It is convenient to do so by stating the types of one or more arguments in a where types = (x1 :: t1, x2 :: t2, ...) clause. Note that types is not a keyword; this is just a local declaration which provides a convenient place to restrict the types of x1, x2 etc. I have never seen such a trick in Haskell before. Here's what I'm really having problems with: * *Why does this syntax for type declarations even exist? What can it do for me that the following couldn't? prop_RevRev :: [Int] -> Bool prop_RevRev xs = reverse (reverse xs) == xs *Does this use of where constitute 'special' syntax for type declarations? Or is it consistent and logical (and if so, how?)? *Is this usage standard or conventional Haskell? A: It is no special syntax, and sometime you just need it, like in the following case: foo :: String -> String foo s = show (read s) As it stands, this cannot be typed because the type of the value read s cannot be identified. All that is known is that it must be an instance of Show and of Read. But this type does not appear in the type signature at all, so it is also not possible to leave it at that and infer a constrained type. (There is just no type variable that could be constrained.) It is interesting to note that what read s does depends entirely on the type signature one gives to read s, for example: read "Just True" :: (Maybe Bool) will succeed, while read "Just True" :: (Maybe Int) will not. A: where is not special syntax for type declarations. For example, this works: prop_RevRev :: [Int] -> Bool prop_RevRev xs = ys == xs where ys = reverse (reverse xs) and so does this: prop_RevRev xs = ys == xs where ys = reverse (reverse xs) ys :: [Int] The advantage of where type = (xs :: [Int]) over prop_RevRev :: [Int] -> Bool is that in the latter case you have to specify the return type, while in the former case the compiler can infer it for you. This would matter if you had a non-Boolean property, for example: prop_positiveSum xs = 0 < length xs && all (0 <) xs ==> 0 < sum xs where types = (xs :: [Int])
{ "language": "en", "url": "https://stackoverflow.com/questions/7635720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Add search box for getting started search box I want to add a search box for getting started example (Hello, World) on chrom extensions http://code.google.com/chrome/extensions/getstarted.html, I was able to add a search box so I can change the word/s are used to get different thumbnails ("text=hello%20world"). The problem I faced is how to refresh the contents with a new thumbnails, for ex.: If I want to search for word jerusalem and click go button the contents (thumbnails) will be updated with a new thumbnails for jerusalem Do I need to use AJAX? Please explain. Thanx for any help. ==================== I included jquery in popup.html Inside showPhotos() function I did the following: function showPhotos() { //Remove previous thumbs if any for (var i = document.images.length; i-- > 0;) document.body.removeChild(document.images[i]); var photos = req.responseXML.getElementsByTagName("photo"); for (var i = 0, photo; photo = photos[i]; i++) { var img = document.createElement("image"); var span = document.createElement("span"); var span1 = document.createElement("span"); $(span1).attr('id', 'innerSpan'); $(span1).attr('style', 'text-align:center;color:#ffffff;'); $(span1).addClass('tooltip black bottom center w100 slide-up'); $(span1).html('<i>' + photo.getAttribute("title") + '</i>'); $(span).addClass('savytip'); $(span).attr('id', 'outerSpan'); $(img).attr('src', constructImageURL(photo)); $(span1).appendTo(span); $(img).appendTo(span); $(span).appendTo('body'); }} The extension just work for the first time and the go button stop responding, where is the wrong in my code? A: This example is already using AJAX, aka XHR(XMLHttpRequest). All you need to do is put the request inside a function to be able to call it again later. Also You'll need to remove the previous thumbs before appending the new ones(see the first line of 'showPhotos' function). Here's a working example: popup.html <html> <head> <script type="text/javascript" src="popup.js"></script> <link rel="stylesheet" type="text/css" href="popup.css"> </head> <body onload="search()"> <input id="query" value="Hello World"><input type="button" value="go" onclick="search()"> </body> </html> popup.js function search() { request(document.getElementById('query').value); return false; } function request(query) { window.req = new XMLHttpRequest(); req.open( "GET", "http://api.flickr.com/services/rest/?" + "method=flickr.photos.search&" + "api_key=90485e931f687a9b9c2a66bf58a3861a&" + "text="+encodeURI(query)+"&" + "safe_search=1&" + // 1 is "safe" "content_type=1&" + // 1 is "photos only" "sort=relevance&" + // another good one is "interestingness-desc" "per_page=20", true); req.onload = showPhotos; req.send(null); } function showPhotos() { //Remove previous thumbs if any for(var i=document.images.length;i-->0;) document.body.removeChild(document.images[i]); var photos = req.responseXML.getElementsByTagName("photo"); for (var i = 0, photo; photo = photos[i]; i++) { var img = document.createElement("image"); img.src = constructImageURL(photo); document.body.appendChild(img); } } // See: http://www.flickr.com/services/api/misc.urls.html function constructImageURL(photo) { return "http://farm" + photo.getAttribute("farm") + ".static.flickr.com/" + photo.getAttribute("server") + "/" + photo.getAttribute("id") + "_" + photo.getAttribute("secret") + "_s.jpg"; } popup.css body { min-width:357px; overflow-x:hidden; } img { margin:5px; border:2px solid black; vertical-align:middle; width:75px; height:75px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I return control from my python script to the calling bash script? I am using a bash script to loop through a configuration file and, based on that, call a python script via ssh. Unfortunately once the Python script does its job and I call quit the bash script also gets closed, therefore the calling bash script's loop is terminated prematurely. Here's my Bash Script target | grep 'srv:' | while read l ; do srv $l $SSH ; done srv () { SSH=$2 SRV=`echo $1 | awk -F: '{print $2}'` STATUS=`echo $1 | awk -F: '{print $3}'` open $SSH "srv" $SRV $STATUS } then on the remote machine where the python script is called if __name__== "main": redirect('./Server.log', 'false') conn() if sys.argv[1] == "srv": ServerState(sys.argv[2], sys.argv[3]) quit() So looks like the quit() is also interrupting the script. A: Nothing that the remote Python script does should be able to kill your do loop unless you have done a set -e in the local bash first to make it sensitive to command failure — in which case it would die only if, as @EOL says, your remote script is hitting an exception and returning a nonzero/error value to SSH which will then die with a nonzero/error code locally. What happens if you replace do srv with do echo srv so that you just get a printout of the commands you think you are running? Do you see several srv command lines get printed out, and do they have the arguments you expect? Oh: and, why are you using open to allocate a new Linux virtual terminal for every single run of the command? You do not run out of virtual terminals that way? A: It looks like quit() is the function that makes your program stop. If you can remove the call to quit() (i.e. if it does nothing), just remove it. Otherwise, you can run your Python program by hand (not from a shell script) and see what happens: it is likely that your Python script generates an exception, which makes the shell script stop. By running your Python program manually with realistic arguments (on the remote machine), you should be able to spot the problem. A: You should be able to simply return from the main function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extend ANTLR3 AST's With ANTLR2, you could define something like this in grammar definition file: options { language = "CSharp"; namespace = "Extended.Tokens"; } tokens { TOKEN<AST=Extended.Tokens.TokenNode>; } And then, you could create a class: public class TokenNode: antlr.BaseAST { ... } Any ideea if something like this can be used (delegate class creation to AST factory instead of me doing the tree replication manually)? It's not working just by simple grammar definition copy from old to new format, and I tried to search their site and samples for somthing similar. Any hints? EDIT I'm not trying to create custom tokens, but custom 'node parsers'. In order to 'execute' a tree you have 2 choices (as far as I understood): * *create a 'tree visitor' and handle values, or *create a tree parser by 'almost-duplicating' the grammar definition. In v2 case, I could decorate the tree node to whateveer method I would have liked and then call them after the parser ran by just calling something like 'execute' from root node. A: I know little C#, but there shouldn't be much difference with the Java target. You can create - and let ANTLR use - a custom tree by setting the ASTLabelType in the options { ... } section (an XTree in this case): T.g grammar T; options { output=AST; ASTLabelType=XTree; } tokens { ROOT; } @parser::header { package demo; import demo.*; } @lexer::header { package demo; import demo.*; } parse : Any* EOF -> ^(ROOT Any*) ; Any : . ; You then create a custom class which extends a CommonTree: demo/XTree.java package demo; import org.antlr.runtime.*; import org.antlr.runtime.tree.*; public class XTree extends CommonTree { public XTree(Token t) { super(t); } public void x() { System.out.println("XTree.text=" + super.getText() + ", children=" + super.getChildCount()); } } and when you create an instance of your TParser, you must create and set a custom TreeAdaptor which creates instances of your XTree: demo/Main.java package demo; import org.antlr.runtime.*; import org.antlr.runtime.tree.*; public class Main { public static void main(String[] args) throws Exception { String source = "ABC"; TLexer lexer = new TLexer(new ANTLRStringStream(source)); TParser parser = new TParser(new CommonTokenStream(lexer)); parser.setTreeAdaptor(new CommonTreeAdaptor(){ @Override public Object create(Token t) { return new XTree(t); } }); XTree root = (XTree)parser.parse().getTree(); root.x(); } } Running the demo: java -cp antlr-3.2.jar org.antlr.Tool T.g -o demo/ javac -cp antlr-3.2.jar demo/*.java java -cp .:antlr-3.2.jar demo.Main will print: XTree.text=ROOT, children=3 For more info, see: http://www.antlr.org/wiki/display/ANTLR3/Tree+construction
{ "language": "en", "url": "https://stackoverflow.com/questions/7635729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Load / Performance tests (HTTP and Web) I'm looking for a load test tool, the main features that I need is: * *Distribution (very important) - I need to be able to run something like 20,000 - 30,000 request per seconds (and more), so one machine is not enough. It should be able to communicate on Amazon EC2 (jMeter for example, can not do it) *Collecting data - It doesn't matter if it can produce graphs or complex data or not, but I should be able to know what was the Throughput of the client and the server, how many errors occured etc. Since it will run on multiple computers, the data should be collected by the tool itself (again jMeter does it, but it has a lot of problems), I'm trying to avoid from fetching data from different machines and merging it "manually". *Graphs or more complex data are nice to have (for example: http://code.google.com/p/multi-mechanize/), but if the tool doesn't provide it, I should be able to get this data from the logs of the tests. I didn't find good reviews on load testing tools (and that's why I'm asking here), and currently the main tool that I'm want to check is Grinder, if you've worked with good tools please share :) I've worked with jMeter, and I've decided to look for a better tool. jMeter is old, it works with old protocols (So I can't work with it distributed on EC2), it slow and hard to work with, and its graphs make it very slow. BTW, It doesn't have to be free / open source, if it costs up to tens or hundreds of dollars its OK. Thanks. A: Locust is a great load testing tool and it meets all of the OP's requirements. As far as meeting the OP's requirements, some Locust features: * *can run in master/slave mode for distributed load generation *gives you access to raw and summarized result data in simple/parseable formats *integrates nicely with graphite/grafana for your visualization needs Locust is open source and written in Python... virtual users are also written in Python code. The power and ease of using Python to develop complex workloads is really nice (compare that to JMeter's clunky declarative XML style). Locust development is hosted on Github and has several active committers. on the Locust website, the tagline is: "Define user behaviour with Python code, and swarm your system with millions of simultaneous users." screenshot of optional web UI: Note: I've worked with all the other tools recommended in other answers, and Locust is far superior A: Visual Studio's Web Performance Tests and Load Tests sound like a good fit here. If you get a license for Visual Studio Ultimate and then a license for Visual Studio Controller/Agents the controllers and agents handle the distribution of load. It is all very well documented and pretty easy to get set up. It has some default reporting that may meet your needs, but also has the ability to export to excel where you can create any custom reports or graphs using Pivot Tables (or external tools like PowerPivot). Here is the quick reference guide: http://vsptqrg.codeplex.com/ and more info is available all over on the web. A: The question states that it is not possible to use JMeter on Amazon ec2 [point 1.]. This is not true, it is possible, but it is made difficult because JMeter uses RMI to communicate and you have to play with tunnels and changing ports to make that work. The other JMeter issue mentioned [point 2.] is that it has a 'lot of problems' collating data. I suspect this refers to a potential bottleneck where all the data from multiple clients is being written to one location. If so, then his issue is typically addressed by using 'batched' or 'statistical' mode in the properties, plus the latest JMeter version, 2.6, has advances in this area. However, I wrote a script that gets around both these problems and makes running JMeter on ec2 considerably easier. A: You can use WebLOAD. I has built in support for automatically launching load machines on EC2, collects all the data and has good reporting capabilities. A: For these numbers of requests I would look a Tsung although (similar to Jmeter) this is XML declarative in terms of load specification. If you are more comfortable with coding a web driver then the Grinder would be worth alook (both Open Source). A: Actually we use Amazon EC2 to run cloud load test with JMeter. It's not so hard as you think. Advantage of JMeter than two tools (Grinder, Tsung) is documentation and community. jMeter is old, it works with old protocols (So I can't work with it distributed on EC2) JMeter last nightly build was yesterday and it means it's not so old as you think. You can check it here. EC2 uses WSDL for API calls, it's common protocol not new, here is EC2 API documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using CodeModuleListener + Blackberry I am trying to use CodeModuleListener in my application. I am testing this on simulator. After I run my application I add another cod file to the simulator but the moduleAdded(..) method of CodeModuleListener is not called, when I expect it would be. public static void main(String[] args) { Application_Load theApp = new Application_Load(); theApp.enterEventDispatcher(); try { CodeModuleManager.addListener(UiApplication.getApplication(), cmListener); } catch (NullPointerException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public Application_Load() { cmListener = new CodeModuleListener() { public void modulesDeleted(String[] moduleNames) { String s = "APP DELETED ====================>"; System.out.println(s); //writeFile(s, "file:///SDCard/uploadedfile.txt"); deleteFile("file:///system/databases/TestApp/TestDB.db"); } public void modulesAdded(int[] handles) { String s = "APP ADDED ====================>"; System.out.println(s); //writeFile(s, "file:///SDCard/uploadedfile.txt"); deleteFile("file:///system/databases/TestApp/TestDB.db"); } public void moduleDeletionsPending(String[] moduleNames) { String s = "APP IS DELETING ====================>"; System.out.println(s); //writeFile(s, "file:///SDCard/uploadedfile.txt"); deleteFile("file:///system/databases/TestApp/TestDB.db"); } }; UiApplication.getUiApplication().invokeLater(new Runnable(){ public void run() { UiApplication.getUiApplication().pushScreen(new TestScreen()); } }); } A: Add listener before the theApp.enterEventDispatcher(); call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which features of BizTalk are essential? I collect information about BizTalk and all its stuff. I'm curious about what are the best practices when developing a new integration project? Should I really use ESB Toolkit (which seems to me quite odd and way complex)? Is it really a bad idea to use UDDI services? What components of BizTalk do you really use? A: I guess the answer to your question is dependent on the problem(s) you're trying to solve. I've recently finished a project for which I considered using the ESB Toolkit for error handling but eventually decided that the scope of the project wasn't big enough for the extra effort required to setup and learn how to use it! For me, the most useful "feature" of BizTalk I use is direct-binding in my orchestrations to produce de-coupled orchestrations. But again, thats what I needed for the specific scenario. BizTalk is a massive product and I would suggest that you use the available functionality only if it solves you problem simply (don't attempt to provide over-engineered solutions!) By all means investigate all the functionality that interests you; there's a huge store of resource available and lots of helpful individuals here on SO! There's my pennies worth :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7635753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to inject PesistenceContext in my tests using EJB 3.1? Hi in Spring it's easy to do so... as Spring doesn't require an Container, you just add an @autowired and it's done. But in EJB 3.1, using @Inject is useless if the app is not deployed... I am getting nullpointer and it's looks logical to get them, because of the lack of a container during tests. How can I inject a PersistenceContext into my TESTS for example using only EJB 3.1 features ? is it possible without a container ? A: Take a look at the Arquillian project. It allows outside container testing of Java EE applications. http://www.jboss.org/arquillian A: Glassfish 3.x will allow you to embed the container and run your tests. Here's a few links that should get you going: * *Unit Testing EJBs and JPA with Embeddable GlassFish *JPA Unit testing with the GlassFish 3 embedded EJB container *Adam Bien's Weblog
{ "language": "en", "url": "https://stackoverflow.com/questions/7635756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access non-visible flex components? I'm a newbie to flex and am building a flex 4.5 app that has a custom component extending SkinnableContainer. This custom component is basically a kind of collapsible panel. When you open it you see all the controls in the contentGroup, when you close they go away and you are left with the title. This is done in the skin by having the contentGroup included only in the open state. I have a bunch of these containers in the app, some open by default and some closed. So in mxml the structure looks like: <ui:MyCustomContainer open="false" label="bla"> <s:HGroup> <s:Button /> <ui:AnotherComponent /> <etc /> </s:HGroup> </ui:MyCustomContainer> My problem is that i cannot access (via actionscript, eg in event handling) the components from the closed containers (and indeed their initialize event code does not run) until they have been opened at least once. Doing some digging i found that flex has some kind of performance enhancement regarding deferred creation of components. So thinking that this must the answer i set creationPolicy to "all" on the SkinnableContainer: <ui:MyCustomContainer open="false" label="bla" creationPolicy="all" > But this does not work. Any ideas? UPDATE: Full example below Revealer.as The skinnable container (taken from book Flex 4 in Action and stripped down a bit) package { import flash.events.Event; import spark.components.SkinnableContainer; import spark.components.ToggleButton; import spark.components.supportClasses.TextBase; [SkinState("open")] [SkinState("closed")] [SkinState("disabled")] //Not used: just appeasing compiler in the skin when host component is defined. [SkinState("normal")] //Not used: just appeasing compiler in the skin when host component is defined. public class Revealer extends SkinnableContainer { private var m_open:Boolean = true; private var m_label:String; [SkinPart] public var toggler:ToggleButton; [SkinPart(required="false")] public var labelDisplay:TextBase; public function Revealer() { super(); } public function get open():Boolean { return m_open; } public function set open( value:Boolean ):void { if( m_open == value ) return; m_open = value; invalidateSkinState(); invalidateProperties(); } public function get label():String { return m_label; } public function set label( value:String ):void { if( m_label == value ) return; m_label = value; if( labelDisplay != null ) labelDisplay.text = value; } override protected function getCurrentSkinState():String { return m_open ? "open" : "closed"; } override protected function partAdded( name:String, instance:Object ):void { super.partAdded( name, instance ); if(instance == toggler) { toggler.addEventListener( Event.CHANGE, toggleButtonChangeHandler ); toggler.selected = m_open; } else if( instance == labelDisplay ) { labelDisplay.text = m_label; } } private function toggleButtonChangeHandler( e:Event ):void { open = toggler.selected; } } } RevealerSkin.mxml The skin for the container <?xml version="1.0" encoding="utf-8"?> <s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" > <fx:Metadata>[HostComponent("Revealer")]</fx:Metadata> <s:states> <s:State name="open" /> <s:State name="closed" /> <s:State name="disabled" /> <!--not used: just appeasing compiler in the skin when host component is defined. --> <s:State name="normal" /> <!--not used: just appeasing compiler in the skin when host component is defined. --> </s:states> <s:Rect radiusX="5" top="0" left="0" right="0" bottom="0" minWidth="200"> <s:stroke><s:SolidColorStroke weight="2" alpha="0.5"/></s:stroke> </s:Rect> <s:Group left="0" top="0" right="0" bottom="5"> <s:ToggleButton id="toggler" label="toggle" left="5" top="5" /> </s:Group> <s:Label id="labelDisplay" left="{toggler.width + 10}" top="10" right="0" /> <s:Group id="contentGroup" includeIn="open" itemCreationPolicy="immediate" left="5" right="5" top="35" bottom="5" /> </s:Skin> MyControl.mxml A custom control placed inside the container <?xml version="1.0" encoding="utf-8"?> <s:BorderContainer xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" borderWeight="2" borderColor="black" borderAlpha="0.2" cornerRadius="2" height="25"> <fx:Script> <![CDATA[ [Bindable] public var minVal:Number; [Bindable] public var maxVal:Number; [Bindable] public var defaultVal:Number; public function get value():Number { return valueSlider.value; } ]]> </fx:Script> <s:layout> <s:VerticalLayout/> </s:layout> <s:HGroup width="100%" paddingTop="5" paddingBottom="5" paddingLeft="5" paddingRight="5"> <s:Label text="Value:" /> <s:Spacer width="100%" /> <s:HSlider id="valueSlider" minimum="{minVal}" maximum="{maxVal}" value="{defaultVal}" /> </s:HGroup> </s:BorderContainer> RevealerTest.mxml A sample app to demonstrate the problem <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:local="*" minWidth="955" minHeight="600" > <fx:Script> <![CDATA[ protected function onClick( e:MouseEvent ):void { debugArea.text += control1.value + "\n" + control2.value + "\n"; } ]]> </fx:Script> <s:HGroup> <s:VGroup> <s:Button label="click me" click="onClick(event)" /> <local:Revealer label="Group 1" skinClass="RevealerSkin" creationPolicy="all"> <local:MyControl id="control1" minVal="0" maxVal="10" defaultVal="5"/> </local:Revealer> <local:Revealer label="Group 2" open="false" skinClass="RevealerSkin" creationPolicy="all"> <local:MyControl id="control2" minVal="0" maxVal="100" defaultVal="50"/> </local:Revealer> </s:VGroup> <s:TextArea id="debugArea" /> </s:HGroup> </s:Application> Note that if you hit the click me button before opening the second container we are unable to get the value from the control in the initially collapsed group. Opening the group once allows access to the value. Collapsing the group is still ok. It's the first time that's the problem. I have added creationPolicy to the container and itemCreationPolicy to the content group in the skin but no luck! A: Actually, it's not creationPolicyyou are looking for but itemCreationPolicy. This is a property of your hidden element (contentGroup). You have to set it to immediate to access the element event if it is not displayed due to currentState.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Application selection dialog based on filetype I'm trying to create a Dialog, which will display a list of availible applications to open a given filetype. I've been looking at some question here on stackoverflow that work with the same issue, but I get lost due to lacking answer. In particular I've been looking at this question: In Android, How can I display an application selector based on file type? My follow-up question is then: * *What to do with the List<ResolveInfo>? *How can I display the availible applications with name and icon? *When the user selects an application, how can I start it based on the ResolveInfo of the selected item? A: I found a solution, that gives me a full list of applications that can open a given mimetype. It's not the best, as I would like the list to be more specific and just a few applications (e.g. if it was an URL I wanted to open only browsers would show up) but serves the purpose. Here is what I did: File file = new File( "myFileLocation.txt" ); String extension = MimeTypeMap.getFileExtensionFromUrl( file.getPath() ); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); Intent intent = new Intent(); intent.setAction( Intent.ACTION_VIEW ); intent.setDataAndType( Uri.fromFile( file ), type ); context.startActivity( intent );
{ "language": "en", "url": "https://stackoverflow.com/questions/7635764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery: Finding link best matching to current URL I have the following code which tries to add a class of selected to a link that matches the url: var pathname = window.location.pathname; $(document).ready(function () { $('ul#ui-ajax-tabs li a').each(function() { if (pathname.indexOf($(this).attr('href')) == 0) { $(this).parents('li').addClass('selected'); } }); }); 1.) So for example if I have a url like /Organisations/Journal and /Organisations/Journal/Edit a link with Organisations and Journal will show as being selected. This is fine! 2.) However sometimes I have urls like: /Organisations and /Organisations/Archived and if I have a link to the Archived then both will be selected BUT I don't want this to happen because the Organisations like doesn't have the second part of the url so shouldn't match. Can anyone help with getting this working for the second types Without breaking the first type? Also none of this can be hardcoded regex looking for keywords as the urls have lots of different parameters! Cheers EXAMPLES: If the url is /Organisations/ Or /Organisations then a link with /Organisations should be selected. If the URL is /Organisations/Journal/New then a link with /Organisations/Journal or /Organisations/Journal/New would be selected. BUT if I have a url with /Organisations/Recent and have two links: /Organisations and /Organisations/Recent then only the second should be selected! So the thing to note here is that it must have a third parameter before it should look for bits of the URL more loosly rather than an exact match. Remember it might not always be Organisations so it can't be hardcoded into the JS! A: Why dont u use if($(this).attr('href') == pathname ) instead of if (pathname.indexOf($(this).attr('href')) == 0) A: Edit: My previous solution was quite over-complicated. Updated answer and fiddle. var pathname = window.location.pathname; $(document).ready(function () { var best_distance = 999; // var to hold best distance so far var best_match = false; // var to hold best match object $('ul#ui-ajax-tabs li a').each(function() { if (pathname.indexOf($(this).attr('href')) == 0) { // we know that the link is part of our path name. // the next line calculates how many characters the path name is longer than our link overlap_penalty = pathname.replace($(this).attr('href'), '').length; if (overlap_penalty < best_distance) { // if we found a link that has less difference in length that all previous ones ... best_distance = overlap_penalty; // remember the length difference best_match = this; // remember the link } } }); if (best_match !== false) { $(best_match).closest('li').addClass('selected'); } }); The best match is calculated like so: Assume our pathname is "/foo/bar/baz/x". We have two links in question: * */foo/bar/ */foo/bar/baz This is what happens: * */foo/bar/baz/x (the first link's url is deleted from the path name pathname.replace($(this).attr('href'), '')) *"baz/x" is what remains. *The character count (length) of this remainder is 5. this is our "penalty" for the link. *We compare 5 to our previous best distance (if (overlap_penalty < best_distance)). 5 is lower (=better) than 999. *We save this (being the <a href="/foo/bar/"> DOM object) for possible later use. *The second link is handled in the same manner: */foo/bar/baz/x (the second link's url is deleted from the path name) *"/x" is what remains. *The character count of this remainder is 2. *We compare 2 to our previous best distance (being 5). 2 is lower than 5. *We save this (being the <a href="/foo/bar/baz"> DOM object) for possible later use. In the end, we just check if we found any matching link and, if so, apply addClass('selected') to its closest <li> parent. A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { var windowLocationPathname = "/HTMLPage14.htm"; // For testing purpose. //Or //var windowLocationPathname = window.location.pathname; $('ul.ui-ajax-tab').find('a[href^="' + windowLocationPathname + '"]').addClass('currentPage'); }); </script> <style type="text/css"> .ui-ajax-tab { list-style: none; } a.currentPage { color: Red; background-color: Yellow; } </style> </head> <body> <ul class="ui-ajax-tab"> <li><a href="/HTMLPage14.htm">Test 1 (/HTMLPage14.htm)</a></li> <li><a href="/HTMLPage15.htm">Test 2 (/HTMLPage15.htm)</a></li> <li><a href="/HTMLPage16.htm">Test 3 (/HTMLPage16.htm)</a></li> <li><a href="/HTMLPage17.htm">Test 4 (/HTMLPage17.htm)</a></li> </ul> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7635766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android NDK setup in Ubuntu 10.10 Hi All I am new to Android JNI. I have Ubuntu 10.10, android sdk, android-ndk-r6. All my path vaiables are set like platform-tools in sdk, android ndk path, java path etc. When I try to compile Hello-Jni sample in ndk samples folder i getting error /home/manager/Android/android-ndk-r6/samples/hello-jni/jni/hello-jni.c:17:20: error: string.h: No such file or directory /home/manager/Android/android-ndk-r6/samples/hello-jni/jni/hello-jni.c:18:17: error: jni.h: No such file or directory /home/manager/Android/android-ndk-r6/samples/hello-jni/jni/hello-jni.c:27: error: expected '=', ',', ';', 'asm' or 'attribute' before 'Java_com_example_hellojni_HelloJni_stringFromJNI' What might be the issue? I searched google which provided following link http://comments.gmane.org/gmane.comp.handhelds.android.ndk/13082 But i didnot get what symbolic links he is talking. Can any one guide me?
{ "language": "en", "url": "https://stackoverflow.com/questions/7635769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Warning while declaring versions of dependencies in POM When I specify version of my dependencies within pom.xml, there's a warning : Overrides version defined in PluginManagement. The managed version is _____. What does this mean and how do I rectify it ? A: That message would mean that the version you have specified for a plugin is different than the version "recommended" by the parent (has nothing to do with deps). You are allowed to do this. Plugin Management
{ "language": "en", "url": "https://stackoverflow.com/questions/7635775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: projects and gitolite remote on same machine I'm trying to setup a new development server that also will serve as a git remote host. Some people will be developing on the server and push to the remote and some use there own machine and push to the server when there done. We are using gitolite to facilitate those who work on there own machine so the can push and pull with there private key. The problem now is that those working on the server itself have a hard time cloning, pushing and pulling. There are always permission problems with are hard to get around. It just doest feel like this is the way it should work, so i was wondering if our setup is right or are we just using it in the wrong way (maybe we don't even need gitolite?) A: gitolite isn't really designed to also support people cloning on the local machine, since it does all of its permissions magic via ssh hooks. You could just have those working on the server clone via SSH anyways, to make sure everyone's process is paralleled. Thus, instead of the people on the local machine doing this: git clone /path/to/repo have them do this: git clone git@localhost:path/to/repo (And set up their ssh keys in gitolite as you do for everyone else.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7635784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: trend towards MVC as opposed to web forms in ASP.net? I know there will always be uses for both methodologies, but to those who work various contract jobs or attend conferences, do you see a trend towards MVC as being the preference for most ASP.net development. I understand this will involve lots of opinion on if you prefer one method to the other, but was curious. Thanks for insight you might have I apologize if this question is out of scope for the discussion. I didn't think about that when I asked it to begin with. I'm doing some dev in both and was trying to get a better idea of direction to take. No worries then if this question is deleted or just dies. A: I havn't been in the industry for very long, but from what I have noticed everyone seem to prefer MVC and all new projects we start are built using MVC3 :) A: Some people enjoy challenges, and Webforms can be very challenging for large scale applications. ;) Some people prefer to take the path of least resistance. MVC can often times be that. Yes, it's new. And as such, there's a certain amount of "oooh, shiny" mentality, but MVC really does bring a lot to the table that Webforms makes more difficult. Webforms, however, still has the drag and drop features that many people crave.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails 3 not nil I'm trying to select all records that are not null from my table using where method MyModel.where(:some_id => !nil) but it doesn't work, is there any other solution to do this? A: Use a string rather than a hash MyModel.where("some_id is not null") A: You can use: MyModel.where("some_id IS NOT NULL") A: You can do it using the Arel syntax (which has the bonus of being database independent): MyModel.where(MyModel.arel_table['some_id'].not_eq(nil))
{ "language": "en", "url": "https://stackoverflow.com/questions/7635791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How Long is the iPad Roation Duration? Pretty simple question but I can't seem to find an answer. Does anyone know the length in seconds the duration of the iPad Roation animation? I can guess that it's something short like 0.5 or 1 second long but if anyone knows an exact number it would be handy. Thanks! A: - (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration If you are trying to do something in sync use the above method and grab the duration. And ideally also initiate the animation you wish to perform there as well. Also I believe its 0.4, most standard animations are 0.3 or 0.4s. IIRC
{ "language": "en", "url": "https://stackoverflow.com/questions/7635794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Created Nested List Based on Attribute I get stuck when trying to implement recursive logic in jQuery--I don't have much practice with it. I have a simple need, which is to nest unsorted lists by class. What I have is two dynamic lists on a page (they're generated by two CAML queries). The first list will be the top level <li> and the second list will be nested. The first list has <li>s with numeric id's and the second list has <li>s with numeric classes that match the id's that they have to be nested under. i.e.: <ul> <li id="10">Parent Item 1</li> <li id="14">Parent Item 2</li> </ul> <ul> <li class="10">Child 1</li> <li class="10">Child 2</li> <li class="14">Child X</li> </ul> There will be an undetermined number of parents and child <li>s over time. Also, if it's better to use a different attr than class for the children that's fine. Ultimately I'll want to add more classes for CSS. Any help would be greatly appreciated. A: Working example here: http://jsfiddle.net/rkCKT/ Assuming this markup: <ul class="parents"> <li id="10">Parent Item 1</li> <li id="14">Parent Item 2</li> </ul> <ul class="children"> <li class="10">Child 1</li> <li class="10">Child 2</li> <li class="14">Child X</li> </ul> this would work: $(document).ready(function(){ $('ul.children li').each(function(){ probable_parent = $('ul.parents li#' + $(this).attr('class')); if (probable_parent.length) { if (!probable_parent.find('ul').length) probable_parent.append('<ul/>'); $(this).detach().appendTo(probable_parent.find('ul')); } }); }); Edit: As soon as you add any classes to the .children lis for presentational reasons, everything will be broken. For this and half a million other reasons, if your document is HTML5, I strongly suggest using proper attributes for the parent-child relationship. Ideally, the markup would look something like this: <ul class="parents"> <li data-itemid="10">Parent Item 1</li> <li data-itemid="14">Parent Item 2</li> </ul> <ul class="children"> <li data-itemid="10">Child 1</li> <li data-itemid="10">Child 2</li> <li data-itemid="14">Child X</li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/7635795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get unique values using XSLT 1.0 (Without using XSL:Key) I'm facing a typical problem while am getting the Unique list using XSLT 1.0. Sample XSLT: <xsl:if test="$tempVar = 'true'"> <xsl:variable name="filePath" select="document($mPath)" /> // Do something // I can't implement this using "Muenchian Method". // Since, I can't declare <xsl:key> inside of <xsl:if> // There is no chance to declare <xsl:key> on top. // I should get unique list from here only </xsl:if> filepath variable would contain XML as follows:- <Root> <Data id="102"> <SubData> <Info code="abc">Information 102</Info> </SubData> </Data> <Data id="78"> <SubData> <Info code="def">Information 78</Info> </SubData> </Data> <Data id="34"> <SubData> <Info code="abc">Information 34</Info> </SubData> </Data> <Data id="55"> <SubData> <Info code="xyz">Information 55</Info> </SubData> </Data> <Data id="86"> <SubData> <Info code="def">Information 86</Info> </SubData> </Data> <Data id="100"> <SubData> <Info code="xyz">Information 100</Info> </SubData> </Data> </Root> Output: Unique list of code should be abc def xyz Thanks A: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <xsl:apply-templates select="//Data[ not( */Info/@code = preceding-sibling::Data/*/Info/@code ) ]/*/Info/@code"/> </xsl:template> <xsl:template match="@*"> <xsl:value-of select="."/> <xsl:text>&#xD;</xsl:text> </xsl:template> </xsl:stylesheet> A: <xsl:if test="$tempVar = 'true'"> <xsl:variable name="filePath" select="document($mPath)" /> // Do something // I can't implement this using "Muenchian Method". // Since, I can't declare <xsl:key> inside of <xsl:if> // There is no chance to declare <xsl:key> on top. // I should get unique list from here only </xsl:if> It isn't true that one cannot use <xsl:key> and the key() function in such circumstances: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ext="http://exslt.org/common"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:key name="kcodeByVal" match="@code" use="."/> <xsl:variable name="tempVar" select="'true'"/> <xsl:variable name="vrtfFilePath"> <Root> <Data id="102"> <SubData> <Info code="abc">Information 102</Info> </SubData> </Data> <Data id="78"> <SubData> <Info code="def">Information 78</Info> </SubData> </Data> <Data id="34"> <SubData> <Info code="abc">Information 34</Info> </SubData> </Data> <Data id="55"> <SubData> <Info code="xyz">Information 55</Info> </SubData> </Data> <Data id="86"> <SubData> <Info code="def">Information 86</Info> </SubData> </Data> <Data id="100"> <SubData> <Info code="xyz">Information 100</Info> </SubData> </Data> </Root> </xsl:variable> <xsl:variable name="vfilePath" select="ext:node-set($vrtfFilePath)"/> <xsl:template match="/"> <xsl:if test="$tempVar = 'true'"> <xsl:for-each select="$vfilePath"> <xsl:for-each select= "*/*/*/Info/@code [generate-id() = generate-id(key('kcodeByVal',.)[1]) ] "> <xsl:value-of select="concat(.,' ')"/> </xsl:for-each> </xsl:for-each> </xsl:if> </xsl:template> </xsl:stylesheet> when this transformation is applied to any XML document (not used in this example), the wanted, correct result is produced: abc def xyz A: Your reason for not using the Muenchian method or xsl:key is spurious. It will work perfectly well. You have probably failed to understand that when you declare a key definition, it is not specific to one particular source document, it allows you to use the key() function against any source document.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can compiler optimizations, like ghc -O2, change the order (time or storage) of a program? I've got the feeling that the answer is yes, and that's not restricted to Haskell. For example, tail-call optimization changes memory requirements from O(n) to O(l), right? My precise concern is: in the Haskell context, what is expected to understand about compiler optimizations when reasoning about performance and size of a program? In Scheme, you can take some optimizations for granted, like TCO, given that you are using an interpreter/compiler that conforms to the specification. A: Yes, in particular GHC performs strictness analysis, which can drastically reduce space usage of a program with unintended laziness from O(n) to O(1). For example, consider this trivial program: $ cat LazySum.hs main = print $ sum [1..100000] Since sum does not assume that the addition operator is strict, (it might be used with a Num instance for which (+) is lazy), it will cause a large number of thunks to be allocated. Without optimizations enabled, strictness analysis is not performed. $ ghc --make LazySum.hs -rtsopts -fforce-recomp [1 of 1] Compiling Main ( LazySum.hs, LazySum.o ) Linking LazySum ... $ ./LazySum +RTS -s ./LazySum +RTS -s 5000050000 22,047,576 bytes allocated in the heap 18,365,440 bytes copied during GC 6,348,584 bytes maximum residency (4 sample(s)) 3,133,528 bytes maximum slop 15 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 23 collections, 0 parallel, 0.04s, 0.03s elapsed Generation 1: 4 collections, 0 parallel, 0.01s, 0.02s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 0.01s ( 0.03s elapsed) GC time 0.05s ( 0.04s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 0.06s ( 0.07s elapsed) %GC time 83.3% (58.0% elapsed) Alloc rate 2,204,757,600 bytes per MUT second Productivity 16.7% of total user, 13.7% of total elapsed However, if we compile with optimizations enabled, the strictness analyzer will determine that since we're using the addition operator for Integer, which is known to be strict, the compiler knows that it is safe to evaluate the thunks ahead of time, and so the program runs in constant space. $ ghc --make -O2 LazySum.hs -rtsopts -fforce-recomp [1 of 1] Compiling Main ( LazySum.hs, LazySum.o ) Linking LazySum ... $ ./LazySum +RTS -s ./LazySum +RTS -s 5000050000 9,702,512 bytes allocated in the heap 8,112 bytes copied during GC 27,792 bytes maximum residency (1 sample(s)) 20,320 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 18 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 0.01s ( 0.02s elapsed) GC time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 0.01s ( 0.02s elapsed) %GC time 0.0% (2.9% elapsed) Alloc rate 970,251,200 bytes per MUT second Productivity 100.0% of total user, 55.0% of total elapsed Note that we can get constant space even without optimizations, if we add the strictness ourselves: $ cat StrictSum.hs import Data.List (foldl') main = print $ foldl' (+) 0 [1..100000] $ ghc --make StrictSum.hs -rtsopts -fforce-recomp [1 of 1] Compiling Main ( StrictSum.hs, StrictSum.o ) Linking StrictSum ... $ ./StrictSum +RTS -s ./StrictSum +RTS -s 5000050000 9,702,664 bytes allocated in the heap 8,144 bytes copied during GC 27,808 bytes maximum residency (1 sample(s)) 20,304 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 18 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 0.00s ( 0.01s elapsed) GC time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 0.00s ( 0.01s elapsed) %GC time 0.0% (2.1% elapsed) Alloc rate 9,702,664,000,000 bytes per MUT second Productivity 100.0% of total user, 0.0% of total elapsed Strictness tends to be a bigger issue than tail calls, which aren't really a useful concept in Haskell, because of Haskell's evaluation model.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Java + Linked-List + Polymorphic Objects "Would you recommend inheriting off of the built in Linked List in order to customize it for my polymorphic objects? or should I build a Linked List from scratch?" A: I'm not really sure what the context is here, but I would never (well, almost never) build a Linked List from scratch. What you could consider instead of inheritance is using delegation by the way. Define an interface for your 'polymorphic objects' and simply delegate all linked list related calls to the Linked List. A: I wouldn't write your own unless you really really really have to. By "polymorphic objects" I am assuming you mean you have a class hierarchy and want to put instances of any of those classes in the list. Nothing prevents you from doing that, although the generics will place limits on the types the compiler sees, you can get around by casting as a last resort. Or you can just declare a list with no generic types, although in that case you lose all the compile-time checking you could get. For 99.9999% of cases, the default LinkedList implementation is going to be fine. It's probably a better idea to use it than roll your own, unless the default implementation is completely inadequate. If you think it might be, update your question or start a new one with very explicit details. There is probably a good way to work with the default implementation. All that said, if this is for learning, feel free to write you own linked list. Also note that anything you come up with will at best have to follow the same rules of generics/typing that the default LinkedList has. If you build your 'polymorphic objects' directly into the list, that's fine, but you have just created a really specific implementation that will only be useful for you (which might be ok). A: If you need to create your own version of LinkedList that changes the behavior of one or more methods, you should use the Decorator pattern. I would also suggest using Guava's ForwardingList class which does most of the work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to use sed to remove all double quotes within a file I have a file called file.txt. It has a number of double quotes throughout it. I want to remove all of them. I have tried sed 's/"//g' file.txt I have tried sed -s "s/^\(\(\"\(.*\)\"\)\|\('\(.*\)'\)\)\$/\\3\\5/g" file.txt Neither have worked. How can I just remove all of the double quotes in the file? A: Additional comment. Yes this works: sed 's/\"//g' infile.txt > outfile.txt (however with batch gnu sed, will just print to screen) In batch scripting (GNU SED), this was needed: sed 's/\x22//g' infile.txt > outfile.txt A: Try this: sed -i -e 's/\"//g' file.txt A: Are you sure you need to use sed? How about: tr -d "\"" A: Try prepending the doublequote with a backslash in your expresssion: sed 's/\"//g' [file name] A: For replacing in place you can also do: sed -i '' 's/\"//g' file.txt or in Linux sed -i 's/\"//g' file.txt A: You just need to escape the quote in your first example: $ sed 's/\"//g' file.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/7635807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: Setting up multiple domains for single app_id Facebook recently added the option for multiple domain support within an app. You can find the post here: https://developers.facebook.com/blog/post/570/ However, when I add the second domain to the app_domain, I get the following error: Error siteB.org must be derived from your Site URL. My site URL is: fb.siteA.com Can you add additional site URLs that are comma delimited? e.g. fb.siteA.com, www.siteB.org Thoughts? What needs to be adjusted?
{ "language": "en", "url": "https://stackoverflow.com/questions/7635822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Distribute a sqlite database with a BlackBerry application How can I deploy my application with sqlite database? A: I do not understand your question but these articles may be helpful: * *A java.net article: Getting Started with Java and SQLite on Blackberry OS 5.0 *In the BlackBerry developer knowledge base: Storing data in SQLite databases
{ "language": "en", "url": "https://stackoverflow.com/questions/7635826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Load a webpage in another webpage with jQuery using .load I'm looking for a way to load a webpage in another webpage using .load in jQuery. The instructions listed on the page weren't very clear. Let's say the domain is "example.com" and the page I'm trying to load is located at "example.com/page". A: API explains enough: http://api.jquery.com/load/ $('#result').load('/page'); Where #result is the div with id result. Inside that div, the page /page will be loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where to store methods in MVC projects In MVC3, where is the best place to store methods I am currently racking up quite a bit of code in my HomeController and feel that my methods should be seperate from the controller logic. Should I create a model with a class of "HomeControllerMethods" or something? A: Definitely do not put them inside your controllers if they are not specific to a controler and if they don't use the properties or methods of that controller. Put them some other place. Where you need to put them is up to you. I always create another project called MyApp.Infrastructure. A: Well, application architecture is your own choice which must be dictated by your conrete use cases. Try reading about three tier pattern to begin with A: Here is an answer https://codereview.stackexchange.com/questions/981/not-feeling-100-about-my-controller-design discussing a similar topic. Another great resource is www.tekpub.com I've just gone through the ASP.NET MVC3 Real World series. This series goes along at a cracking pace, and Rob uses an Infrastructure folder similar to @tugberk's advice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check for Is Not Null in VBA? Hi I have the following expression. I'm trying to say "if the second field Is Not Null". Can you help. Thanks =Iif((Fields!approved.Value = "N" & Fields!W_O_Count.Value IsNotNull), "Red", "Transparent") A: Use Not IsNull(Fields!W_O_Count.Value) So: =IIF(Fields!approved.Value = "N" & Not IsNull(Fields!W_O_Count.Value)), "Red", "Transparent") A: you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise. Not IsNull(Fields!W_O_Count.Value)
{ "language": "en", "url": "https://stackoverflow.com/questions/7635835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Django queryset excluding many to many objects Let's assume we have a model: class a(models.Model): users = models.ManyToManyField(User) # django.contrib.auth.models.User and these variables: user = request.user queryset = a.objects.all() Then I want to exclude these records from a model that contains the user in users. How can I do that? queryset.exclude(...) A: It's as simple as this: queryset.exclude(users=user)
{ "language": "en", "url": "https://stackoverflow.com/questions/7635838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Deleting from a List In this code, when I select an element from the middle of the list and delete, the elements below the selected element are also removed from "view". But they are present in the database and appear once again when the app is run. Please help me with this mistake. Thanks. DeleteController delController = new DeleteController(); delController.deleteInfo(dbId); this.jList1 = list; AbstractListModel model = (AbstractListModel) jList1.getModel(); int numberElements = model.getSize(); final String[] allElements = new String[numberElements + 1]; for (int i = 0; i < numberElements - 1; i++) { String val = (String) model.getElementAt(i); if (!dbId.equals(val)) { allElements[i] = (String) model.getElementAt(i); } } jList1.setModel(new javax.swing.AbstractListModel() { String[] strings = allElements; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); A: Use DefaultListModel. It has removeElementAt() method
{ "language": "en", "url": "https://stackoverflow.com/questions/7635840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Live checking value of textarea I have a textarea that have a id upload-message. And this jvavscript: // step-2 happens in the browser dialog $('#upload-message').change(function() { $('.step-3').removeClass('error'); $('.details').removeClass('error'); }); But how can i check this live? Now, i type in the upload message textarea. And go out of the textarea. Than the jquery function is fired. But how can i do this live? Thanks A: With .keyup: $('#upload-message').keyup(function() { $('.step-3, .details').removeClass('error'); }); However, this'll keep on running for every keypress, which in the case you provided does not make sense. You should rather bind it once with one: $('#upload-message').one('keyup', function() { $('.step-3, .details').removeClass('error'); }); ...so that this event will only fire once. A: Simply bind some code to the keyup event: $('#upload-message').keyup(function(){ //this code fires every time the user releases a key $('.step-3').removeClass('error'); $('.details').removeClass('error'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7635841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Securing cron file I've have a cron file, monthly.php and I want to prevent direct access using web browser. It should be accessible only through CPanel cron. Thanks. A: Don't put it under the webroot. Just execute it using the command line php program. A: You can use a .htaccess to deny access to it. Or you can just move it out of the htdocs or public_html directory. <Files "cron.php"> Order deny,allow Allow from name.of.this.machine Allow from another.authorized.name.net Allow from 127.0.0.1 Deny from all </Files> So it can only be requested from the server. A: If you, for some reason, need to put it in a webroot, try the following: Can PHP detect if its run from a cron job or from the command line? A: Just pass in a key to it to protect it. And don't report "Key parameter is missing" to the browser, just die() if the key is not there. And please, dont use the parameter "key", use something of your own like: http://myscript.com/monthly.php?mycomplexkeyname=ksldhfguorihgiauzsiludrfthgo45j1234134
{ "language": "en", "url": "https://stackoverflow.com/questions/7635842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Posting two games with same bundle identifier i am using game center into my app only for the leaderboard. I planned to release the app in two different mode(free and premium). Can i able to have two apps with same name and bundle identifer? if not is there is any way to do that? A: You have to change the bundle identifier. It must be unique. If you try to load one version, it will wipe the other. If you want to do two apps, just change the bundle identifier. iirc you can still use the same name for both. A: Even the correct answer is no it's not possible to use the same BundleID BUT as I assume you'd like to use the same leader board for both apps, and this is possible! From iOS 6 you can use Game Center Group and both or more apps could feed the same group leader boards or achievements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Querying the client periodically for update via sockets-Reusing ports using the Controller.java, I' implementing the run() in NetworkDiscovery.java which queries all the machine in the subnet . The active machines reply with their status. This happens at regular intervals. public class Controller { NetworkDiscovery n; public static int discoveryInterval=2000; PM pmList; List pmlist=(List) new PM(); public static void main(String[] args) throws UnknownHostException{ Timer t1=new Timer(); t1.scheduleAtFixedRate(new NetworkDiscovery(), 2000, discoveryInterval); } public class NetworkDiscovery extends TimerTask{ InetAddress controllerIP; int controllerPort; NetworkDiscovery() throws UnknownHostException { controllerIP=InetAddress.getLocalHost(); controllerPort=4455; } @Override public void run() { try { byte[] recvBuf = new byte[5000]; DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length); DatagramSocket dSock = new DatagramSocket(4445); dSock.receive(packet); //implementation related code follows **dSock.close();** } } On the client's side a similar Datagram socket is opened and objects are received/sent. The problem is that on the COntroller's side, I'm executing NetworkDiscovery's run() after a specific time interval and during the second execution it says - java.net.BindException: Address already in use Since I'm closing the Controller's socket by close(), why does it still show that this address is already being in use? How can I make sure that during the next iteration, the controller starts over fresh call of networkDiscovery? A: Perhaps the second task starts before the first was completly executed? Have you tried to insert debug messages and see if the first task was finished?
{ "language": "en", "url": "https://stackoverflow.com/questions/7635844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android switching between layout(Forms) I am fairly new to the android development platform. I am developing a small android help desk application, as a project. My problem is switching between my layouts. now there are a lot of help on the internet but could not find anything use full to my application. I have a "main.xml" layout file and a "login.xml" layout file. I can not find a proper way to switch between the two layouts. I though setting the context view to the other layout will work. but i keep on getting a force close message on my simulator setContentView(R.layout.login); So as you can see i have an login screen and as soon as the user logged in the layout needs to change to the main layout. A: In Android, you can not change the content view of the activity. However, you can create a new activity for example LoginActivity and set its content view with setContentView(R.layout.login); and then you can switch to this layout by creating an intent which will open the new activity as below. startActivity(new Intent (YourActivity.this, TheActivitytobeopened.class)); A: I have an activity with a LinearLayout. And then I dynamically add and remove views to it. LinearLayout llMain = (LinearLayout) this.findViewById(R.id.room_layout_main); roomView = new RoomView(this); llMain.addView(roomView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); //use llMain.removeView(roomView) to remove it I am pretty sure you can load views from xml but I am not sure. Hope that helps. EDIT- looks like you can load a view from xml, see here: http://www.aslingandastone.com/2011/dynamically-changing-android-views-with-xml-layouts/
{ "language": "en", "url": "https://stackoverflow.com/questions/7635848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get line number in XSLT? Is it possible to get the line number when we apply XSLT to an XML? I need to know the line number when there is a particular template match found in the XML. Is it possible to retrieve the line number? A: If you mean the line number of the node in the source document, Saxon provides this using an extension function saxon:line-number(), provided the source document is supplied via an interface (e.g. a SAX parser) that reports line numbers. There's no standard XSLT mechanism for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to store user credentials in an ASP.NET MVC website My settings is as follows: I have an MVC web application (EbWebApp) which has a service reference to an WCF service named EbServiceApp. For authentication purposes I implemented a forms authentication scenario: The user logs on to the web site, and then in turn I authenticate the user to the web service (using forms authentication) too. For this I created another web service named AuthService. Everything works just fine but when the forms authentication ticket expires for the web service I would have to relog on the user to the webservice without asking for username and password (this scenario can happen for example if I set a persistent cookie on the website for the user). I don't know how could I store the user's credentials to be available for reconnection to the web service. Any help is appreciated. A: Warning! Warning! Warning! Whenever you think "How can i store the users credentials so i can automatically log them in later?" then you are doing something very dangerous. If you can log them in later, then someone can steal those credentials. It's ALWAYS a bad idea. If the forms authentication ticket expires, then only the end user should be able to log himself back in. Otherwise, you're defeating the purpose of a ticket expiry. If you want the ticket to last longer, then just set its expiration to be longer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Store data in the internal memory not on the sd card? I've been developing a content-based app for Android and I have over 120 MB of data that i need to store on the phone. I download this data from a server when the user first runs the app. My first question is, is it ok if I store this data on the internal memory of the app using Context.getDir() method or is it better to store it on the sd card using Environment.getExternalStorageDirectory(). The problem with storing it on the sd card is that I would then have to secure this data somehow otherwise they would be accessible to every other app or person. My second question is if it's okey to store that amount of data in the internal memory of the app then are they secure there? A: For the First Question and For the Second Question If you're intend to saving files to the internal memory, you'll just need to call a method like this: FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE); If you set the Context.MODE_PRIVATE, it is not visible for other apps and even for you and user. Of course, this MODE_PRIVATE is useful only for the phone without root access. Those phones who have get rooted will have access to any folder in internal memory no matter if you set PRIVATE MODE or not. Therefore if you decide to save your files in internal memory, despite of the sizes, you need to use some kind of encryption if you think these files should be kept privately. As for the sizes, 120MB is a little bit oversized for data files saving on internal memory. The phones in the same era of Nexus One usually has 512MB internal memory, so from the user point of view, they don't like oversized app to occupy their internal memory because insufficient internal memory sometimes will cause the Android OS to stop receiving SMS and stop synchronisation. All in all, because of the root access in nearly all Android phone, it is not safe to directly save your app private data to either external or internal memory. As for your 120MB data size, I recommend you do a simple encryption and save to SD Card. Here's an excellent explanation on two storage types on saving files And here's the Saving Options from Android Developers for your reference. A: You must research on how to secure your data, cause your application data should be deployed/downloaded into the external storage sd card as an example. Cause many modern smartphones relies on the internal storage in as ram memory to run the applications. Thats why I think you shouldn't install you applicatino data in the internal storage. I learned this developing for windows ce, windows mobile similar OS devices. Thanks, A: My suggestion is in internal memory. Most of the devices should have the same storage partition shared between internal storage and SD card. Either way, you consume the same storage space. From the users' perspactive, there is no different between SD Card and internal storage except that the data in SD card could be shared in some ways which is not what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you say not equal to in Ruby? This is a much simpler example of what I'm trying to do in my program but is a similar idea. In an, if statement how do I say not equal to? Is != correct? def test vara = 1 varb = 2 if vara == 1 && varb != 3 puts "correct" else puts "false" end end A: Yes. In Ruby the not equal to operator is: != You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "64" }
Q: JAX-RS and unknown query parameters I have a Java client that calls a RESTEasy (JAX-RS) Java server. It is possible that some of my users may have a newer version of the client than the server. That client may call a resource on the server that contains query parameters that the server does not know about. Is it possible to detect this on the server side and return an error? I understand that if the client calls a URL that has not been implemented yet on the server, the client will get a 404 error, but what happens if the client passes in a query parameter that is not implemented (e.g.: ?sort_by=last_name)? A: Is it possible to detect this on the server side and return an error? Yes, you can do it. I think the easiest way is to use @Context UriInfo. You can obtain all query parameters by calling getQueryParameters() method. So you know if there are any unknown parameters and you can return error. but what happens if the client passes in a query parameter that is not implemented If you implement no special support of handling "unknown" parameters, the resource will be called and the parameter will be silently ignored. Personally I think that it's better to ignore the unknown parameters. If you just ignore them, it may help to make the API backward compatible. A: You should definitely check out the JAX-RS filters (org.apache.cxf.jaxrs.ext.RequestHandler) to intercept, validate, manipulate request, e.g. for security or validatng query parameters. If you declared all your parameters using annotations you can parse the web.xml file for the resource class names (see possible regex below) and use the full qualified class names to access the declared annotations for methods (like javax.ws.rs.GET) and method parameters (like javax.ws.rs.QueryParam) to scan all available web service resources - this way you don't have to manually add all resource classes to your filter. Store this information in static variables so you just have to parse this stuff the first time you hit your filter. In your filter you can access the org.apache.cxf.message.Message for the incoming request. The query string is easy to access - if you also want to validate form parameters and multipart names, you have to reas the message content and write it back to the message (this gets a bit nasty since you have to deal with multipart boundaries etc). To 'index' the resources I just take the HTTP method and append the path (which is then used as key to access the declared parameters. You can use the ServletContext to read the web.xml file. For extracting the resource classes this regex might be helpful String webxml = readInputStreamAsString(context.getResourceAsStream("WEB-INF/web.xml")); Pattern serviceClassesPattern = Pattern.compile("<param-name>jaxrs.serviceClasses</param-name>.*?<param-value>(.*?)</param-value>", Pattern.DOTALL | Pattern.MULTILINE);
{ "language": "en", "url": "https://stackoverflow.com/questions/7635875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What are the performance implications of disabling the lock-screen? I am working on a timer application (it's my first app to try and learn the ropes). While the timer is running, I want to offer the user the ability to prevent the screen from locking. Since the screen is always displaying something (and refreshing the clock every second), what would the performance penalty be for doing this? The only things active on the screen are the timer (black background with just the running time) and "split" and "stop" buttons? I am mostly concerned with the battery life of the phone; e.g. if this were a long-running timer job (let's say long-distance running with split times). A: I have used both an iPhone and an android for running apps in the past. The first iPhone versions couldn't 'lock' the screen because it disabled the GPS too. Leaving the screen on, even with minimal backlight, absolutely ruins battery life, because the backlight and screen-refresh operations are quite expensive. Battery life went up from ~30 minutes to ~5 hours when running with the screen off. There are some innovative solutions to this for runners, for example RunKeeper (and I'm sure most of the other ones too) has an option to fade the music out and give you updates on your stats every n minutes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ~/ not starting at app root I know this may be a basic question, but it is driving me crazy. I have an asp.net (4.0 framework) application that I have been working on. I have a masterpage in the root directory, and a secondary masterpage in a subdirectory. The secondary masterpage inherits the site master. The issue is that even though I used ~/ to describe the location of the resource ("<img src="~/Images/myImage.jpg" />) they are not loading. Using the console on firebug, I get this error: "NetworkError: 404 Not Found - http://localhost:4601/Account/~/Images/myImage.jpg" What do I need to do to correctly translate resources from masterpage to masterpage across subfolders? And what is it that I am misunderstanding about '~/'? A: Using <img src="~/Images/myImage.jpg" /> Is mixing HTML code with .Net ASP code. The tilde (~) is not something of the HTML markup and this is why it does not produce what you want. To make it works, you need to change the source with the <% %> tag that will let you add ASP code that will be translated into HTML code when processing. <img src="<%= Page.ResolveUrl("~/Images/myImage.jpg") %>" /> Inside ASP.NET tag, you should use the ResolveURL that will transform the URL into something that the HTML will be able to understand. If you do not want to use this trick, you can also use instead of the HTML img tag the ASP.NET image control. This will automatically execute the ResolveUrl <asp:Image runat="server" ID="imgHelp" ImageUrl="~/Images/myImage.jpg" /> A: <img src="<%= Page.ResolveUrl("~/Images/myImage.jpg") %>" /> or <img src="<%= Control.ResolveUrl("~/Images/myImage.jpg") %>" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7635880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create an independent HTML block? I want to know if there is some way to create an independent HTML block . For more explanation : My problem is that I have a webpage in which I allow some users can add content (may contain HTML & CSS ) I allow them to add their content inside a certain block , but sometimes their content may not be clean code , and may contain some DIVS with no end , Or even some DIV end with no starting DIV This sometimes distort my page completely Is there any way to make their content displayed independently from my parent div , so that my div is first displayed well , and then the content inside it is displayed ? I'm sorry for long message . Thanks for any trial to help A: sometimes their content may not be clean code , and may contain some DIVS with no end , Or even some DIV end with no starting DIV This sometimes distort my page completely The easiest solution for you is going to be to add the submitted content to your page inside an <iframe>. That way, it doesn't matter if the submitted HTML is invalid. If you have to worry about users possibly submitting malicious content (such as JavaScript), the problem becomes much harder: you need to sanitize the HTML. I can't tell you how to do this without knowing what server-side language you're using. A: My problem is that I have a webpage in which I allow some users can add content (may contain HTML & CSS ) I allow them to add their content inside a certain block , but sometimes their content may not be clean code , and may contain some DIVS with no end , Or even some DIV end with no starting DIV This sometimes distort my page completely If that is the problem you are trying to solve, then having some markup to say a chunk of code was independent wouldn't help: They might include the "End of independent section" code in the HTML. If you want to put the code in a page, you need to parse it, sanitise it (using a whitelist) to remove anything potentially harmful and then generate clean markup from the DOM. A: you could use Static iframes. check this out http://www.samisite.com/test-csb2nf/id43.htm A: The safest way is to restrict the tags they can submit, and validate/sanitize those that they do, similar to the way we can use markup on here. Having unchecked HTML injected into your page is asking for trouble. Failing that, good old iframe will do the trick. A: Okay, i belive there is something you can do, but it can require some time. You can use a parser to go through the users html, and get the tags and their content, and recreate the html making it clean. But, as there are a lot of tags that can be used, or even invented tags, than you can limit the tags that the user are able to use in their html. You put a legend with the acceptable tags. There are some pretty good html parsers for php, but they may break for some very bad html code, so this is why i suggest you just recreate it based on the parsing with a limited subset of acceptable tags. I know it's a difficult/time consuming solution, but this is what i have in mind
{ "language": "en", "url": "https://stackoverflow.com/questions/7635881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling client-side timeout with a Sinatra web service I'm a rank beginner with Ruby and Sinatra, but have managed to come up with a web service that works pretty well, running on Heroku. I access this web service from Salesforce.com. The HTTPRequest class that I use in Salesforce/Apex has a maximum timeout of 60s. If I hit that timeout (or, when I hit a 1 second timeout I'm using for testing purposes), I get an exception on the Salesforce side, which I can easily handle. What I'm interested in is how to handle this on the Sinatra side. If my client gets a timeout, and somehow closes the connection, is there a way to "sense" this in my Sintra app? I'd like to note client timeout, continue doing the work the app had started, and then send an email to let the user know the job had finished after the timeout. I should note that when I do get the timeout now, the Sinatra app happily finishes what it was doing, and, I'm guessing, returns the JSON data that it is supposed to. Only there's nothing on the client side to get that data. Any thoughts? A: Fun problem. As a stateless protocol, I do not believe HTTP includes a method of "sensing" when a client closes a connection. I really don't know anything about what SalesForce does, but here's some standard HTTP solutions (I'm assuming Web Sockets are out). Easiest, but prone to false positives Since you know the max timeout, time your Sinatra request. If it took longer than 60 sec, assume it timed out and send an email. Obviously this is prone to error anywhere around 59-61 seconds, and you may get some false positives and false negatives. Harder, but prone to perfection You could implement a "read receipt." Your JSON response would include a UID. If your SalesForce request doesn't timeout, send the UID back as a receipt. Then Sinatra would know everything was okay. If the Sinatra app doesn't receive the receipt within n seconds/minutes (because SalesForce timed out and you never got the UID), the Sinatra app could send an email (or whatever) after n seconds/minutes. This could be implemented several ways. The simplest probably involves a database, a script, and cron. The most difficult probably involves HTTP streaming (now trivial in Sinatra 1.3) and possibly multi-threaded or evented servers like Thin or Zbattery. I'd be happy to elaborate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }